diff --git a/make/mkdemo/jfc/Makefile b/make/mkdemo/jfc/Makefile index 768e5b8f4a81defb9a74b4d51b32dd70b6c15bc8..8eecf28597877440c3950e7b52b6ee10e8b2a2b8 100644 --- a/make/mkdemo/jfc/Makefile +++ b/make/mkdemo/jfc/Makefile @@ -39,7 +39,8 @@ SUBDIRS = \ Notepad \ SampleTree \ SwingApplet \ - TableExample + TableExample \ + TransparentRuler # Some demos aren't currently included in OpenJDK ifndef OPENJDK diff --git a/make/mkdemo/jfc/TransparentRuler/Makefile b/make/mkdemo/jfc/TransparentRuler/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..7092b875048962f0e7fb2b861a0ef674b9376f41 --- /dev/null +++ b/make/mkdemo/jfc/TransparentRuler/Makefile @@ -0,0 +1,44 @@ +# +# Copyright (c) 2011, Oracle and/or its affiliates. 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. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# +# Makefile to build the TransparentRuler demo. +# + +BUILDDIR = ../../.. +PRODUCT = demo/jfc +DEMONAME = TransparentRuler +include $(BUILDDIR)/common/Defs.gmk + +DEMO_ROOT = $(SHARE_SRC)/demo/jfc/$(DEMONAME) +DEMO_TOPFILES = ./README.txt +DEMO_MAINCLASS = transparentruler.Ruler +DEMO_DESTDIR = $(DEMODIR)/jfc/$(DEMONAME) + + +# +# Demo jar building rules. +# +include $(BUILDDIR)/common/Demo.gmk diff --git a/make/sun/javazic/tzdata/VERSION b/make/sun/javazic/tzdata/VERSION index 0b57ca90d1001d4a819d8959101154f4bccd0339..c19847f5a1183da27fcd45bc6f23451a0e1bfa1f 100644 --- a/make/sun/javazic/tzdata/VERSION +++ b/make/sun/javazic/tzdata/VERSION @@ -21,4 +21,4 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -tzdata2011d +tzdata2011e diff --git a/make/sun/javazic/tzdata/africa b/make/sun/javazic/tzdata/africa index ce560077e00498bc981e455e6651f2af1e38bfab..bea5f8157bba583b77f67a6a0377d5da4758e3b0 100644 --- a/make/sun/javazic/tzdata/africa +++ b/make/sun/javazic/tzdata/africa @@ -734,6 +734,48 @@ Zone Indian/Mayotte 3:00:56 - LMT 1911 Jul # Mamoutzou # http://www.timeanddate.com/news/time/morocco-starts-dst-2010.html # +# From Dan Abitol (2011-03-30): +# ...Rules for Africa/Casablanca are the following (24h format) +# The 3rd april 2011 at 00:00:00, [it] will be 3rd april 1:00:00 +# The 31th july 2011 at 00:59:59, [it] will be 31th July 00:00:00 +# ...Official links of change in morocco +# The change was broadcast on the FM Radio +# I ve called ANRT (telecom regulations in Morocco) at +# +212.537.71.84.00 +# +# http://www.anrt.net.ma/fr/ +# +# They said that +# +# http://www.map.ma/fr/sections/accueil/l_heure_legale_au_ma/view +# +# is the official publication to look at. +# They said that the decision was already taken. +# +# More articles in the press +# +# http://www.yabiladi.com/articles/details/5058/secret-l-heure-d-ete-maroc-lev +# +# e.html +# +# http://www.lematin.ma/Actualite/Express/Article.asp?id=148923 +# +# +# http://www.lavieeco.com/actualite/Le-Maroc-passe-sur-GMT%2B1-a-partir-de-dim +# anche-prochain-5538.html +# + +# From Petr Machata (2011-03-30): +# They have it written in English here: +# +# http://www.map.ma/eng/sections/home/morocco_to_spring_fo/view +# +# +# It says there that "Morocco will resume its standard time on July 31, +# 2011 at midnight." Now they don't say whether they mean midnight of +# wall clock time (i.e. 11pm UTC), but that's what I would assume. It has +# also been like that in the past. + # RULE NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Morocco 1939 only - Sep 12 0:00 1:00 S @@ -757,6 +799,8 @@ Rule Morocco 2009 only - Jun 1 0:00 1:00 S Rule Morocco 2009 only - Aug 21 0:00 0 - Rule Morocco 2010 only - May 2 0:00 1:00 S Rule Morocco 2010 only - Aug 8 0:00 0 - +Rule Morocco 2011 only - Apr 3 0:00 1:00 S +Rule Morocco 2011 only - Jul 31 0 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Africa/Casablanca -0:30:20 - LMT 1913 Oct 26 0:00 Morocco WE%sT 1984 Mar 16 diff --git a/make/sun/javazic/tzdata/southamerica b/make/sun/javazic/tzdata/southamerica index a11df76f6e96a20812e4eb4e3cb1958bb2733d76..7afec35d69685225b80e55dadef20ceaaf2df7a4 100644 --- a/make/sun/javazic/tzdata/southamerica +++ b/make/sun/javazic/tzdata/southamerica @@ -1193,6 +1193,19 @@ Zone America/Rio_Branco -4:31:12 - LMT 1914 # From Arthur David Olson (2011-03-02): # The emol.com article mentions a water shortage as the cause of the # postponement, which may mean that it's not a permanent change. + +# From Glenn Eychaner (2011-03-28): +# The article: +# +# http://diario.elmercurio.com/2011/03/28/_portada/_portada/noticias/7565897A-CA86-49E6-9E03-660B21A4883E.htm?id=3D{7565897A-CA86-49E6-9E03-660B21A4883E} +# +# +# In English: +# Chile's clocks will go back an hour this year on the 7th of May instead +# of this Saturday. They will go forward again the 3rd Saturday in +# August, not in October as they have since 1968. This is a pilot plan +# which will be reevaluated in 2012. + # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Chile 1927 1932 - Sep 1 0:00 1:00 S Rule Chile 1928 1932 - Apr 1 0:00 0 - @@ -1222,13 +1235,16 @@ Rule Chile 1997 only - Mar 30 3:00u 0 - Rule Chile 1998 only - Mar Sun>=9 3:00u 0 - Rule Chile 1998 only - Sep 27 4:00u 1:00 S Rule Chile 1999 only - Apr 4 3:00u 0 - -Rule Chile 1999 max - Oct Sun>=9 4:00u 1:00 S +Rule Chile 1999 2010 - Oct Sun>=9 4:00u 1:00 S +Rule Chile 2011 only - Aug Sun>=16 4:00u 1:00 S +Rule Chile 2012 max - Oct Sun>=9 4:00u 1:00 S Rule Chile 2000 2007 - Mar Sun>=9 3:00u 0 - # N.B.: the end of March 29 in Chile is March 30 in Universal time, # which is used below in specifying the transition. Rule Chile 2008 only - Mar 30 3:00u 0 - Rule Chile 2009 only - Mar Sun>=9 3:00u 0 - -Rule Chile 2010 2011 - Apr Sun>=1 3:00u 0 - +Rule Chile 2010 only - Apr Sun>=1 3:00u 0 - +Rule Chile 2011 only - May Sun>=2 3:00u 0 - Rule Chile 2012 max - Mar Sun>=9 3:00u 0 - # IATA SSIM anomalies: (1992-02) says 1992-03-14; # (1996-09) says 1998-03-08. Ignore these. diff --git a/src/share/classes/java/awt/Component.java b/src/share/classes/java/awt/Component.java index c6ab049457425abc37e99a904803712e9dfc5ce5..09df2e00ba11c32bdd9a275d83aac84b7032d58f 100644 --- a/src/share/classes/java/awt/Component.java +++ b/src/share/classes/java/awt/Component.java @@ -5821,7 +5821,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * InputMethodRequests instance. * If listener l is null, * no exception is thrown and no action is performed. - *

Refer to Refer to AWT Threading Issues for details on AWT's threading model. * * @param l the input method listener diff --git a/src/share/classes/java/lang/CharSequence.java b/src/share/classes/java/lang/CharSequence.java index 6d19f5a1830efa144d5aae25310b1a513dc8c20a..d9e65a005a1b20787d1e8025e730351ccc4e16e3 100644 --- a/src/share/classes/java/lang/CharSequence.java +++ b/src/share/classes/java/lang/CharSequence.java @@ -66,7 +66,7 @@ public interface CharSequence { * indexing.

* *

If the char value specified by the index is a - * surrogate, the surrogate + * surrogate, the surrogate * value is returned. * * @param index the index of the char value to be returned diff --git a/src/share/classes/java/lang/Character.java b/src/share/classes/java/lang/Character.java index 0289d54cdf7f245bbf425e75672194851ac8fc85..cc1dae863df8ea6a7a2d267bbac475b4a214dd0f 100644 --- a/src/share/classes/java/lang/Character.java +++ b/src/share/classes/java/lang/Character.java @@ -31,10 +31,10 @@ import java.util.HashMap; import java.util.Locale; /** - * The Character class wraps a value of the primitive - * type char in an object. An object of type - * Character contains a single field whose type is - * char. + * The {@code Character} class wraps a value of the primitive + * type {@code char} in an object. An object of type + * {@code Character} contains a single field whose type is + * {@code char}. *

* In addition, this class provides several methods for determining * a character's category (lowercase letter, digit, etc.) and for converting @@ -42,7 +42,7 @@ import java.util.Locale; *

* Character information is based on the Unicode Standard, version 6.0.0. *

- * The methods and data of class Character are defined by + * The methods and data of class {@code Character} are defined by * the information in the UnicodeData file that is part of the * Unicode Character Database maintained by the Unicode * Consortium. This file specifies various properties including name @@ -56,8 +56,8 @@ import java.util.Locale; * *

Unicode Character Representations

* - *

The char data type (and therefore the value that a - * Character object encapsulates) are based on the + *

The {@code char} data type (and therefore the value that a + * {@code Character} object encapsulates) are based on the * original Unicode specification, which defined characters as * fixed-width 16-bit entities. The Unicode standard has since been * changed to allow for characters whose representation requires more @@ -72,43 +72,43 @@ import java.util.Locale; * sometimes referred to as the Basic Multilingual Plane (BMP). * Characters whose code points are greater * than U+FFFF are called supplementary characters. The Java - * platform uses the UTF-16 representation in char arrays and - * in the String and StringBuffer classes. In + * platform uses the UTF-16 representation in {@code char} arrays and + * in the {@code String} and {@code StringBuffer} classes. In * this representation, supplementary characters are represented as a pair - * of char values, the first from the high-surrogates + * of {@code char} values, the first from the high-surrogates * range, (\uD800-\uDBFF), the second from the * low-surrogates range (\uDC00-\uDFFF). * - *

A char value, therefore, represents Basic + *

A {@code char} value, therefore, represents Basic * Multilingual Plane (BMP) code points, including the surrogate * code points, or code units of the UTF-16 encoding. An - * int value represents all Unicode code points, + * {@code int} value represents all Unicode code points, * including supplementary code points. The lower (least significant) - * 21 bits of int are used to represent Unicode code + * 21 bits of {@code int} are used to represent Unicode code * points and the upper (most significant) 11 bits must be zero. * Unless otherwise specified, the behavior with respect to - * supplementary characters and surrogate char values is + * supplementary characters and surrogate {@code char} values is * as follows: * *

* *

In the Java SE API documentation, Unicode code point is * used for character values in the range between U+0000 and U+10FFFF, * and Unicode code unit is used for 16-bit - * char values that are code units of the UTF-16 + * {@code char} values that are code units of the UTF-16 * encoding. For more information on Unicode terminology, refer to the * Unicode Glossary. * @@ -125,9 +125,8 @@ class Character implements java.io.Serializable, Comparable { * The minimum radix available for conversion to and from strings. * The constant value of this field is the smallest value permitted * for the radix argument in radix-conversion methods such as the - * digit method, the forDigit - * method, and the toString method of class - * Integer. + * {@code digit} method, the {@code forDigit} method, and the + * {@code toString} method of class {@code Integer}. * * @see Character#digit(char, int) * @see Character#forDigit(int, int) @@ -140,9 +139,8 @@ class Character implements java.io.Serializable, Comparable { * The maximum radix available for conversion to and from strings. * The constant value of this field is the largest value permitted * for the radix argument in radix-conversion methods such as the - * digit method, the forDigit - * method, and the toString method of class - * Integer. + * {@code digit} method, the {@code forDigit} method, and the + * {@code toString} method of class {@code Integer}. * * @see Character#digit(char, int) * @see Character#forDigit(int, int) @@ -153,7 +151,7 @@ class Character implements java.io.Serializable, Comparable { /** * The constant value of this field is the smallest value of type - * char, '\u0000'. + * {@code char}, {@code '\u005Cu0000'}. * * @since 1.0.2 */ @@ -161,15 +159,15 @@ class Character implements java.io.Serializable, Comparable { /** * The constant value of this field is the largest value of type - * char, '\uFFFF'. + * {@code char}, {@code '\u005CuFFFF'}. * * @since 1.0.2 */ public static final char MAX_VALUE = '\uFFFF'; /** - * The Class instance representing the primitive type - * char. + * The {@code Class} instance representing the primitive type + * {@code char}. * * @since 1.1 */ @@ -371,7 +369,7 @@ class Character implements java.io.Serializable, Comparable { /** - * Undefined bidirectional character type. Undefined char + * Undefined bidirectional character type. Undefined {@code char} * values have undefined directionality in the Unicode specification. * @since 1.4 */ @@ -495,7 +493,7 @@ class Character implements java.io.Serializable, Comparable { * The minimum value of a * * Unicode high-surrogate code unit - * in the UTF-16 encoding, constant '\uD800'. + * in the UTF-16 encoding, constant {@code '\u005CuD800'}. * A high-surrogate is also known as a leading-surrogate. * * @since 1.5 @@ -506,7 +504,7 @@ class Character implements java.io.Serializable, Comparable { * The maximum value of a * * Unicode high-surrogate code unit - * in the UTF-16 encoding, constant '\uDBFF'. + * in the UTF-16 encoding, constant {@code '\u005CuDBFF'}. * A high-surrogate is also known as a leading-surrogate. * * @since 1.5 @@ -517,7 +515,7 @@ class Character implements java.io.Serializable, Comparable { * The minimum value of a * * Unicode low-surrogate code unit - * in the UTF-16 encoding, constant '\uDC00'. + * in the UTF-16 encoding, constant {@code '\u005CuDC00'}. * A low-surrogate is also known as a trailing-surrogate. * * @since 1.5 @@ -528,7 +526,7 @@ class Character implements java.io.Serializable, Comparable { * The maximum value of a * * Unicode low-surrogate code unit - * in the UTF-16 encoding, constant '\uDFFF'. + * in the UTF-16 encoding, constant {@code '\u005CuDFFF'}. * A low-surrogate is also known as a trailing-surrogate. * * @since 1.5 @@ -537,7 +535,7 @@ class Character implements java.io.Serializable, Comparable { /** * The minimum value of a Unicode surrogate code unit in the - * UTF-16 encoding, constant '\uD800'. + * UTF-16 encoding, constant {@code '\u005CuD800'}. * * @since 1.5 */ @@ -545,7 +543,7 @@ class Character implements java.io.Serializable, Comparable { /** * The maximum value of a Unicode surrogate code unit in the - * UTF-16 encoding, constant '\uDFFF'. + * UTF-16 encoding, constant {@code '\u005CuDFFF'}. * * @since 1.5 */ @@ -582,7 +580,7 @@ class Character implements java.io.Serializable, Comparable { /** * Instances of this class represent particular subsets of the Unicode * character set. The only family of subsets defined in the - * Character class is {@link Character.UnicodeBlock}. + * {@code Character} class is {@link Character.UnicodeBlock}. * Other portions of the Java API may define other subsets for their * own purposes. * @@ -593,10 +591,10 @@ class Character implements java.io.Serializable, Comparable { private String name; /** - * Constructs a new Subset instance. + * Constructs a new {@code Subset} instance. * * @param name The name of this subset - * @exception NullPointerException if name is null + * @exception NullPointerException if name is {@code null} */ protected Subset(String name) { if (name == null) { @@ -606,10 +604,10 @@ class Character implements java.io.Serializable, Comparable { } /** - * Compares two Subset objects for equality. - * This method returns true if and only if - * this and the argument refer to the same - * object; since this method is final, this + * Compares two {@code Subset} objects for equality. + * This method returns {@code true} if and only if + * {@code this} and the argument refer to the same + * object; since this method is {@code final}, this * guarantee holds for all subclasses. */ public final boolean equals(Object obj) { @@ -618,9 +616,9 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the standard hash code as defined by the - * {@link Object#hashCode} method. This method - * is final in order to ensure that the - * equals and hashCode methods will + * {@link Object#hashCode} method. This method + * is {@code final} in order to ensure that the + * {@code equals} and {@code hashCode} methods will * be consistent in all subclasses. */ public final int hashCode() { @@ -2960,7 +2958,7 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the object representing the Unicode block containing the - * given character, or null if the character is not a + * given character, or {@code null} if the character is not a * member of a defined block. * *

Note: This method cannot handle @@ -2969,9 +2967,9 @@ class Character implements java.io.Serializable, Comparable { * supplementary characters, use the {@link #of(int)} method. * * @param c The character in question - * @return The UnicodeBlock instance representing the + * @return The {@code UnicodeBlock} instance representing the * Unicode block of which this character is a member, or - * null if the character is not a member of any + * {@code null} if the character is not a member of any * Unicode block */ public static UnicodeBlock of(char c) { @@ -2981,16 +2979,16 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the object representing the Unicode block * containing the given character (Unicode code point), or - * null if the character is not a member of a + * {@code null} if the character is not a member of a * defined block. * * @param codePoint the character (Unicode code point) in question. - * @return The UnicodeBlock instance representing the + * @return The {@code UnicodeBlock} instance representing the * Unicode block of which this character is a member, or - * null if the character is not a member of any + * {@code null} if the character is not a member of any * Unicode block * @exception IllegalArgumentException if the specified - * codePoint is an invalid Unicode code point. + * {@code codePoint} is an invalid Unicode code point. * @see Character#isValidCodePoint(int) * @since 1.5 */ @@ -3044,12 +3042,12 @@ class Character implements java.io.Serializable, Comparable { * If the Unicode Standard changes block names, both the previous and * current names will be accepted. * - * @param blockName A UnicodeBlock name. - * @return The UnicodeBlock instance identified - * by blockName - * @throws IllegalArgumentException if blockName is an + * @param blockName A {@code UnicodeBlock} name. + * @return The {@code UnicodeBlock} instance identified + * by {@code blockName} + * @throws IllegalArgumentException if {@code blockName} is an * invalid name - * @throws NullPointerException if blockName is null + * @throws NullPointerException if {@code blockName} is null * @since 1.5 */ public static final UnicodeBlock forName(String blockName) { @@ -4280,11 +4278,11 @@ class Character implements java.io.Serializable, Comparable { * the given character (Unicode code point) is assigned to. * * @param codePoint the character (Unicode code point) in question. - * @return The UnicodeScript constant representing the + * @return The {@code UnicodeScript} constant representing the * Unicode script of which this character is assigned to. * * @exception IllegalArgumentException if the specified - * codePoint is an invalid Unicode code point. + * {@code codePoint} is an invalid Unicode code point. * @see Character#isValidCodePoint(int) * */ @@ -4315,12 +4313,12 @@ class Character implements java.io.Serializable, Comparable { * case-insensitive string comparisons for script name validation. *

* - * @param scriptName A UnicodeScript name. - * @return The UnicodeScript constant identified - * by scriptName - * @throws IllegalArgumentException if scriptName is an + * @param scriptName A {@code UnicodeScript} name. + * @return The {@code UnicodeScript} constant identified + * by {@code scriptName} + * @throws IllegalArgumentException if {@code scriptName} is an * invalid name - * @throws NullPointerException if scriptName is null + * @throws NullPointerException if {@code scriptName} is null */ public static final UnicodeScript forName(String scriptName) { scriptName = scriptName.toUpperCase(Locale.ENGLISH); @@ -4333,7 +4331,7 @@ class Character implements java.io.Serializable, Comparable { } /** - * The value of the Character. + * The value of the {@code Character}. * * @serial */ @@ -4343,11 +4341,11 @@ class Character implements java.io.Serializable, Comparable { private static final long serialVersionUID = 3786198910865385080L; /** - * Constructs a newly allocated Character object that - * represents the specified char value. + * Constructs a newly allocated {@code Character} object that + * represents the specified {@code char} value. * * @param value the value to be represented by the - * Character object. + * {@code Character} object. */ public Character(char value) { this.value = value; @@ -4374,7 +4372,7 @@ class Character implements java.io.Serializable, Comparable { * frequently requested values. * * This method will always cache values in the range {@code - * '\u005Cu0000'} to {@code '\u005Cu007f'}, inclusive, and may + * '\u005Cu0000'} to {@code '\u005Cu007F'}, inclusive, and may * cache other values outside of this range. * * @param c a char value. @@ -4389,8 +4387,8 @@ class Character implements java.io.Serializable, Comparable { } /** - * Returns the value of this Character object. - * @return the primitive char value represented by + * Returns the value of this {@code Character} object. + * @return the primitive {@code char} value represented by * this object. */ public char charValue() { @@ -4409,13 +4407,13 @@ class Character implements java.io.Serializable, Comparable { /** * Compares this object against the specified object. - * The result is true if and only if the argument is not - * null and is a Character object that - * represents the same char value as this object. + * The result is {@code true} if and only if the argument is not + * {@code null} and is a {@code Character} object that + * represents the same {@code char} value as this object. * * @param obj the object to compare with. - * @return true if the objects are the same; - * false otherwise. + * @return {@code true} if the objects are the same; + * {@code false} otherwise. */ public boolean equals(Object obj) { if (obj instanceof Character) { @@ -4425,11 +4423,11 @@ class Character implements java.io.Serializable, Comparable { } /** - * Returns a String object representing this - * Character's value. The result is a string of + * Returns a {@code String} object representing this + * {@code Character}'s value. The result is a string of * length 1 whose sole component is the primitive - * char value represented by this - * Character object. + * {@code char} value represented by this + * {@code Character} object. * * @return a string representation of this object. */ @@ -4439,12 +4437,12 @@ class Character implements java.io.Serializable, Comparable { } /** - * Returns a String object representing the - * specified char. The result is a string of length - * 1 consisting solely of the specified char. + * Returns a {@code String} object representing the + * specified {@code char}. The result is a string of length + * 1 consisting solely of the specified {@code char}. * - * @param c the char to be converted - * @return the string representation of the specified char + * @param c the {@code char} to be converted + * @return the string representation of the specified {@code char} * @since 1.4 */ public static String toString(char c) { @@ -4578,7 +4576,7 @@ class Character implements java.io.Serializable, Comparable { } /** - * Determines whether the specified pair of char + * Determines whether the specified pair of {@code char} * values is a valid * * Unicode surrogate pair. @@ -4590,9 +4588,9 @@ class Character implements java.io.Serializable, Comparable { * * @param high the high-surrogate code value to be tested * @param low the low-surrogate code value to be tested - * @return true if the specified high and + * @return {@code true} if the specified high and * low-surrogate code values represent a valid surrogate pair; - * false otherwise. + * {@code false} otherwise. * @since 1.5 */ public static boolean isSurrogatePair(char high, char low) { @@ -4600,7 +4598,7 @@ class Character implements java.io.Serializable, Comparable { } /** - * Determines the number of char values needed to + * Determines the number of {@code char} values needed to * represent the specified character (Unicode code point). If the * specified character is equal to or greater than 0x10000, then * the method returns 2. Otherwise, the method returns 1. @@ -4643,23 +4641,23 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the code point at the given index of the - * CharSequence. If the char value at - * the given index in the CharSequence is in the + * {@code CharSequence}. If the {@code char} value at + * the given index in the {@code CharSequence} is in the * high-surrogate range, the following index is less than the - * length of the CharSequence, and the - * char value at the following index is in the + * length of the {@code CharSequence}, and the + * {@code char} value at the following index is in the * low-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, - * the char value at the given index is returned. + * the {@code char} value at the given index is returned. * - * @param seq a sequence of char values (Unicode code + * @param seq a sequence of {@code char} values (Unicode code * units) - * @param index the index to the char values (Unicode - * code units) in seq to be converted + * @param index the index to the {@code char} values (Unicode + * code units) in {@code seq} to be converted * @return the Unicode code point at the given index - * @exception NullPointerException if seq is null. + * @exception NullPointerException if {@code seq} is null. * @exception IndexOutOfBoundsException if the value - * index is negative or not less than + * {@code index} is negative or not less than * {@link CharSequence#length() seq.length()}. * @since 1.5 */ @@ -4678,23 +4676,23 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the code point at the given index of the - * char array. If the char value at - * the given index in the char array is in the + * {@code char} array. If the {@code char} value at + * the given index in the {@code char} array is in the * high-surrogate range, the following index is less than the - * length of the char array, and the - * char value at the following index is in the + * length of the {@code char} array, and the + * {@code char} value at the following index is in the * low-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, - * the char value at the given index is returned. + * the {@code char} value at the given index is returned. * - * @param a the char array - * @param index the index to the char values (Unicode - * code units) in the char array to be converted + * @param a the {@code char} array + * @param index the index to the {@code char} values (Unicode + * code units) in the {@code char} array to be converted * @return the Unicode code point at the given index - * @exception NullPointerException if a is null. + * @exception NullPointerException if {@code a} is null. * @exception IndexOutOfBoundsException if the value - * index is negative or not less than - * the length of the char array. + * {@code index} is negative or not less than + * the length of the {@code char} array. * @since 1.5 */ public static int codePointAt(char[] a, int index) { @@ -4703,27 +4701,27 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the code point at the given index of the - * char array, where only array elements with - * index less than limit can be used. If - * the char value at the given index in the - * char array is in the high-surrogate range, the - * following index is less than the limit, and the - * char value at the following index is in the + * {@code char} array, where only array elements with + * {@code index} less than {@code limit} can be used. If + * the {@code char} value at the given index in the + * {@code char} array is in the high-surrogate range, the + * following index is less than the {@code limit}, and the + * {@code char} value at the following index is in the * low-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, - * the char value at the given index is returned. + * the {@code char} value at the given index is returned. * - * @param a the char array - * @param index the index to the char values (Unicode - * code units) in the char array to be converted - * @param limit the index after the last array element that can be used in the - * char array + * @param a the {@code char} array + * @param index the index to the {@code char} values (Unicode + * code units) in the {@code char} array to be converted + * @param limit the index after the last array element that + * can be used in the {@code char} array * @return the Unicode code point at the given index - * @exception NullPointerException if a is null. - * @exception IndexOutOfBoundsException if the index - * argument is negative or not less than the limit - * argument, or if the limit argument is negative or - * greater than the length of the char array. + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException if the {@code index} + * argument is negative or not less than the {@code limit} + * argument, or if the {@code limit} argument is negative or + * greater than the length of the {@code char} array. * @since 1.5 */ public static int codePointAt(char[] a, int index, int limit) { @@ -4749,21 +4747,21 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the code point preceding the given index of the - * CharSequence. If the char value at - * (index - 1) in the CharSequence is in - * the low-surrogate range, (index - 2) is not - * negative, and the char value at (index - - * 2) in the CharSequence is in the + * {@code CharSequence}. If the {@code char} value at + * {@code (index - 1)} in the {@code CharSequence} is in + * the low-surrogate range, {@code (index - 2)} is not + * negative, and the {@code char} value at {@code (index - 2)} + * in the {@code CharSequence} is in the * high-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, - * the char value at (index - 1) is + * the {@code char} value at {@code (index - 1)} is * returned. * - * @param seq the CharSequence instance + * @param seq the {@code CharSequence} instance * @param index the index following the code point that should be returned * @return the Unicode code point value before the given index. - * @exception NullPointerException if seq is null. - * @exception IndexOutOfBoundsException if the index + * @exception NullPointerException if {@code seq} is null. + * @exception IndexOutOfBoundsException if the {@code index} * argument is less than 1 or greater than {@link * CharSequence#length() seq.length()}. * @since 1.5 @@ -4783,23 +4781,23 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the code point preceding the given index of the - * char array. If the char value at - * (index - 1) in the char array is in - * the low-surrogate range, (index - 2) is not - * negative, and the char value at (index - - * 2) in the char array is in the + * {@code char} array. If the {@code char} value at + * {@code (index - 1)} in the {@code char} array is in + * the low-surrogate range, {@code (index - 2)} is not + * negative, and the {@code char} value at {@code (index - 2)} + * in the {@code char} array is in the * high-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, - * the char value at (index - 1) is + * the {@code char} value at {@code (index - 1)} is * returned. * - * @param a the char array + * @param a the {@code char} array * @param index the index following the code point that should be returned * @return the Unicode code point value before the given index. - * @exception NullPointerException if a is null. - * @exception IndexOutOfBoundsException if the index + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException if the {@code index} * argument is less than 1 or greater than the length of the - * char array + * {@code char} array * @since 1.5 */ public static int codePointBefore(char[] a, int index) { @@ -4808,29 +4806,29 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the code point preceding the given index of the - * char array, where only array elements with - * index greater than or equal to start - * can be used. If the char value at (index - - * 1) in the char array is in the - * low-surrogate range, (index - 2) is not less than - * start, and the char value at - * (index - 2) in the char array is in + * {@code char} array, where only array elements with + * {@code index} greater than or equal to {@code start} + * can be used. If the {@code char} value at {@code (index - 1)} + * in the {@code char} array is in the + * low-surrogate range, {@code (index - 2)} is not less than + * {@code start}, and the {@code char} value at + * {@code (index - 2)} in the {@code char} array is in * the high-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, - * the char value at (index - 1) is + * the {@code char} value at {@code (index - 1)} is * returned. * - * @param a the char array + * @param a the {@code char} array * @param index the index following the code point that should be returned * @param start the index of the first array element in the - * char array + * {@code char} array * @return the Unicode code point value before the given index. - * @exception NullPointerException if a is null. - * @exception IndexOutOfBoundsException if the index - * argument is not greater than the start argument or - * is greater than the length of the char array, or - * if the start argument is negative or not less than - * the length of the char array. + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException if the {@code index} + * argument is not greater than the {@code start} argument or + * is greater than the length of the {@code char} array, or + * if the {@code start} argument is negative or not less than + * the length of the {@code char} array. * @since 1.5 */ public static int codePointBefore(char[] a, int index, int start) { @@ -4915,31 +4913,31 @@ class Character implements java.io.Serializable, Comparable { * Converts the specified character (Unicode code point) to its * UTF-16 representation. If the specified code point is a BMP * (Basic Multilingual Plane or Plane 0) value, the same value is - * stored in dst[dstIndex], and 1 is returned. If the + * stored in {@code dst[dstIndex]}, and 1 is returned. If the * specified code point is a supplementary character, its - * surrogate values are stored in dst[dstIndex] - * (high-surrogate) and dst[dstIndex+1] + * surrogate values are stored in {@code dst[dstIndex]} + * (high-surrogate) and {@code dst[dstIndex+1]} * (low-surrogate), and 2 is returned. * * @param codePoint the character (Unicode code point) to be converted. - * @param dst an array of char in which the - * codePoint's UTF-16 value is stored. - * @param dstIndex the start index into the dst + * @param dst an array of {@code char} in which the + * {@code codePoint}'s UTF-16 value is stored. + * @param dstIndex the start index into the {@code dst} * array where the converted value is stored. * @return 1 if the code point is a BMP code point, 2 if the * code point is a supplementary code point. * @exception IllegalArgumentException if the specified - * codePoint is not a valid Unicode code point. - * @exception NullPointerException if the specified dst is null. - * @exception IndexOutOfBoundsException if dstIndex - * is negative or not less than dst.length, or if - * dst at dstIndex doesn't have enough - * array element(s) to store the resulting char - * value(s). (If dstIndex is equal to - * dst.length-1 and the specified - * codePoint is a supplementary character, the + * {@code codePoint} is not a valid Unicode code point. + * @exception NullPointerException if the specified {@code dst} is null. + * @exception IndexOutOfBoundsException if {@code dstIndex} + * is negative or not less than {@code dst.length}, or if + * {@code dst} at {@code dstIndex} doesn't have enough + * array element(s) to store the resulting {@code char} + * value(s). (If {@code dstIndex} is equal to + * {@code dst.length-1} and the specified + * {@code codePoint} is a supplementary character, the * high-surrogate value is not stored in - * dst[dstIndex].) + * {@code dst[dstIndex]}.) * @since 1.5 */ public static int toChars(int codePoint, char[] dst, int dstIndex) { @@ -4956,18 +4954,18 @@ class Character implements java.io.Serializable, Comparable { /** * Converts the specified character (Unicode code point) to its - * UTF-16 representation stored in a char array. If + * UTF-16 representation stored in a {@code char} array. If * the specified code point is a BMP (Basic Multilingual Plane or - * Plane 0) value, the resulting char array has - * the same value as codePoint. If the specified code + * Plane 0) value, the resulting {@code char} array has + * the same value as {@code codePoint}. If the specified code * point is a supplementary code point, the resulting - * char array has the corresponding surrogate pair. + * {@code char} array has the corresponding surrogate pair. * * @param codePoint a Unicode code point - * @return a char array having - * codePoint's UTF-16 representation. + * @return a {@code char} array having + * {@code codePoint}'s UTF-16 representation. * @exception IllegalArgumentException if the specified - * codePoint is not a valid Unicode code point. + * {@code codePoint} is not a valid Unicode code point. * @since 1.5 */ public static char[] toChars(int codePoint) { @@ -4991,24 +4989,24 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the number of Unicode code points in the text range of * the specified char sequence. The text range begins at the - * specified beginIndex and extends to the - * char at index endIndex - 1. Thus the - * length (in chars) of the text range is - * endIndex-beginIndex. Unpaired surrogates within + * specified {@code beginIndex} and extends to the + * {@code char} at index {@code endIndex - 1}. Thus the + * length (in {@code char}s) of the text range is + * {@code endIndex-beginIndex}. Unpaired surrogates within * the text range count as one code point each. * * @param seq the char sequence - * @param beginIndex the index to the first char of + * @param beginIndex the index to the first {@code char} of * the text range. - * @param endIndex the index after the last char of + * @param endIndex the index after the last {@code char} of * the text range. * @return the number of Unicode code points in the specified text * range - * @exception NullPointerException if seq is null. + * @exception NullPointerException if {@code seq} is null. * @exception IndexOutOfBoundsException if the - * beginIndex is negative, or endIndex + * {@code beginIndex} is negative, or {@code endIndex} * is larger than the length of the given sequence, or - * beginIndex is larger than endIndex. + * {@code beginIndex} is larger than {@code endIndex}. * @since 1.5 */ public static int codePointCount(CharSequence seq, int beginIndex, int endIndex) { @@ -5029,21 +5027,21 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the number of Unicode code points in a subarray of the - * char array argument. The offset - * argument is the index of the first char of the - * subarray and the count argument specifies the - * length of the subarray in chars. Unpaired + * {@code char} array argument. The {@code offset} + * argument is the index of the first {@code char} of the + * subarray and the {@code count} argument specifies the + * length of the subarray in {@code char}s. Unpaired * surrogates within the subarray count as one code point each. * - * @param a the char array - * @param offset the index of the first char in the - * given char array - * @param count the length of the subarray in chars + * @param a the {@code char} array + * @param offset the index of the first {@code char} in the + * given {@code char} array + * @param count the length of the subarray in {@code char}s * @return the number of Unicode code points in the specified subarray - * @exception NullPointerException if a is null. - * @exception IndexOutOfBoundsException if offset or - * count is negative, or if offset + - * count is larger than the length of the given array. + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException if {@code offset} or + * {@code count} is negative, or if {@code offset + + * count} is larger than the length of the given array. * @since 1.5 */ public static int codePointCount(char[] a, int offset, int count) { @@ -5068,24 +5066,24 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the index within the given char sequence that is offset - * from the given index by codePointOffset + * from the given {@code index} by {@code codePointOffset} * code points. Unpaired surrogates within the text range given by - * index and codePointOffset count as + * {@code index} and {@code codePointOffset} count as * one code point each. * * @param seq the char sequence * @param index the index to be offset * @param codePointOffset the offset in code points * @return the index within the char sequence - * @exception NullPointerException if seq is null. - * @exception IndexOutOfBoundsException if index + * @exception NullPointerException if {@code seq} is null. + * @exception IndexOutOfBoundsException if {@code index} * is negative or larger then the length of the char sequence, - * or if codePointOffset is positive and the - * subsequence starting with index has fewer than - * codePointOffset code points, or if - * codePointOffset is negative and the subsequence - * before index has fewer than the absolute value - * of codePointOffset code points. + * or if {@code codePointOffset} is positive and the + * subsequence starting with {@code index} has fewer than + * {@code codePointOffset} code points, or if + * {@code codePointOffset} is negative and the subsequence + * before {@code index} has fewer than the absolute value + * of {@code codePointOffset} code points. * @since 1.5 */ public static int offsetByCodePoints(CharSequence seq, int index, @@ -5123,36 +5121,36 @@ class Character implements java.io.Serializable, Comparable { } /** - * Returns the index within the given char subarray - * that is offset from the given index by - * codePointOffset code points. The - * start and count arguments specify a - * subarray of the char array. Unpaired surrogates - * within the text range given by index and - * codePointOffset count as one code point each. + * Returns the index within the given {@code char} subarray + * that is offset from the given {@code index} by + * {@code codePointOffset} code points. The + * {@code start} and {@code count} arguments specify a + * subarray of the {@code char} array. Unpaired surrogates + * within the text range given by {@code index} and + * {@code codePointOffset} count as one code point each. * - * @param a the char array - * @param start the index of the first char of the + * @param a the {@code char} array + * @param start the index of the first {@code char} of the * subarray - * @param count the length of the subarray in chars + * @param count the length of the subarray in {@code char}s * @param index the index to be offset * @param codePointOffset the offset in code points * @return the index within the subarray - * @exception NullPointerException if a is null. + * @exception NullPointerException if {@code a} is null. * @exception IndexOutOfBoundsException - * if start or count is negative, - * or if start + count is larger than the length of + * if {@code start} or {@code count} is negative, + * or if {@code start + count} is larger than the length of * the given array, - * or if index is less than start or - * larger then start + count, - * or if codePointOffset is positive and the text range - * starting with index and ending with start - * + count - 1 has fewer than codePointOffset code + * or if {@code index} is less than {@code start} or + * larger then {@code start + count}, + * or if {@code codePointOffset} is positive and the text range + * starting with {@code index} and ending with {@code start + count - 1} + * has fewer than {@code codePointOffset} code * points, - * or if codePointOffset is negative and the text range - * starting with start and ending with index - * - 1 has fewer than the absolute value of - * codePointOffset code points. + * or if {@code codePointOffset} is negative and the text range + * starting with {@code start} and ending with {@code index - 1} + * has fewer than the absolute value of + * {@code codePointOffset} code points. * @since 1.5 */ public static int offsetByCodePoints(char[] a, int start, int count, @@ -5198,8 +5196,8 @@ class Character implements java.io.Serializable, Comparable { * Determines if the specified character is a lowercase character. *

* A character is lowercase if its general category type, provided - * by Character.getType(ch), is - * LOWERCASE_LETTER. + * by {@code Character.getType(ch)}, is + * {@code LOWERCASE_LETTER}. *

* The following are examples of lowercase characters: *

@@ -5217,8 +5215,8 @@ class Character implements java.io.Serializable, Comparable {
      * the {@link #isLowerCase(int)} method.
      *
      * @param   ch   the character to be tested.
-     * @return  true if the character is lowercase;
-     *          false otherwise.
+     * @return  {@code true} if the character is lowercase;
+     *          {@code false} otherwise.
      * @see     Character#isLowerCase(char)
      * @see     Character#isTitleCase(char)
      * @see     Character#toLowerCase(char)
@@ -5234,7 +5232,7 @@ class Character implements java.io.Serializable, Comparable {
      * 

* A character is lowercase if its general category type, provided * by {@link Character#getType getType(codePoint)}, is - * LOWERCASE_LETTER. + * {@code LOWERCASE_LETTER}. *

* The following are examples of lowercase characters: *

@@ -5247,8 +5245,8 @@ class Character implements java.io.Serializable, Comparable {
      * 

Many other Unicode characters are lowercase too. * * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is lowercase; - * false otherwise. + * @return {@code true} if the character is lowercase; + * {@code false} otherwise. * @see Character#isLowerCase(int) * @see Character#isTitleCase(int) * @see Character#toLowerCase(int) @@ -5263,7 +5261,7 @@ class Character implements java.io.Serializable, Comparable { * Determines if the specified character is an uppercase character. *

* A character is uppercase if its general category type, provided by - * Character.getType(ch), is UPPERCASE_LETTER. + * {@code Character.getType(ch)}, is {@code UPPERCASE_LETTER}. *

* The following are examples of uppercase characters: *

@@ -5281,8 +5279,8 @@ class Character implements java.io.Serializable, Comparable {
      * the {@link #isUpperCase(int)} method.
      *
      * @param   ch   the character to be tested.
-     * @return  true if the character is uppercase;
-     *          false otherwise.
+     * @return  {@code true} if the character is uppercase;
+     *          {@code false} otherwise.
      * @see     Character#isLowerCase(char)
      * @see     Character#isTitleCase(char)
      * @see     Character#toUpperCase(char)
@@ -5297,7 +5295,7 @@ class Character implements java.io.Serializable, Comparable {
      * Determines if the specified character (Unicode code point) is an uppercase character.
      * 

* A character is uppercase if its general category type, provided by - * {@link Character#getType(int) getType(codePoint)}, is UPPERCASE_LETTER. + * {@link Character#getType(int) getType(codePoint)}, is {@code UPPERCASE_LETTER}. *

* The following are examples of uppercase characters: *

@@ -5310,8 +5308,8 @@ class Character implements java.io.Serializable, Comparable {
      * 

Many other Unicode characters are uppercase too.

* * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is uppercase; - * false otherwise. + * @return {@code true} if the character is uppercase; + * {@code false} otherwise. * @see Character#isLowerCase(int) * @see Character#isTitleCase(int) * @see Character#toUpperCase(int) @@ -5326,8 +5324,8 @@ class Character implements java.io.Serializable, Comparable { * Determines if the specified character is a titlecase character. *

* A character is a titlecase character if its general - * category type, provided by Character.getType(ch), - * is TITLECASE_LETTER. + * category type, provided by {@code Character.getType(ch)}, + * is {@code TITLECASE_LETTER}. *

* Some characters look like pairs of Latin letters. For example, there * is an uppercase letter that looks like "LJ" and has a corresponding @@ -5336,12 +5334,12 @@ class Character implements java.io.Serializable, Comparable { * with initial capitals, as for a book title. *

* These are some of the Unicode characters for which this method returns - * true: + * {@code true}: *

    - *
  • LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON - *
  • LATIN CAPITAL LETTER L WITH SMALL LETTER J - *
  • LATIN CAPITAL LETTER N WITH SMALL LETTER J - *
  • LATIN CAPITAL LETTER D WITH SMALL LETTER Z + *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON} + *
  • {@code LATIN CAPITAL LETTER L WITH SMALL LETTER J} + *
  • {@code LATIN CAPITAL LETTER N WITH SMALL LETTER J} + *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z} *
*

Many other Unicode characters are titlecase too.

* @@ -5351,8 +5349,8 @@ class Character implements java.io.Serializable, Comparable { * the {@link #isTitleCase(int)} method. * * @param ch the character to be tested. - * @return true if the character is titlecase; - * false otherwise. + * @return {@code true} if the character is titlecase; + * {@code false} otherwise. * @see Character#isLowerCase(char) * @see Character#isUpperCase(char) * @see Character#toTitleCase(char) @@ -5368,7 +5366,7 @@ class Character implements java.io.Serializable, Comparable { *

* A character is a titlecase character if its general * category type, provided by {@link Character#getType(int) getType(codePoint)}, - * is TITLECASE_LETTER. + * is {@code TITLECASE_LETTER}. *

* Some characters look like pairs of Latin letters. For example, there * is an uppercase letter that looks like "LJ" and has a corresponding @@ -5377,18 +5375,18 @@ class Character implements java.io.Serializable, Comparable { * with initial capitals, as for a book title. *

* These are some of the Unicode characters for which this method returns - * true: + * {@code true}: *

    - *
  • LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON - *
  • LATIN CAPITAL LETTER L WITH SMALL LETTER J - *
  • LATIN CAPITAL LETTER N WITH SMALL LETTER J - *
  • LATIN CAPITAL LETTER D WITH SMALL LETTER Z + *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON} + *
  • {@code LATIN CAPITAL LETTER L WITH SMALL LETTER J} + *
  • {@code LATIN CAPITAL LETTER N WITH SMALL LETTER J} + *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z} *
*

Many other Unicode characters are titlecase too.

* * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is titlecase; - * false otherwise. + * @return {@code true} if the character is titlecase; + * {@code false} otherwise. * @see Character#isLowerCase(int) * @see Character#isUpperCase(int) * @see Character#toTitleCase(int) @@ -5403,20 +5401,20 @@ class Character implements java.io.Serializable, Comparable { * Determines if the specified character is a digit. *

* A character is a digit if its general category type, provided - * by Character.getType(ch), is - * DECIMAL_DIGIT_NUMBER. + * by {@code Character.getType(ch)}, is + * {@code DECIMAL_DIGIT_NUMBER}. *

* Some Unicode character ranges that contain digits: *

    - *
  • '\u0030' through '\u0039', - * ISO-LATIN-1 digits ('0' through '9') - *
  • '\u0660' through '\u0669', + *
  • {@code '\u005Cu0030'} through {@code '\u005Cu0039'}, + * ISO-LATIN-1 digits ({@code '0'} through {@code '9'}) + *
  • {@code '\u005Cu0660'} through {@code '\u005Cu0669'}, * Arabic-Indic digits - *
  • '\u06F0' through '\u06F9', + *
  • {@code '\u005Cu06F0'} through {@code '\u005Cu06F9'}, * Extended Arabic-Indic digits - *
  • '\u0966' through '\u096F', + *
  • {@code '\u005Cu0966'} through {@code '\u005Cu096F'}, * Devanagari digits - *
  • '\uFF10' through '\uFF19', + *
  • {@code '\u005CuFF10'} through {@code '\u005CuFF19'}, * Fullwidth digits *
* @@ -5428,8 +5426,8 @@ class Character implements java.io.Serializable, Comparable { * the {@link #isDigit(int)} method. * * @param ch the character to be tested. - * @return true if the character is a digit; - * false otherwise. + * @return {@code true} if the character is a digit; + * {@code false} otherwise. * @see Character#digit(char, int) * @see Character#forDigit(int, int) * @see Character#getType(char) @@ -5443,27 +5441,27 @@ class Character implements java.io.Serializable, Comparable { *

* A character is a digit if its general category type, provided * by {@link Character#getType(int) getType(codePoint)}, is - * DECIMAL_DIGIT_NUMBER. + * {@code DECIMAL_DIGIT_NUMBER}. *

* Some Unicode character ranges that contain digits: *

    - *
  • '\u0030' through '\u0039', - * ISO-LATIN-1 digits ('0' through '9') - *
  • '\u0660' through '\u0669', + *
  • {@code '\u005Cu0030'} through {@code '\u005Cu0039'}, + * ISO-LATIN-1 digits ({@code '0'} through {@code '9'}) + *
  • {@code '\u005Cu0660'} through {@code '\u005Cu0669'}, * Arabic-Indic digits - *
  • '\u06F0' through '\u06F9', + *
  • {@code '\u005Cu06F0'} through {@code '\u005Cu06F9'}, * Extended Arabic-Indic digits - *
  • '\u0966' through '\u096F', + *
  • {@code '\u005Cu0966'} through {@code '\u005Cu096F'}, * Devanagari digits - *
  • '\uFF10' through '\uFF19', + *
  • {@code '\u005CuFF10'} through {@code '\u005CuFF19'}, * Fullwidth digits *
* * Many other character ranges contain digits as well. * * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is a digit; - * false otherwise. + * @return {@code true} if the character is a digit; + * {@code false} otherwise. * @see Character#forDigit(int, int) * @see Character#getType(int) * @since 1.5 @@ -5487,8 +5485,8 @@ class Character implements java.io.Serializable, Comparable { * the {@link #isDefined(int)} method. * * @param ch the character to be tested - * @return true if the character has a defined meaning - * in Unicode; false otherwise. + * @return {@code true} if the character has a defined meaning + * in Unicode; {@code false} otherwise. * @see Character#isDigit(char) * @see Character#isLetter(char) * @see Character#isLetterOrDigit(char) @@ -5511,8 +5509,8 @@ class Character implements java.io.Serializable, Comparable { * * * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character has a defined meaning - * in Unicode; false otherwise. + * @return {@code true} if the character has a defined meaning + * in Unicode; {@code false} otherwise. * @see Character#isDigit(int) * @see Character#isLetter(int) * @see Character#isLetterOrDigit(int) @@ -5529,14 +5527,14 @@ class Character implements java.io.Serializable, Comparable { * Determines if the specified character is a letter. *

* A character is considered to be a letter if its general - * category type, provided by Character.getType(ch), + * category type, provided by {@code Character.getType(ch)}, * is any of the following: *

    - *
  • UPPERCASE_LETTER - *
  • LOWERCASE_LETTER - *
  • TITLECASE_LETTER - *
  • MODIFIER_LETTER - *
  • OTHER_LETTER + *
  • {@code UPPERCASE_LETTER} + *
  • {@code LOWERCASE_LETTER} + *
  • {@code TITLECASE_LETTER} + *
  • {@code MODIFIER_LETTER} + *
  • {@code OTHER_LETTER} *
* * Not all letters have case. Many characters are @@ -5548,8 +5546,8 @@ class Character implements java.io.Serializable, Comparable { * the {@link #isLetter(int)} method. * * @param ch the character to be tested. - * @return true if the character is a letter; - * false otherwise. + * @return {@code true} if the character is a letter; + * {@code false} otherwise. * @see Character#isDigit(char) * @see Character#isJavaIdentifierStart(char) * @see Character#isJavaLetter(char) @@ -5571,19 +5569,19 @@ class Character implements java.io.Serializable, Comparable { * category type, provided by {@link Character#getType(int) getType(codePoint)}, * is any of the following: *
    - *
  • UPPERCASE_LETTER - *
  • LOWERCASE_LETTER - *
  • TITLECASE_LETTER - *
  • MODIFIER_LETTER - *
  • OTHER_LETTER + *
  • {@code UPPERCASE_LETTER} + *
  • {@code LOWERCASE_LETTER} + *
  • {@code TITLECASE_LETTER} + *
  • {@code MODIFIER_LETTER} + *
  • {@code OTHER_LETTER} *
* * Not all letters have case. Many characters are * letters but are neither uppercase nor lowercase nor titlecase. * * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is a letter; - * false otherwise. + * @return {@code true} if the character is a letter; + * {@code false} otherwise. * @see Character#isDigit(int) * @see Character#isJavaIdentifierStart(int) * @see Character#isLetterOrDigit(int) @@ -5606,9 +5604,9 @@ class Character implements java.io.Serializable, Comparable { * Determines if the specified character is a letter or digit. *

* A character is considered to be a letter or digit if either - * Character.isLetter(char ch) or - * Character.isDigit(char ch) returns - * true for the character. + * {@code Character.isLetter(char ch)} or + * {@code Character.isDigit(char ch)} returns + * {@code true} for the character. * *

Note: This method cannot handle supplementary characters. To support @@ -5616,8 +5614,8 @@ class Character implements java.io.Serializable, Comparable { * the {@link #isLetterOrDigit(int)} method. * * @param ch the character to be tested. - * @return true if the character is a letter or digit; - * false otherwise. + * @return {@code true} if the character is a letter or digit; + * {@code false} otherwise. * @see Character#isDigit(char) * @see Character#isJavaIdentifierPart(char) * @see Character#isJavaLetter(char) @@ -5636,11 +5634,11 @@ class Character implements java.io.Serializable, Comparable { * A character is considered to be a letter or digit if either * {@link #isLetter(int) isLetter(codePoint)} or * {@link #isDigit(int) isDigit(codePoint)} returns - * true for the character. + * {@code true} for the character. * * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is a letter or digit; - * false otherwise. + * @return {@code true} if the character is a letter or digit; + * {@code false} otherwise. * @see Character#isDigit(int) * @see Character#isJavaIdentifierPart(int) * @see Character#isLetter(int) @@ -5664,15 +5662,15 @@ class Character implements java.io.Serializable, Comparable { * A character may start a Java identifier if and only if * one of the following is true: *

    - *
  • {@link #isLetter(char) isLetter(ch)} returns true - *
  • {@link #getType(char) getType(ch)} returns LETTER_NUMBER - *
  • ch is a currency symbol (such as "$") - *
  • ch is a connecting punctuation character (such as "_"). + *
  • {@link #isLetter(char) isLetter(ch)} returns {@code true} + *
  • {@link #getType(char) getType(ch)} returns {@code LETTER_NUMBER} + *
  • {@code ch} is a currency symbol (such as {@code '$'}) + *
  • {@code ch} is a connecting punctuation character (such as {@code '_'}). *
* * @param ch the character to be tested. - * @return true if the character may start a Java - * identifier; false otherwise. + * @return {@code true} if the character may start a Java + * identifier; {@code false} otherwise. * @see Character#isJavaLetterOrDigit(char) * @see Character#isJavaIdentifierStart(char) * @see Character#isJavaIdentifierPart(char) @@ -5695,19 +5693,19 @@ class Character implements java.io.Serializable, Comparable { * of the following are true: *
    *
  • it is a letter - *
  • it is a currency symbol (such as '$') - *
  • it is a connecting punctuation character (such as '_') + *
  • it is a currency symbol (such as {@code '$'}) + *
  • it is a connecting punctuation character (such as {@code '_'}) *
  • it is a digit *
  • it is a numeric letter (such as a Roman numeral character) *
  • it is a combining mark *
  • it is a non-spacing mark - *
  • isIdentifierIgnorable returns - * true for the character. + *
  • {@code isIdentifierIgnorable} returns + * {@code true} for the character. *
* * @param ch the character to be tested. - * @return true if the character may be part of a - * Java identifier; false otherwise. + * @return {@code true} if the character may be part of a + * Java identifier; {@code false} otherwise. * @see Character#isJavaLetter(char) * @see Character#isJavaIdentifierStart(char) * @see Character#isJavaIdentifierPart(char) @@ -5730,10 +5728,10 @@ class Character implements java.io.Serializable, Comparable { * A character may start a Java identifier if and only if * one of the following conditions is true: *
    - *
  • {@link #isLetter(char) isLetter(ch)} returns true - *
  • {@link #getType(char) getType(ch)} returns LETTER_NUMBER - *
  • ch is a currency symbol (such as "$") - *
  • ch is a connecting punctuation character (such as "_"). + *
  • {@link #isLetter(char) isLetter(ch)} returns {@code true} + *
  • {@link #getType(char) getType(ch)} returns {@code LETTER_NUMBER} + *
  • {@code ch} is a currency symbol (such as {@code '$'}) + *
  • {@code ch} is a connecting punctuation character (such as {@code '_'}). *
* *

Note: This method cannot handle { * the {@link #isJavaIdentifierStart(int)} method. * * @param ch the character to be tested. - * @return true if the character may start a Java identifier; - * false otherwise. + * @return {@code true} if the character may start a Java identifier; + * {@code false} otherwise. * @see Character#isJavaIdentifierPart(char) * @see Character#isLetter(char) * @see Character#isUnicodeIdentifierStart(char) @@ -5762,17 +5760,17 @@ class Character implements java.io.Serializable, Comparable { * one of the following conditions is true: *

* * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character may start a Java identifier; - * false otherwise. + * @return {@code true} if the character may start a Java identifier; + * {@code false} otherwise. * @see Character#isJavaIdentifierPart(int) * @see Character#isLetter(int) * @see Character#isUnicodeIdentifierStart(int) @@ -5791,14 +5789,14 @@ class Character implements java.io.Serializable, Comparable { * are true: *
    *
  • it is a letter - *
  • it is a currency symbol (such as '$') - *
  • it is a connecting punctuation character (such as '_') + *
  • it is a currency symbol (such as {@code '$'}) + *
  • it is a connecting punctuation character (such as {@code '_'}) *
  • it is a digit *
  • it is a numeric letter (such as a Roman numeral character) *
  • it is a combining mark *
  • it is a non-spacing mark - *
  • isIdentifierIgnorable returns - * true for the character + *
  • {@code isIdentifierIgnorable} returns + * {@code true} for the character *
* *

Note: This method cannot handle { * the {@link #isJavaIdentifierPart(int)} method. * * @param ch the character to be tested. - * @return true if the character may be part of a - * Java identifier; false otherwise. + * @return {@code true} if the character may be part of a + * Java identifier; {@code false} otherwise. * @see Character#isIdentifierIgnorable(char) * @see Character#isJavaIdentifierStart(char) * @see Character#isLetterOrDigit(char) @@ -5828,20 +5826,20 @@ class Character implements java.io.Serializable, Comparable { * are true: *

* * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character may be part of a - * Java identifier; false otherwise. + * @return {@code true} if the character may be part of a + * Java identifier; {@code false} otherwise. * @see Character#isIdentifierIgnorable(int) * @see Character#isJavaIdentifierStart(int) * @see Character#isLetterOrDigit(int) @@ -5860,9 +5858,9 @@ class Character implements java.io.Serializable, Comparable { * A character may start a Unicode identifier if and only if * one of the following conditions is true: *
    - *
  • {@link #isLetter(char) isLetter(ch)} returns true + *
  • {@link #isLetter(char) isLetter(ch)} returns {@code true} *
  • {@link #getType(char) getType(ch)} returns - * LETTER_NUMBER. + * {@code LETTER_NUMBER}. *
* *

Note: This method cannot handle { * the {@link #isUnicodeIdentifierStart(int)} method. * * @param ch the character to be tested. - * @return true if the character may start a Unicode - * identifier; false otherwise. + * @return {@code true} if the character may start a Unicode + * identifier; {@code false} otherwise. * @see Character#isJavaIdentifierStart(char) * @see Character#isLetter(char) * @see Character#isUnicodeIdentifierPart(char) @@ -5890,13 +5888,13 @@ class Character implements java.io.Serializable, Comparable { * one of the following conditions is true: *

* @param codePoint the character (Unicode code point) to be tested. - * @return true if the character may start a Unicode - * identifier; false otherwise. + * @return {@code true} if the character may start a Unicode + * identifier; {@code false} otherwise. * @see Character#isJavaIdentifierStart(int) * @see Character#isLetter(int) * @see Character#isUnicodeIdentifierPart(int) @@ -5914,13 +5912,13 @@ class Character implements java.io.Serializable, Comparable { * one of the following statements is true: *
    *
  • it is a letter - *
  • it is a connecting punctuation character (such as '_') + *
  • it is a connecting punctuation character (such as {@code '_'}) *
  • it is a digit *
  • it is a numeric letter (such as a Roman numeral character) *
  • it is a combining mark *
  • it is a non-spacing mark - *
  • isIdentifierIgnorable returns - * true for this character. + *
  • {@code isIdentifierIgnorable} returns + * {@code true} for this character. *
* *

Note: This method cannot handle { * the {@link #isUnicodeIdentifierPart(int)} method. * * @param ch the character to be tested. - * @return true if the character may be part of a - * Unicode identifier; false otherwise. + * @return {@code true} if the character may be part of a + * Unicode identifier; {@code false} otherwise. * @see Character#isIdentifierIgnorable(char) * @see Character#isJavaIdentifierPart(char) * @see Character#isLetterOrDigit(char) @@ -5949,17 +5947,17 @@ class Character implements java.io.Serializable, Comparable { * one of the following statements is true: *

* @param codePoint the character (Unicode code point) to be tested. - * @return true if the character may be part of a - * Unicode identifier; false otherwise. + * @return {@code true} if the character may be part of a + * Unicode identifier; {@code false} otherwise. * @see Character#isIdentifierIgnorable(int) * @see Character#isJavaIdentifierPart(int) * @see Character#isLetterOrDigit(int) @@ -5979,12 +5977,12 @@ class Character implements java.io.Serializable, Comparable { *
    *
  • ISO control characters that are not whitespace *
      - *
    • '\u0000' through '\u0008' - *
    • '\u000E' through '\u001B' - *
    • '\u007F' through '\u009F' + *
    • {@code '\u005Cu0000'} through {@code '\u005Cu0008'} + *
    • {@code '\u005Cu000E'} through {@code '\u005Cu001B'} + *
    • {@code '\u005Cu007F'} through {@code '\u005Cu009F'} *
    * - *
  • all characters that have the FORMAT general + *
  • all characters that have the {@code FORMAT} general * category value *
* @@ -5994,9 +5992,9 @@ class Character implements java.io.Serializable, Comparable { * the {@link #isIdentifierIgnorable(int)} method. * * @param ch the character to be tested. - * @return true if the character is an ignorable control + * @return {@code true} if the character is an ignorable control * character that may be part of a Java or Unicode identifier; - * false otherwise. + * {@code false} otherwise. * @see Character#isJavaIdentifierPart(char) * @see Character#isUnicodeIdentifierPart(char) * @since 1.1 @@ -6014,19 +6012,19 @@ class Character implements java.io.Serializable, Comparable { *
    *
  • ISO control characters that are not whitespace *
      - *
    • '\u0000' through '\u0008' - *
    • '\u000E' through '\u001B' - *
    • '\u007F' through '\u009F' + *
    • {@code '\u005Cu0000'} through {@code '\u005Cu0008'} + *
    • {@code '\u005Cu000E'} through {@code '\u005Cu001B'} + *
    • {@code '\u005Cu007F'} through {@code '\u005Cu009F'} *
    * - *
  • all characters that have the FORMAT general + *
  • all characters that have the {@code FORMAT} general * category value *
* * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is an ignorable control + * @return {@code true} if the character is an ignorable control * character that may be part of a Java or Unicode identifier; - * false otherwise. + * {@code false} otherwise. * @see Character#isJavaIdentifierPart(int) * @see Character#isUnicodeIdentifierPart(int) * @since 1.5 @@ -6040,16 +6038,16 @@ class Character implements java.io.Serializable, Comparable { * mapping information from the UnicodeData file. *

* Note that - * Character.isLowerCase(Character.toLowerCase(ch)) - * does not always return true for some ranges of + * {@code Character.isLowerCase(Character.toLowerCase(ch))} + * does not always return {@code true} for some ranges of * characters, particularly those that are symbols or ideographs. * *

In general, {@link String#toLowerCase()} should be used to map - * characters to lowercase. String case mapping methods - * have several benefits over Character case mapping methods. - * String case mapping methods can perform locale-sensitive + * characters to lowercase. {@code String} case mapping methods + * have several benefits over {@code Character} case mapping methods. + * {@code String} case mapping methods can perform locale-sensitive * mappings, context-sensitive mappings, and 1:M character mappings, whereas - * the Character case mapping methods cannot. + * the {@code Character} case mapping methods cannot. * *

Note: This method cannot handle supplementary characters. To support @@ -6072,16 +6070,16 @@ class Character implements java.io.Serializable, Comparable { * file. * *

Note that - * Character.isLowerCase(Character.toLowerCase(codePoint)) - * does not always return true for some ranges of + * {@code Character.isLowerCase(Character.toLowerCase(codePoint))} + * does not always return {@code true} for some ranges of * characters, particularly those that are symbols or ideographs. * *

In general, {@link String#toLowerCase()} should be used to map - * characters to lowercase. String case mapping methods - * have several benefits over Character case mapping methods. - * String case mapping methods can perform locale-sensitive + * characters to lowercase. {@code String} case mapping methods + * have several benefits over {@code Character} case mapping methods. + * {@code String} case mapping methods can perform locale-sensitive * mappings, context-sensitive mappings, and 1:M character mappings, whereas - * the Character case mapping methods cannot. + * the {@code Character} case mapping methods cannot. * * @param codePoint the character (Unicode code point) to be converted. * @return the lowercase equivalent of the character (Unicode code @@ -6100,16 +6098,16 @@ class Character implements java.io.Serializable, Comparable { * information from the UnicodeData file. *

* Note that - * Character.isUpperCase(Character.toUpperCase(ch)) - * does not always return true for some ranges of + * {@code Character.isUpperCase(Character.toUpperCase(ch))} + * does not always return {@code true} for some ranges of * characters, particularly those that are symbols or ideographs. * *

In general, {@link String#toUpperCase()} should be used to map - * characters to uppercase. String case mapping methods - * have several benefits over Character case mapping methods. - * String case mapping methods can perform locale-sensitive + * characters to uppercase. {@code String} case mapping methods + * have several benefits over {@code Character} case mapping methods. + * {@code String} case mapping methods can perform locale-sensitive * mappings, context-sensitive mappings, and 1:M character mappings, whereas - * the Character case mapping methods cannot. + * the {@code Character} case mapping methods cannot. * *

Note: This method cannot handle supplementary characters. To support @@ -6132,16 +6130,16 @@ class Character implements java.io.Serializable, Comparable { * file. * *

Note that - * Character.isUpperCase(Character.toUpperCase(codePoint)) - * does not always return true for some ranges of + * {@code Character.isUpperCase(Character.toUpperCase(codePoint))} + * does not always return {@code true} for some ranges of * characters, particularly those that are symbols or ideographs. * *

In general, {@link String#toUpperCase()} should be used to map - * characters to uppercase. String case mapping methods - * have several benefits over Character case mapping methods. - * String case mapping methods can perform locale-sensitive + * characters to uppercase. {@code String} case mapping methods + * have several benefits over {@code Character} case mapping methods. + * {@code String} case mapping methods can perform locale-sensitive * mappings, context-sensitive mappings, and 1:M character mappings, whereas - * the Character case mapping methods cannot. + * the {@code Character} case mapping methods cannot. * * @param codePoint the character (Unicode code point) to be converted. * @return the uppercase equivalent of the character, if any; @@ -6161,13 +6159,13 @@ class Character implements java.io.Serializable, Comparable { * explicit titlecase mapping and is not itself a titlecase char * according to UnicodeData, then the uppercase mapping is * returned as an equivalent titlecase mapping. If the - * char argument is already a titlecase - * char, the same char value will be + * {@code char} argument is already a titlecase + * {@code char}, the same {@code char} value will be * returned. *

* Note that - * Character.isTitleCase(Character.toTitleCase(ch)) - * does not always return true for some ranges of + * {@code Character.isTitleCase(Character.toTitleCase(ch))} + * does not always return {@code true} for some ranges of * characters. * *

Note: This method cannot handle { * returned. * *

Note that - * Character.isTitleCase(Character.toTitleCase(codePoint)) - * does not always return true for some ranges of + * {@code Character.isTitleCase(Character.toTitleCase(codePoint))} + * does not always return {@code true} for some ranges of * characters. * * @param codePoint the character (Unicode code point) to be converted. @@ -6215,28 +6213,40 @@ class Character implements java.io.Serializable, Comparable { } /** - * Returns the numeric value of the character ch in the + * Returns the numeric value of the character {@code ch} in the * specified radix. *

- * If the radix is not in the range MIN_RADIX <= - * radix <= MAX_RADIX or if the - * value of ch is not a valid digit in the specified - * radix, -1 is returned. A character is a valid digit + * If the radix is not in the range {@code MIN_RADIX} ≤ + * {@code radix} ≤ {@code MAX_RADIX} or if the + * value of {@code ch} is not a valid digit in the specified + * radix, {@code -1} is returned. A character is a valid digit * if at least one of the following is true: *

* @@ -6260,25 +6270,39 @@ class Character implements java.io.Serializable, Comparable { * Returns the numeric value of the specified character (Unicode * code point) in the specified radix. * - *

If the radix is not in the range MIN_RADIX <= - * radix <= MAX_RADIX or if the + *

If the radix is not in the range {@code MIN_RADIX} ≤ + * {@code radix} ≤ {@code MAX_RADIX} or if the * character is not a valid digit in the specified - * radix, -1 is returned. A character is a valid digit + * radix, {@code -1} is returned. A character is a valid digit * if at least one of the following is true: *

    - *
  • The method {@link #isDigit(int) isDigit(codePoint)} is true of the character + *
  • The method {@link #isDigit(int) isDigit(codePoint)} is {@code true} of the character * and the Unicode decimal digit value of the character (or its * single-character decomposition) is less than the specified radix. * In this case the decimal digit value is returned. *
  • The character is one of the uppercase Latin letters - * 'A' through 'Z' and its code is less than - * radix + 'A' - 10. - * In this case, ch - 'A' + 10 + * {@code 'A'} through {@code 'Z'} and its code is less than + * {@code radix + 'A' - 10}. + * In this case, {@code codePoint - 'A' + 10} * is returned. *
  • The character is one of the lowercase Latin letters - * 'a' through 'z' and its code is less than - * radix + 'a' - 10. - * In this case, ch - 'a' + 10 + * {@code 'a'} through {@code 'z'} and its code is less than + * {@code radix + 'a' - 10}. + * In this case, {@code codePoint - 'a' + 10} + * is returned. + *
  • The character is one of the fullwidth uppercase Latin letters A + * ({@code '\u005CuFF21'}) through Z ({@code '\u005CuFF3A'}) + * and its code is less than + * {@code radix + '\u005CuFF21' - 10}. + * In this case, + * {@code codePoint - '\u005CuFF21' + 10} + * is returned. + *
  • The character is one of the fullwidth lowercase Latin letters a + * ({@code '\u005CuFF41'}) through z ({@code '\u005CuFF5A'}) + * and its code is less than + * {@code radix + '\u005CuFF41'- 10}. + * In this case, + * {@code codePoint - '\u005CuFF41' + 10} * is returned. *
* @@ -6295,19 +6319,19 @@ class Character implements java.io.Serializable, Comparable { } /** - * Returns the int value that the specified Unicode + * Returns the {@code int} value that the specified Unicode * character represents. For example, the character - * '\u216C' (the roman numeral fifty) will return + * {@code '\u005Cu216C'} (the roman numeral fifty) will return * an int with a value of 50. *

- * The letters A-Z in their uppercase ('\u0041' through - * '\u005A'), lowercase - * ('\u0061' through '\u007A'), and - * full width variant ('\uFF21' through - * '\uFF3A' and '\uFF41' through - * '\uFF5A') forms have numeric values from 10 + * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through + * {@code '\u005Cu005A'}), lowercase + * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and + * full width variant ({@code '\u005CuFF21'} through + * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through + * {@code '\u005CuFF5A'}) forms have numeric values from 10 * through 35. This is independent of the Unicode specification, - * which does not assign numeric values to these char + * which does not assign numeric values to these {@code char} * values. *

* If the character does not have a numeric value, then -1 is returned. @@ -6321,7 +6345,7 @@ class Character implements java.io.Serializable, Comparable { * the {@link #getNumericValue(int)} method. * * @param ch the character to be converted. - * @return the numeric value of the character, as a nonnegative int + * @return the numeric value of the character, as a nonnegative {@code int} * value; -2 if the character has a numeric value that is not a * nonnegative integer; -1 if the character has no numeric value. * @see Character#forDigit(int, int) @@ -6333,19 +6357,19 @@ class Character implements java.io.Serializable, Comparable { } /** - * Returns the int value that the specified + * Returns the {@code int} value that the specified * character (Unicode code point) represents. For example, the character - * '\u216C' (the Roman numeral fifty) will return - * an int with a value of 50. + * {@code '\u005Cu216C'} (the Roman numeral fifty) will return + * an {@code int} with a value of 50. *

- * The letters A-Z in their uppercase ('\u0041' through - * '\u005A'), lowercase - * ('\u0061' through '\u007A'), and - * full width variant ('\uFF21' through - * '\uFF3A' and '\uFF41' through - * '\uFF5A') forms have numeric values from 10 + * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through + * {@code '\u005Cu005A'}), lowercase + * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and + * full width variant ({@code '\u005CuFF21'} through + * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through + * {@code '\u005CuFF5A'}) forms have numeric values from 10 * through 35. This is independent of the Unicode specification, - * which does not assign numeric values to these char + * which does not assign numeric values to these {@code char} * values. *

* If the character does not have a numeric value, then -1 is returned. @@ -6354,7 +6378,7 @@ class Character implements java.io.Serializable, Comparable { * is returned. * * @param codePoint the character (Unicode code point) to be converted. - * @return the numeric value of the character, as a nonnegative int + * @return the numeric value of the character, as a nonnegative {@code int} * value; -2 if the character has a numeric value that is not a * nonnegative integer; -1 if the character has no numeric value. * @see Character#forDigit(int, int) @@ -6367,24 +6391,24 @@ class Character implements java.io.Serializable, Comparable { /** * Determines if the specified character is ISO-LATIN-1 white space. - * This method returns true for the following five + * This method returns {@code true} for the following five * characters only: * - * - * - * - * - * - * - * - * - * - * + * + * + * + * + * + * + * + * + * + * *
'\t' U+0009HORIZONTAL TABULATION
'\n' U+000ANEW LINE
'\f' U+000CFORM FEED
'\r' U+000DCARRIAGE RETURN
' ' U+0020SPACE
{@code '\t'} {@code U+0009}{@code HORIZONTAL TABULATION}
{@code '\n'} {@code U+000A}{@code NEW LINE}
{@code '\f'} {@code U+000C}{@code FORM FEED}
{@code '\r'} {@code U+000D}{@code CARRIAGE RETURN}
{@code ' '} {@code U+0020}{@code SPACE}
* * @param ch the character to be tested. - * @return true if the character is ISO-LATIN-1 white - * space; false otherwise. + * @return {@code true} if the character is ISO-LATIN-1 white + * space; {@code false} otherwise. * @see Character#isSpaceChar(char) * @see Character#isWhitespace(char) * @deprecated Replaced by isWhitespace(char). @@ -6407,9 +6431,9 @@ class Character implements java.io.Serializable, Comparable { * method returns true if the character's general category type is any of * the following: *

    - *
  • SPACE_SEPARATOR - *
  • LINE_SEPARATOR - *
  • PARAGRAPH_SEPARATOR + *
  • {@code SPACE_SEPARATOR} + *
  • {@code LINE_SEPARATOR} + *
  • {@code PARAGRAPH_SEPARATOR} *
* *

Note: This method cannot handle { * the {@link #isSpaceChar(int)} method. * * @param ch the character to be tested. - * @return true if the character is a space character; - * false otherwise. + * @return {@code true} if the character is a space character; + * {@code false} otherwise. * @see Character#isWhitespace(char) * @since 1.1 */ @@ -6441,8 +6465,8 @@ class Character implements java.io.Serializable, Comparable { * * * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is a space character; - * false otherwise. + * @return {@code true} if the character is a space character; + * {@code false} otherwise. * @see Character#isWhitespace(int) * @since 1.5 */ @@ -6458,19 +6482,19 @@ class Character implements java.io.Serializable, Comparable { * A character is a Java whitespace character if and only if it satisfies * one of the following criteria: *

* *

Note: This method cannot handle { * the {@link #isWhitespace(int)} method. * * @param ch the character to be tested. - * @return true if the character is a Java whitespace - * character; false otherwise. + * @return {@code true} if the character is a Java whitespace + * character; {@code false} otherwise. * @see Character#isSpaceChar(char) * @since 1.1 */ @@ -6496,23 +6520,23 @@ class Character implements java.io.Serializable, Comparable { *

*

* * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is a Java whitespace - * character; false otherwise. + * @return {@code true} if the character is a Java whitespace + * character; {@code false} otherwise. * @see Character#isSpaceChar(int) * @since 1.5 */ @@ -6523,9 +6547,9 @@ class Character implements java.io.Serializable, Comparable { /** * Determines if the specified character is an ISO control * character. A character is considered to be an ISO control - * character if its code is in the range '\u0000' - * through '\u001F' or in the range - * '\u007F' through '\u009F'. + * character if its code is in the range {@code '\u005Cu0000'} + * through {@code '\u005Cu001F'} or in the range + * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}. * *

Note: This method cannot handle supplementary characters. To support @@ -6533,8 +6557,8 @@ class Character implements java.io.Serializable, Comparable { * the {@link #isISOControl(int)} method. * * @param ch the character to be tested. - * @return true if the character is an ISO control character; - * false otherwise. + * @return {@code true} if the character is an ISO control character; + * {@code false} otherwise. * * @see Character#isSpaceChar(char) * @see Character#isWhitespace(char) @@ -6547,13 +6571,13 @@ class Character implements java.io.Serializable, Comparable { /** * Determines if the referenced character (Unicode code point) is an ISO control * character. A character is considered to be an ISO control - * character if its code is in the range '\u0000' - * through '\u001F' or in the range - * '\u007F' through '\u009F'. + * character if its code is in the range {@code '\u005Cu0000'} + * through {@code '\u005Cu001F'} or in the range + * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}. * * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is an ISO control character; - * false otherwise. + * @return {@code true} if the character is an ISO control character; + * {@code false} otherwise. * @see Character#isSpaceChar(int) * @see Character#isWhitespace(int) * @since 1.5 @@ -6575,7 +6599,7 @@ class Character implements java.io.Serializable, Comparable { * the {@link #getType(int)} method. * * @param ch the character to be tested. - * @return a value of type int representing the + * @return a value of type {@code int} representing the * character's general category. * @see Character#COMBINING_SPACING_MARK * @see Character#CONNECTOR_PUNCTUATION @@ -6617,7 +6641,7 @@ class Character implements java.io.Serializable, Comparable { * Returns a value indicating a character's general category. * * @param codePoint the character (Unicode code point) to be tested. - * @return a value of type int representing the + * @return a value of type {@code int} representing the * character's general category. * @see Character#COMBINING_SPACING_MARK COMBINING_SPACING_MARK * @see Character#CONNECTOR_PUNCTUATION CONNECTOR_PUNCTUATION @@ -6657,23 +6681,23 @@ class Character implements java.io.Serializable, Comparable { /** * Determines the character representation for a specific digit in - * the specified radix. If the value of radix is not a - * valid radix, or the value of digit is not a valid + * the specified radix. If the value of {@code radix} is not a + * valid radix, or the value of {@code digit} is not a valid * digit in the specified radix, the null character - * ('\u0000') is returned. + * ({@code '\u005Cu0000'}) is returned. *

- * The radix argument is valid if it is greater than or - * equal to MIN_RADIX and less than or equal to - * MAX_RADIX. The digit argument is valid if - * 0 <=digit < radix. + * The {@code radix} argument is valid if it is greater than or + * equal to {@code MIN_RADIX} and less than or equal to + * {@code MAX_RADIX}. The {@code digit} argument is valid if + * {@code 0 <= digit < radix}. *

* If the digit is less than 10, then - * '0' + digit is returned. Otherwise, the value - * 'a' + digit - 10 is returned. + * {@code '0' + digit} is returned. Otherwise, the value + * {@code 'a' + digit - 10} is returned. * * @param digit the number to convert to a character. * @param radix the radix. - * @return the char representation of the specified digit + * @return the {@code char} representation of the specified digit * in the specified radix. * @see Character#MIN_RADIX * @see Character#MAX_RADIX @@ -6696,16 +6720,16 @@ class Character implements java.io.Serializable, Comparable { * Returns the Unicode directionality property for the given * character. Character directionality is used to calculate the * visual ordering of text. The directionality value of undefined - * char values is DIRECTIONALITY_UNDEFINED. + * {@code char} values is {@code DIRECTIONALITY_UNDEFINED}. * *

Note: This method cannot handle supplementary characters. To support * all Unicode characters, including supplementary characters, use * the {@link #getDirectionality(int)} method. * - * @param ch char for which the directionality property + * @param ch {@code char} for which the directionality property * is requested. - * @return the directionality property of the char value. + * @return the directionality property of the {@code char} value. * * @see Character#DIRECTIONALITY_UNDEFINED * @see Character#DIRECTIONALITY_LEFT_TO_RIGHT @@ -6774,7 +6798,7 @@ class Character implements java.io.Serializable, Comparable { * Determines whether the character is mirrored according to the * Unicode specification. Mirrored characters should have their * glyphs horizontally mirrored when displayed in text that is - * right-to-left. For example, '\u0028' LEFT + * right-to-left. For example, {@code '\u005Cu0028'} LEFT * PARENTHESIS is semantically defined to be an opening * parenthesis. This will appear as a "(" in text that is * left-to-right but as a ")" in text that is right-to-left. @@ -6784,9 +6808,9 @@ class Character implements java.io.Serializable, Comparable { * all Unicode characters, including supplementary characters, use * the {@link #isMirrored(int)} method. * - * @param ch char for which the mirrored property is requested - * @return true if the char is mirrored, false - * if the char is not mirrored or is not defined. + * @param ch {@code char} for which the mirrored property is requested + * @return {@code true} if the char is mirrored, {@code false} + * if the {@code char} is not mirrored or is not defined. * @since 1.4 */ public static boolean isMirrored(char ch) { @@ -6798,13 +6822,13 @@ class Character implements java.io.Serializable, Comparable { * is mirrored according to the Unicode specification. Mirrored * characters should have their glyphs horizontally mirrored when * displayed in text that is right-to-left. For example, - * '\u0028' LEFT PARENTHESIS is semantically + * {@code '\u005Cu0028'} LEFT PARENTHESIS is semantically * defined to be an opening parenthesis. This will appear * as a "(" in text that is left-to-right but as a ")" in text * that is right-to-left. * * @param codePoint the character (Unicode code point) to be tested. - * @return true if the character is mirrored, false + * @return {@code true} if the character is mirrored, {@code false} * if the character is not mirrored or is not defined. * @since 1.5 */ @@ -6813,16 +6837,16 @@ class Character implements java.io.Serializable, Comparable { } /** - * Compares two Character objects numerically. + * Compares two {@code Character} objects numerically. * - * @param anotherCharacter the Character to be compared. + * @param anotherCharacter the {@code Character} to be compared. - * @return the value 0 if the argument Character - * is equal to this Character; a value less than - * 0 if this Character is numerically less - * than the Character argument; and a value greater than - * 0 if this Character is numerically greater - * than the Character argument (unsigned comparison). + * @return the value {@code 0} if the argument {@code Character} + * is equal to this {@code Character}; a value less than + * {@code 0} if this {@code Character} is numerically less + * than the {@code Character} argument; and a value greater than + * {@code 0} if this {@code Character} is numerically greater + * than the {@code Character} argument (unsigned comparison). * Note that this is strictly a numerical comparison; it is not * locale-dependent. * @since 1.2 @@ -6856,8 +6880,8 @@ class Character implements java.io.Serializable, Comparable { * * @param codePoint the character (Unicode code point) to be converted. * @return either the uppercase equivalent of the character, if - * any, or an error flag (Character.ERROR) - * that indicates that a 1:M char mapping exists. + * any, or an error flag ({@code Character.ERROR}) + * that indicates that a 1:M {@code char} mapping exists. * @see Character#isLowerCase(char) * @see Character#isUpperCase(char) * @see Character#toLowerCase(char) @@ -6873,11 +6897,11 @@ class Character implements java.io.Serializable, Comparable { * Converts the character (Unicode code point) argument to uppercase using case * mapping information from the SpecialCasing file in the Unicode * specification. If a character has no explicit uppercase - * mapping, then the char itself is returned in the - * char[]. + * mapping, then the {@code char} itself is returned in the + * {@code char[]}. * * @param codePoint the character (Unicode code point) to be converted. - * @return a char[] with the uppercased character. + * @return a {@code char[]} with the uppercased character. * @since 1.4 */ static char[] toUpperCaseCharArray(int codePoint) { @@ -6908,7 +6932,7 @@ class Character implements java.io.Serializable, Comparable { /** * Returns the Unicode name of the specified character - * codePoint, or null if the code point is + * {@code codePoint}, or null if the code point is * {@link #UNASSIGNED unassigned}. *

* Note: if the specified character is not assigned a name by @@ -6916,14 +6940,12 @@ class Character implements java.io.Serializable, Comparable { * Database maintained by the Unicode Consortium), the returned * name is the same as the result of expression * - *

- * Character.UnicodeBlock.of(codePoint) - * .toString() - * .replace('_', ' ') + *
{@code + * Character.UnicodeBlock.of(codePoint).toString().replace('_', ' ') * + " " * + Integer.toHexString(codePoint).toUpperCase(Locale.ENGLISH); * - *
+ * }
* * @param codePoint the character (Unicode code point) * @@ -6931,7 +6953,7 @@ class Character implements java.io.Serializable, Comparable { * the code point is unassigned. * * @exception IllegalArgumentException if the specified - * codePoint is not a valid Unicode + * {@code codePoint} is not a valid Unicode * code point. * * @since 1.7 diff --git a/src/share/classes/javax/swing/JLayer.java b/src/share/classes/javax/swing/JLayer.java index 592fe82e24c00af9cedc85cb7bbb426c9628ec6b..42f21e605a66dd0624eb1f1217bf1b6dd5edb000 100644 --- a/src/share/classes/javax/swing/JLayer.java +++ b/src/share/classes/javax/swing/JLayer.java @@ -476,7 +476,7 @@ public final class JLayer * for this {@code JLayer} and the {@code JLayer} * is displayable. *

- * The following example shows how to correclty use this method + * The following example shows how to correctly use this method * in the {@code LayerUI} implementations: *

      *    public void installUI(JComponent c) {
@@ -834,7 +834,7 @@ public final class JLayer
         }
 
         /**
-         * First, implementatation of this method iterates through
+         * First, implementation of this method iterates through
          * glassPane's child components and returns {@code true}
          * if any of them is visible and contains passed x,y point.
          * After that it checks if no mouseListeners is attached to this component
diff --git a/src/share/classes/javax/swing/PopupFactory.java b/src/share/classes/javax/swing/PopupFactory.java
index 13a1f9d1a687d2925a96f31a00684367f94f3158..713ada71558c6ce56ff298fd2fbcec2218354815 100644
--- a/src/share/classes/javax/swing/PopupFactory.java
+++ b/src/share/classes/javax/swing/PopupFactory.java
@@ -203,6 +203,12 @@ public class PopupFactory {
                     popupType = HEAVY_WEIGHT_POPUP;
                     break;
                 }
+            } else if (c instanceof Window) {
+                Window w = (Window) c;
+                if (!w.isOpaque() || w.getOpacity() < 1 || w.getShape() != null) {
+                    popupType = HEAVY_WEIGHT_POPUP;
+                    break;
+                }
             }
             c = c.getParent();
         }
diff --git a/src/share/classes/javax/swing/SpringLayout.java b/src/share/classes/javax/swing/SpringLayout.java
index 53a86c3d099f927a00d89fe60c9c8adc25b19fd7..7686fc5622857b3f377622f14cd15dbb95851015 100644
--- a/src/share/classes/javax/swing/SpringLayout.java
+++ b/src/share/classes/javax/swing/SpringLayout.java
@@ -727,6 +727,9 @@ public class SpringLayout implements LayoutManager2 {
         * For any other String value passed as the edge,
         * no action is taken. For a null edge, a
         * NullPointerException is thrown.
+        * 

+ * Note: This method can affect {@code x} and {@code y} values + * previously set for this {@code Constraints}. * * @param edgeName the edge to be set * @param s the spring controlling the specified edge diff --git a/src/share/classes/javax/swing/plaf/LayerUI.java b/src/share/classes/javax/swing/plaf/LayerUI.java index e118467aa99967717bea219277f1aea9935ae690..c7ff14eeb4bf845e6be1a854e58988d8a5f9ed6e 100644 --- a/src/share/classes/javax/swing/plaf/LayerUI.java +++ b/src/share/classes/javax/swing/plaf/LayerUI.java @@ -25,9 +25,7 @@ package javax.swing.plaf; -import javax.accessibility.Accessible; import javax.swing.*; -import javax.swing.plaf.ComponentUI; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; @@ -38,7 +36,7 @@ import java.io.Serializable; /** * The base class for all {@link javax.swing.JLayer}'s UI delegates. *

- * {@link #paint(java.awt.Graphics, javax.swing.JComponent)} method performes the + * {@link #paint(java.awt.Graphics, javax.swing.JComponent)} method performs the * painting of the {@code JLayer} * and {@link #eventDispatched(AWTEvent, JLayer)} method is notified * about any {@code AWTEvent}s which have been generated by a {@code JLayer} @@ -165,7 +163,7 @@ public class LayerUI * l.setLayerEventMask(AWTEvent.COMPONENT_EVENT_MASK); * } * - * public void unistallUI(JComponent c) { + * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * l.setLayerEventMask(0); @@ -197,7 +195,7 @@ public class LayerUI * l.setLayerEventMask(AWTEvent.FOCUS_EVENT_MASK); * } * - * public void unistallUI(JComponent c) { + * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * l.setLayerEventMask(0); @@ -229,7 +227,7 @@ public class LayerUI * l.setLayerEventMask(AWTEvent.KEY_EVENT_MASK); * } * - * public void unistallUI(JComponent c) { + * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * l.setLayerEventMask(0); @@ -261,7 +259,7 @@ public class LayerUI * l.setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK); * } * - * public void unistallUI(JComponent c) { + * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * l.setLayerEventMask(0); @@ -293,7 +291,7 @@ public class LayerUI * l.setLayerEventMask(AWTEvent.MOUSE_MOTION_EVENT_MASK); * } * - * public void unistallUI(JComponent c) { + * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * l.setLayerEventMask(0); @@ -325,7 +323,7 @@ public class LayerUI * l.setLayerEventMask(AWTEvent.MOUSE_WHEEL_EVENT_MASK); * } * - * public void unistallUI(JComponent c) { + * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * l.setLayerEventMask(0); @@ -357,7 +355,7 @@ public class LayerUI * l.setLayerEventMask(AWTEvent.INPUT_METHOD_EVENT_MASK); * } * - * public void unistallUI(JComponent c) { + * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * l.setLayerEventMask(0); @@ -389,7 +387,7 @@ public class LayerUI * l.setLayerEventMask(AWTEvent.HIERARCHY_EVENT_MASK); * } * - * public void unistallUI(JComponent c) { + * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * l.setLayerEventMask(0); @@ -421,7 +419,7 @@ public class LayerUI * l.setLayerEventMask(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK); * } * - * public void unistallUI(JComponent c) { + * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * l.setLayerEventMask(0); @@ -691,7 +689,7 @@ public class LayerUI * Otherwise, the default implementation is used. * * @param c {@code JLayer} to return preferred size for - * @return maximun size for the passed {@code JLayer} + * @return maximum size for the passed {@code JLayer} */ public Dimension getMaximumSize(JComponent c) { JLayer l = (JLayer) c; diff --git a/src/share/classes/javax/swing/plaf/nimbus/LoweredBorder.java b/src/share/classes/javax/swing/plaf/nimbus/LoweredBorder.java index 46fc84adf67a2b9105010b6452b0e385aa42a7cd..768d77219745f7124319357cbf4b95988f388333 100644 --- a/src/share/classes/javax/swing/plaf/nimbus/LoweredBorder.java +++ b/src/share/classes/javax/swing/plaf/nimbus/LoweredBorder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2011, Oracle and/or its affiliates. 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 @@ -26,13 +26,11 @@ package javax.swing.plaf.nimbus; import javax.swing.border.Border; import javax.swing.JComponent; -import javax.swing.plaf.UIResource; import java.awt.Insets; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Color; -import java.awt.Transparency; import java.awt.RenderingHints; import java.awt.Dimension; import java.awt.image.BufferedImage; @@ -58,7 +56,9 @@ class LoweredBorder extends AbstractRegionPainter implements Border { @Override protected Object[] getExtendedCacheKeys(JComponent c) { - return new Object[] {c.getBackground()}; + return (c != null) + ? new Object[] { c.getBackground() } + : null; } /** @@ -85,6 +85,7 @@ class LoweredBorder extends AbstractRegionPainter implements Border { */ protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) { + Color color = (c == null) ? Color.BLACK : c.getBackground(); BufferedImage img1 = new BufferedImage(IMG_SIZE,IMG_SIZE, BufferedImage.TYPE_INT_ARGB); BufferedImage img2 = new BufferedImage(IMG_SIZE,IMG_SIZE, @@ -93,14 +94,14 @@ class LoweredBorder extends AbstractRegionPainter implements Border { Graphics2D g2 = (Graphics2D)img1.getGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2.setColor(c.getBackground()); + g2.setColor(color); g2.fillRoundRect(2,0,26,26,RADIUS,RADIUS); g2.dispose(); // draw shadow InnerShadowEffect effect = new InnerShadowEffect(); effect.setDistance(1); effect.setSize(3); - effect.setColor(getLighter(c.getBackground(),2.1f)); + effect.setColor(getLighter(color, 2.1f)); effect.setAngle(90); effect.applyEffect(img1,img2,IMG_SIZE,IMG_SIZE); // draw outline to img2 @@ -108,7 +109,7 @@ class LoweredBorder extends AbstractRegionPainter implements Border { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setClip(0,28,IMG_SIZE,1); - g2.setColor(getLighter(c.getBackground(),0.90f)); + g2.setColor(getLighter(color, 0.90f)); g2.drawRoundRect(2,1,25,25,RADIUS,RADIUS); g2.dispose(); // draw final image @@ -150,7 +151,7 @@ class LoweredBorder extends AbstractRegionPainter implements Border { * @param c the component for which this border insets value applies */ public Insets getBorderInsets(Component c) { - return INSETS; + return (Insets) INSETS.clone(); } /** diff --git a/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java b/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java index 621be2400f441d8f8b050a4ffd8e049a89d17cda..b1e6a09291057266fbfc84160a5a33ad18f4b96f 100644 --- a/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java +++ b/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java @@ -786,9 +786,9 @@ public class SynthTableUI extends BasicTableUI hasFocus, row, column); setIcon(null); - Class columnClass = table.getColumnClass(column); - configureValue(value, columnClass); - + if (table != null) { + configureValue(value, table.getColumnClass(column)); + } return this; } diff --git a/src/share/demo/applets/ArcTest/ArcTest.java b/src/share/demo/applets/ArcTest/ArcTest.java index d02fd0e377f8d9e6c882b25686f01fe7b7b9baf9..d58ef44b340cf07e38322e6a7b2ea51b6a81ff08 100644 --- a/src/share/demo/applets/ArcTest/ArcTest.java +++ b/src/share/demo/applets/ArcTest/ArcTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,22 +29,24 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import java.awt.*; import java.awt.event.*; import java.applet.*; + /** * An interactive test of the Graphics.drawArc and Graphics.fillArc * routines. Can be run either as a standalone application by * typing "java ArcTest" or as an applet in the AppletViewer. */ +@SuppressWarnings("serial") public class ArcTest extends Applet { + ArcControls controls; // The controls for marking and filling arcs ArcCanvas canvas; // The drawing area to display arcs + @Override public void init() { setLayout(new BorderLayout()); canvas = new ArcCanvas(); @@ -52,19 +54,23 @@ public class ArcTest extends Applet { add("South", controls = new ArcControls(canvas)); } + @Override public void destroy() { remove(controls); remove(canvas); } + @Override public void start() { controls.setEnabled(true); } + @Override public void stop() { controls.setEnabled(false); } + @Override public void processEvent(AWTEvent e) { if (e.getID() == Event.WINDOW_DESTROY) { System.exit(0); @@ -80,20 +86,28 @@ public class ArcTest extends Applet { f.add("Center", arcTest); f.setSize(300, 300); - f.show(); + f.setVisible(true); } + @Override public String getAppletInfo() { - return "An interactive test of the Graphics.drawArc and \nGraphics.fillArc routines. Can be run \neither as a standalone application by typing 'java ArcTest' \nor as an applet in the AppletViewer."; + return "An interactive test of the Graphics.drawArc and \nGraphics." + + "fillArc routines. Can be run \neither as a standalone " + + "application by typing 'java ArcTest' \nor as an applet in " + + "the AppletViewer."; } } + +@SuppressWarnings("serial") class ArcCanvas extends Canvas { - int startAngle = 0; - int extent = 45; - boolean filled = false; - Font font = new java.awt.Font("SansSerif", Font.PLAIN, 12); + int startAngle = 0; + int extent = 45; + boolean filled = false; + Font font = new java.awt.Font("SansSerif", Font.PLAIN, 12); + + @Override public void paint(Graphics g) { Rectangle r = getBounds(); int hlines = r.height / 10; @@ -134,12 +148,16 @@ class ArcCanvas extends Canvas { } } + +@SuppressWarnings("serial") class ArcControls extends Panel - implements ActionListener { + implements ActionListener { + TextField startTF; TextField extentTF; ArcCanvas canvas; + @SuppressWarnings("LeakingThisInConstructor") public ArcControls(ArcCanvas canvas) { Button b = null; @@ -154,18 +172,19 @@ class ArcControls extends Panel add(b); } + @Override public void actionPerformed(ActionEvent ev) { String label = ev.getActionCommand(); int start, extent; try { start = Integer.parseInt(startTF.getText().trim()); - } catch (NumberFormatException nfe) { + } catch (NumberFormatException ignored) { start = 0; } try { extent = Integer.parseInt(extentTF.getText().trim()); - } catch (NumberFormatException nfe) { + } catch (NumberFormatException ignored) { extent = 0; } @@ -173,6 +192,8 @@ class ArcControls extends Panel } } + +@SuppressWarnings("serial") class IntegerTextField extends TextField { String oldText = null; @@ -188,6 +209,7 @@ class IntegerTextField extends TextField { // function, but this is neater, since ideally, it would prevent // the text from appearing at all. Sigh. See bugid 4100317/4114565. // + @Override protected void processEvent(AWTEvent evt) { int id = evt.getID(); if (id != KeyEvent.KEY_TYPED) { @@ -200,8 +222,8 @@ class IntegerTextField extends TextField { // Digits, backspace, and delete are okay // Note that the minus sign is allowed, but not the decimal - if (Character.isDigit(c) || (c == '\b') || (c == '\u007f') || - (c == '\u002d')) { + if (Character.isDigit(c) || (c == '\b') || (c == '\u007f') || (c + == '\u002d')) { super.processEvent(evt); return; } @@ -215,6 +237,7 @@ class IntegerTextField extends TextField { // so we can revert to it on a TextEvent (paste, or // legal key in the wrong location) with bad text // + @Override protected void processTextEvent(TextEvent te) { // The empty string is okay, too String newText = getText(); @@ -233,12 +256,11 @@ class IntegerTextField extends TextField { // Note that the empty string is not allowed. // private boolean textIsInteger(String textToCheck) { - int value = -1; try { - value = Integer.parseInt(textToCheck, 10); + Integer.parseInt(textToCheck, 10); return true; - } catch (NumberFormatException nfe) { + } catch (NumberFormatException ignored) { return false; } } diff --git a/src/share/demo/applets/BarChart/BarChart.java b/src/share/demo/applets/BarChart/BarChart.java index dce59b51c57a5664149261c6e99b27cc02db8a13..81cab8fcf3b9905271e57888c0afec5d82357dc7 100644 --- a/src/share/demo/applets/BarChart/BarChart.java +++ b/src/share/demo/applets/BarChart/BarChart.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,28 +29,26 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import java.awt.*; + /** * A simple bar chart demo * @author Sami Shaio * @modified 06/21/00 Daniel Peek : refactored, comments */ +@SuppressWarnings("serial") public class BarChart extends java.applet.Applet { + private static final int VERTICAL = 0; private static final int HORIZONTAL = 1; - private static final int SOLID = 0; private static final int STRIPED = 1; - private int orientation; private String title; private Font font; private FontMetrics metrics; - private int fontHeight = 15; private int columns; private int values[]; private Color colors[]; @@ -61,6 +59,7 @@ public class BarChart extends java.applet.Applet { private int barSpacing = 10; private int maxValue = 0; + @Override public void init() { getSettings(); @@ -70,7 +69,7 @@ public class BarChart extends java.applet.Applet { styles = new int[columns]; colors = new Color[columns]; - for (int i=0; i < columns; i++) { + for (int i = 0; i < columns; i++) { parseValue(i); parseLabel(i); parseStyle(i); @@ -112,7 +111,7 @@ public class BarChart extends java.applet.Applet { } private void parseValue(int i) { - String temp = getParameter("C" + (i+1)); + String temp = getParameter("C" + (i + 1)); try { values[i] = Integer.parseInt(temp); } catch (NumberFormatException e) { @@ -124,18 +123,17 @@ public class BarChart extends java.applet.Applet { } private void parseLabel(int i) { - String temp = getParameter("C" + (i+1) + "_label"); - if (temp==null) { + String temp = getParameter("C" + (i + 1) + "_label"); + if (temp == null) { labels[i] = ""; } else { labels[i] = temp; } - maxLabelWidth = Math.max(metrics.stringWidth - ((String) (labels[i])), maxLabelWidth); + maxLabelWidth = Math.max(metrics.stringWidth(labels[i]), maxLabelWidth); } private void parseStyle(int i) { - String temp = getParameter("C" + (i+1) + "_style"); + String temp = getParameter("C" + (i + 1) + "_style"); if (temp == null || temp.equalsIgnoreCase("solid")) { styles[i] = SOLID; } else if (temp.equalsIgnoreCase("striped")) { @@ -146,7 +144,7 @@ public class BarChart extends java.applet.Applet { } private void parseColor(int i) { - String temp = getParameter("C" + (i+1) + "_color"); + String temp = getParameter("C" + (i + 1) + "_color"); if (temp != null) { temp = temp.toLowerCase(); if (temp.equals("red")) { @@ -179,6 +177,7 @@ public class BarChart extends java.applet.Applet { } } + @Override public void paint(Graphics g) { // draw the title centered at the bottom of the bar graph g.setColor(Color.black); @@ -192,7 +191,7 @@ public class BarChart extends java.applet.Applet { g.drawString(title, cx, cy); // draw the bars and their titles - if(orientation == HORIZONTAL) { + if (orientation == HORIZONTAL) { paintHorizontal(g); } else { // VERTICAL paintVertical(g); @@ -208,12 +207,13 @@ public class BarChart extends java.applet.Applet { // set the X coordinate for this bar and label and center it int widthOfItems = maxLabelWidth + 3 + (maxValue * scale) + 5 - + metrics.stringWidth(Integer.toString(maxValue)); + + metrics.stringWidth(Integer.toString(maxValue)); cx = Math.max((getSize().width - widthOfItems) / 2, 0); // set the Y coordinate for this bar and label cy = getSize().height - metrics.getDescent() - metrics.getHeight() - - barSpacing - ((columns - i - 1) * (barSpacing + barHeight)); + - barSpacing + - ((columns - i - 1) * (barSpacing + barHeight)); // draw the label g.setColor(Color.black); @@ -223,7 +223,7 @@ public class BarChart extends java.applet.Applet { // draw the shadow g.fillRect(cx + 4, cy - barHeight + 4, - (values[i] * scale), barHeight); + (values[i] * scale), barHeight); // draw the bar g.setColor(colors[i]); @@ -233,7 +233,7 @@ public class BarChart extends java.applet.Applet { } } else { // SOLID g.fillRect(cx, cy - barHeight, - (values[i] * scale) + 1, barHeight + 1); + (values[i] * scale) + 1, barHeight + 1); } cx += (values[i] * scale) + 4; @@ -255,7 +255,7 @@ public class BarChart extends java.applet.Applet { // Y coordinate for this label and bar int cy = getSize().height - metrics.getHeight() - - metrics.getDescent() - 4; + - metrics.getDescent() - 4; // draw the label g.setColor(Color.black); @@ -264,18 +264,18 @@ public class BarChart extends java.applet.Applet { // draw the shadow g.fillRect(cx + 4, cy - (values[i] * scale) - 4, - barWidth, (values[i] * scale)); + barWidth, (values[i] * scale)); // draw the bar g.setColor(colors[i]); if (styles[i] == STRIPED) { - for (int k=0; k <= values[i] * scale; k+=2) { + for (int k = 0; k <= values[i] * scale; k += 2) { g.drawLine(cx, cy - k, - cx + barWidth, cy - k); + cx + barWidth, cy - k); } } else { g.fillRect(cx, cy - (values[i] * scale), - barWidth + 1, (values[i] * scale) + 1); + barWidth + 1, (values[i] * scale) + 1); } cy -= (values[i] * scale) + 5; @@ -285,28 +285,30 @@ public class BarChart extends java.applet.Applet { } } + @Override public String getAppletInfo() { return "Title: Bar Chart \n" - + "Author: Sami Shaio \n" - + "A simple bar chart demo."; + + "Author: Sami Shaio \n" + + "A simple bar chart demo."; } + @Override public String[][] getParameterInfo() { String[][] info = { - {"title", "string", "The title of bar graph. Default is 'Chart'"}, - {"scale", "int", "The scale of the bar graph. Default is 10."}, - {"columns", "int", "The number of columns/rows. Default is 5."}, - {"orientation", "{VERTICAL, HORIZONTAL}", - "The orienation of the bar graph. Default is VERTICAL."}, - {"c#", "int", "Subsitute a number for #. " - + "The value/size of bar #. Default is 0."}, - {"c#_label", "string", "The label for bar #. " - + "Default is an empty label."}, - {"c#_style", "{SOLID, STRIPED}", "The style of bar #. " - + "Default is SOLID."}, - {"c#_color", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, " - + "WHITE, YELLOW, GRAY, DARKGRAY}", - "The color of bar #. Default is GRAY."} + { "title", "string", "The title of bar graph. Default is 'Chart'" }, + { "scale", "int", "The scale of the bar graph. Default is 10." }, + { "columns", "int", "The number of columns/rows. Default is 5." }, + { "orientation", "{VERTICAL, HORIZONTAL}", + "The orienation of the bar graph. Default is VERTICAL." }, + { "c#", "int", "Subsitute a number for #. " + + "The value/size of bar #. Default is 0." }, + { "c#_label", "string", "The label for bar #. " + + "Default is an empty label." }, + { "c#_style", "{SOLID, STRIPED}", "The style of bar #. " + + "Default is SOLID." }, + { "c#_color", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, " + + "WHITE, YELLOW, GRAY, DARKGRAY}", + "The color of bar #. Default is GRAY." } }; return info; } diff --git a/src/share/demo/applets/Blink/Blink.java b/src/share/demo/applets/Blink/Blink.java index 3495dc9ef0c1b843c951ff777b8d735ea864ab3b..ab6f9795cc6ad3d16df93e52e0a5fc7b99b306a3 100644 --- a/src/share/demo/applets/Blink/Blink.java +++ b/src/share/demo/applets/Blink/Blink.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,92 +29,106 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ /** * I love blinking things. * * @author Arthur van Hoff - * @modified 04/24/96 Jim Hagen use getBackground - * @modified 02/05/98 Mike McCloskey removed use of deprecated methods - * @modified 04/23/99 Josh Bloch, use timer instead of explicit multithreading. - * @modified 07/10/00 Daniel Peek brought to code conventions, minor changes + * @author 04/24/96 Jim Hagen use getBackground + * @author 02/05/98 Mike McCloskey removed use of deprecated methods + * @author 04/23/99 Josh Bloch, use timer instead of explicit multithreading. + * @author 07/10/00 Daniel Peek brought to code conventions, minor changes */ +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.util.StringTokenizer; +import java.util.Timer; +import java.util.TimerTask; -import java.awt.*; -import java.util.*; public class Blink extends java.applet.Applet { + + private static final long serialVersionUID = -775844794477507646L; private Timer timer; // Schedules the blinking private String labelString; // The label for the window private int delay; // the delay time between blinks + @Override public void init() { String blinkFrequency = getParameter("speed"); - delay = (blinkFrequency == null) ? 400 : - (1000 / Integer.parseInt(blinkFrequency)); + delay = (blinkFrequency == null) ? 400 + : (1000 / Integer.parseInt(blinkFrequency)); labelString = getParameter("lbl"); - if (labelString == null) + if (labelString == null) { labelString = "Blink"; + } Font font = new java.awt.Font("Serif", Font.PLAIN, 24); setFont(font); } + @Override public void start() { timer = new Timer(); //creates a new timer to schedule the blinking timer.schedule(new TimerTask() { //creates a timertask to schedule + // overrides the run method to provide functionality + @Override public void run() { repaint(); } - } - , delay, delay); + }, delay, delay); } + @Override public void paint(Graphics g) { int fontSize = g.getFont().getSize(); int x = 0, y = fontSize, space; - int red = (int) ( 50 * Math.random()); - int green = (int) ( 50 * Math.random()); - int blue = (int) (256 * Math.random()); + int red = (int) (50 * Math.random()); + int green = (int) (50 * Math.random()); + int blue = (int) (256 * Math.random()); Dimension d = getSize(); g.setColor(Color.black); FontMetrics fm = g.getFontMetrics(); space = fm.stringWidth(" "); for (StringTokenizer t = new StringTokenizer(labelString); - t.hasMoreTokens();) { + t.hasMoreTokens();) { String word = t.nextToken(); int w = fm.stringWidth(word) + space; if (x + w > d.width) { x = 0; y += fontSize; //move word to next line if it doesn't fit } - if (Math.random() < 0.5) - g.setColor(new java.awt.Color((red + y*30) % 256, - (green + x/3) % 256, blue)); - else + if (Math.random() < 0.5) { + g.setColor(new java.awt.Color((red + y * 30) % 256, + (green + x / 3) % 256, blue)); + } else { g.setColor(getBackground()); + } g.drawString(word, x, y); x += w; //shift to the right to draw the next word } } + @Override public void stop() { timer.cancel(); //stops the timer } + @Override public String getAppletInfo() { return "Title: Blinker\n" - + "Author: Arthur van Hoff\n" - + "Displays multicolored blinking text."; + + "Author: Arthur van Hoff\n" + + "Displays multicolored blinking text."; } + @Override public String[][] getParameterInfo() { String pinfo[][] = { - {"speed", "string", "The blink frequency"}, - {"lbl", "string", "The text to blink."}, - }; + { "speed", "string", "The blink frequency" }, + { "lbl", "string", "The text to blink." }, }; return pinfo; } } diff --git a/src/share/demo/applets/CardTest/CardTest.java b/src/share/demo/applets/CardTest/CardTest.java index 93e42ff95f0c6c6c0feb44b2d3f6469bdfaa9d38..38110efaf5b6564b54510235983d3c969ba538be 100644 --- a/src/share/demo/applets/CardTest/CardTest.java +++ b/src/share/demo/applets/CardTest/CardTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,14 +29,27 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.*; -import java.awt.event.*; import java.applet.Applet; +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.CardLayout; +import java.awt.Choice; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.LayoutManager; +import java.awt.Panel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + + +@SuppressWarnings("serial") +final class CardPanel extends Panel { -class CardPanel extends Panel { ActionListener listener; Panel create(LayoutManager layout) { @@ -83,16 +96,21 @@ class CardPanel extends Panel { add("six", create(new GridLayout(2, 2, 10, 10))); } + @Override public Dimension getPreferredSize() { return new Dimension(200, 100); } } + +@SuppressWarnings("serial") public class CardTest extends Applet - implements ActionListener, - ItemListener { + implements ActionListener, + ItemListener { + CardPanel cards; + @SuppressWarnings("LeakingThisInConstructor") public CardTest() { setLayout(new BorderLayout()); add("Center", cards = new CardPanel(this)); @@ -127,24 +145,26 @@ public class CardTest extends Applet p.add(c); } + @Override public void itemStateChanged(ItemEvent e) { - ((CardLayout)cards.getLayout()).show(cards, - (String)(e.getItem())); + ((CardLayout) cards.getLayout()).show(cards, + (String) (e.getItem())); } + @Override public void actionPerformed(ActionEvent e) { String arg = e.getActionCommand(); if ("first".equals(arg)) { - ((CardLayout)cards.getLayout()).first(cards); + ((CardLayout) cards.getLayout()).first(cards); } else if ("next".equals(arg)) { - ((CardLayout)cards.getLayout()).next(cards); + ((CardLayout) cards.getLayout()).next(cards); } else if ("previous".equals(arg)) { - ((CardLayout)cards.getLayout()).previous(cards); + ((CardLayout) cards.getLayout()).previous(cards); } else if ("last".equals(arg)) { - ((CardLayout)cards.getLayout()).last(cards); + ((CardLayout) cards.getLayout()).last(cards); } else { - ((CardLayout)cards.getLayout()).show(cards,(String)arg); + ((CardLayout) cards.getLayout()).show(cards, arg); } } @@ -156,9 +176,10 @@ public class CardTest extends Applet f.add("Center", cardTest); f.setSize(300, 300); - f.show(); + f.setVisible(true); } + @Override public String getAppletInfo() { return "Demonstrates the different types of layout managers."; } diff --git a/src/share/demo/applets/Clock/Clock.java b/src/share/demo/applets/Clock/Clock.java index 4c86ad3319dd3f392cde5208339040de01cf9a4a..ea698ff503e4509c8f92a0ddfc9d01dd26047eb3 100644 --- a/src/share/demo/applets/Clock/Clock.java +++ b/src/share/demo/applets/Clock/Clock.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,24 +29,28 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.util.*; -import java.awt.*; -import java.applet.*; -import java.text.*; +import java.applet.Applet; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + /** * Time! * * @author Rachel Gollub - * @modified Daniel Peek replaced circle drawing calculation, few more changes + * @author Daniel Peek replaced circle drawing calculation, few more changes */ +@SuppressWarnings("serial") public class Clock extends Applet implements Runnable { + private volatile Thread timer; // The thread that displays clock private int lastxs, lastys, lastxm, - lastym, lastxh, lastyh; // Dimensions used to draw hands + lastym, lastxh, lastyh; // Dimensions used to draw hands private SimpleDateFormat formatter; // Formats the date displayed private String lastdate; // String to hold date displayed private Font clockFaceFont; // Font for number display on clock @@ -55,11 +59,11 @@ public class Clock extends Applet implements Runnable { private Color numberColor; // Color of second hand and numbers private int xcenter = 80, ycenter = 55; // Center position + @Override public void init() { - int x,y; lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0; - formatter = new SimpleDateFormat ("EEE MMM dd hh:mm:ss yyyy", - Locale.getDefault()); + formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy", + Locale.getDefault()); currentDate = new Date(); lastdate = formatter.format(currentDate); clockFaceFont = new Font("Serif", Font.PLAIN, 14); @@ -68,26 +72,29 @@ public class Clock extends Applet implements Runnable { try { setBackground(new Color(Integer.parseInt(getParameter("bgcolor"), - 16))); + 16))); } catch (NullPointerException e) { } catch (NumberFormatException e) { } try { handColor = new Color(Integer.parseInt(getParameter("fgcolor1"), - 16)); + 16)); } catch (NullPointerException e) { } catch (NumberFormatException e) { } try { numberColor = new Color(Integer.parseInt(getParameter("fgcolor2"), - 16)); + 16)); } catch (NullPointerException e) { } catch (NumberFormatException e) { } - resize(300,300); // Set clock window size + resize(300, 300); // Set clock window size } - // Paint is the main part of the program + /** + * Paint is the main part of the program + */ + @Override public void update(Graphics g) { int xh, yh, xm, ym, xs, ys; int s = 0, m = 10, h = 10; @@ -119,10 +126,12 @@ public class Clock extends Applet implements Runnable { ys = (int) (Math.sin(s * Math.PI / 30 - Math.PI / 2) * 45 + ycenter); xm = (int) (Math.cos(m * Math.PI / 30 - Math.PI / 2) * 40 + xcenter); ym = (int) (Math.sin(m * Math.PI / 30 - Math.PI / 2) * 40 + ycenter); - xh = (int) (Math.cos((h*30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30 - + xcenter); - yh = (int) (Math.sin((h*30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30 - + ycenter); + xh = (int) (Math.cos((h * 30 + m / 2) * Math.PI / 180 - Math.PI / 2) + * 30 + + xcenter); + yh = (int) (Math.sin((h * 30 + m / 2) * Math.PI / 180 - Math.PI / 2) + * 30 + + ycenter); // Get the date to print at the bottom formatter.applyPattern("EEE MMM dd HH:mm:ss yyyy"); @@ -136,12 +145,12 @@ public class Clock extends Applet implements Runnable { g.drawString(lastdate, 5, 125); } if (xm != lastxm || ym != lastym) { - g.drawLine(xcenter, ycenter-1, lastxm, lastym); - g.drawLine(xcenter-1, ycenter, lastxm, lastym); + g.drawLine(xcenter, ycenter - 1, lastxm, lastym); + g.drawLine(xcenter - 1, ycenter, lastxm, lastym); } if (xh != lastxh || yh != lastyh) { - g.drawLine(xcenter, ycenter-1, lastxh, lastyh); - g.drawLine(xcenter-1, ycenter, lastxh, lastyh); + g.drawLine(xcenter, ycenter - 1, lastxh, lastyh); + g.drawLine(xcenter - 1, ycenter, lastxh, lastyh); } // Draw date and hands @@ -149,73 +158,83 @@ public class Clock extends Applet implements Runnable { g.drawString(today, 5, 125); g.drawLine(xcenter, ycenter, xs, ys); g.setColor(handColor); - g.drawLine(xcenter, ycenter-1, xm, ym); - g.drawLine(xcenter-1, ycenter, xm, ym); - g.drawLine(xcenter, ycenter-1, xh, yh); - g.drawLine(xcenter-1, ycenter, xh, yh); - lastxs = xs; lastys = ys; - lastxm = xm; lastym = ym; - lastxh = xh; lastyh = yh; + g.drawLine(xcenter, ycenter - 1, xm, ym); + g.drawLine(xcenter - 1, ycenter, xm, ym); + g.drawLine(xcenter, ycenter - 1, xh, yh); + g.drawLine(xcenter - 1, ycenter, xh, yh); + lastxs = xs; + lastys = ys; + lastxm = xm; + lastym = ym; + lastxh = xh; + lastyh = yh; lastdate = today; currentDate = null; } + @Override public void paint(Graphics g) { g.setFont(clockFaceFont); // Draw the circle and numbers g.setColor(handColor); - g.drawArc(xcenter-50, ycenter-50, 100, 100, 0, 360); + g.drawArc(xcenter - 50, ycenter - 50, 100, 100, 0, 360); g.setColor(numberColor); - g.drawString("9", xcenter-45, ycenter+3); - g.drawString("3", xcenter+40, ycenter+3); - g.drawString("12", xcenter-5, ycenter-37); - g.drawString("6", xcenter-3, ycenter+45); + g.drawString("9", xcenter - 45, ycenter + 3); + g.drawString("3", xcenter + 40, ycenter + 3); + g.drawString("12", xcenter - 5, ycenter - 37); + g.drawString("6", xcenter - 3, ycenter + 45); // Draw date and hands g.setColor(numberColor); g.drawString(lastdate, 5, 125); g.drawLine(xcenter, ycenter, lastxs, lastys); g.setColor(handColor); - g.drawLine(xcenter, ycenter-1, lastxm, lastym); - g.drawLine(xcenter-1, ycenter, lastxm, lastym); - g.drawLine(xcenter, ycenter-1, lastxh, lastyh); - g.drawLine(xcenter-1, ycenter, lastxh, lastyh); + g.drawLine(xcenter, ycenter - 1, lastxm, lastym); + g.drawLine(xcenter - 1, ycenter, lastxm, lastym); + g.drawLine(xcenter, ycenter - 1, lastxh, lastyh); + g.drawLine(xcenter - 1, ycenter, lastxh, lastyh); } + @Override public void start() { timer = new Thread(this); timer.start(); } + @Override public void stop() { timer = null; } + @Override + @SuppressWarnings("SleepWhileHoldingLock") public void run() { Thread me = Thread.currentThread(); while (timer == me) { try { - Thread.currentThread().sleep(100); + Thread.sleep(100); } catch (InterruptedException e) { } repaint(); } } + @Override public String getAppletInfo() { return "Title: A Clock \n" - + "Author: Rachel Gollub, 1995 \n" - + "An analog clock."; + + "Author: Rachel Gollub, 1995 \n" + + "An analog clock."; } + @Override public String[][] getParameterInfo() { String[][] info = { - {"bgcolor", "hexadecimal RGB number", - "The background color. Default is the color of your browser."}, - {"fgcolor1", "hexadecimal RGB number", - "The color of the hands and dial. Default is blue."}, - {"fgcolor2", "hexadecimal RGB number", - "The color of the second hand and numbers. Default is dark gray."} + { "bgcolor", "hexadecimal RGB number", + "The background color. Default is the color of your browser." }, + { "fgcolor1", "hexadecimal RGB number", + "The color of the hands and dial. Default is blue." }, + { "fgcolor2", "hexadecimal RGB number", + "The color of the second hand and numbers. Default is dark gray." } }; return info; } diff --git a/src/share/demo/applets/DitherTest/DitherTest.java b/src/share/demo/applets/DitherTest/DitherTest.java index 25e743db9df706789c81e77c2798661ca7e24201..04165735702d624eaf285491c3431ed38ae44b8b 100644 --- a/src/share/demo/applets/DitherTest/DitherTest.java +++ b/src/share/demo/applets/DitherTest/DitherTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,25 +29,43 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import java.applet.Applet; -import java.awt.event.*; -import java.awt.*; +import java.awt.AWTEvent; +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Canvas; +import java.awt.Choice; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.FontMetrics; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.Label; +import java.awt.LayoutManager; +import java.awt.Panel; +import java.awt.TextField; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.TextEvent; import java.awt.image.ColorModel; import java.awt.image.MemoryImageSource; + +enum DitherMethod { + + NOOP, RED, GREEN, BLUE, ALPHA, SATURATION +}; + + +@SuppressWarnings("serial") public class DitherTest extends Applet implements Runnable { - final private static int NOOP = 0; - final private static int RED = 1; - final private static int GREEN = 2; - final private static int BLUE = 3; - final private static int ALPHA = 4; - final private static int SATURATION = 5; private Thread runner; - private DitherControls XControls; private DitherControls YControls; private DitherCanvas canvas; @@ -62,6 +80,7 @@ public class DitherTest extends Applet implements Runnable { ditherTest.start(); } + @Override public void init() { String xspec = null, yspec = null; int xvals[] = new int[2]; @@ -70,7 +89,7 @@ public class DitherTest extends Applet implements Runnable { try { xspec = getParameter("xaxis"); yspec = getParameter("yaxis"); - } catch (NullPointerException npe) { + } catch (NullPointerException ignored) { //only occurs if run as application } @@ -80,44 +99,34 @@ public class DitherTest extends Applet implements Runnable { if (yspec == null) { yspec = "blue"; } - int xmethod = colormethod(xspec, xvals); - int ymethod = colormethod(yspec, yvals); + DitherMethod xmethod = colorMethod(xspec, xvals); + DitherMethod ymethod = colorMethod(yspec, yvals); setLayout(new BorderLayout()); XControls = new DitherControls(this, xvals[0], xvals[1], - xmethod, false); + xmethod, false); YControls = new DitherControls(this, yvals[0], yvals[1], - ymethod, true); + ymethod, true); YControls.addRenderButton(); add("North", XControls); add("South", YControls); add("Center", canvas = new DitherCanvas()); } - private int colormethod(String s, int vals[]) { - int method = NOOP; + private DitherMethod colorMethod(String s, int vals[]) { + DitherMethod method = DitherMethod.NOOP; if (s == null) { s = ""; } String lower = s.toLowerCase(); - int len = 0; - if (lower.startsWith("red")) { - method = RED; - lower = lower.substring(3); - } else if (lower.startsWith("green")) { - method = GREEN; - lower = lower.substring(5); - } else if (lower.startsWith("blue")) { - method = BLUE; - lower = lower.substring(4); - } else if (lower.startsWith("alpha")) { - method = ALPHA; - lower = lower.substring(5); - } else if (lower.startsWith("saturation")) { - method = SATURATION; - lower = lower.substring(10); + + for (DitherMethod m : DitherMethod.values()) { + if (lower.startsWith(m.toString().toLowerCase())) { + method = m; + lower = lower.substring(m.toString().length()); + } } - if (method == NOOP) { + if (method == DitherMethod.NOOP) { vals[0] = 0; vals[1] = 0; return method; @@ -132,7 +141,7 @@ public class DitherTest extends Applet implements Runnable { begval = Integer.parseInt(lower.substring(0, dash)); endval = Integer.parseInt(lower.substring(dash + 1)); } - } catch (NumberFormatException nfe) { + } catch (NumberFormatException ignored) { } if (begval < 0) { @@ -173,16 +182,14 @@ public class DitherTest extends Applet implements Runnable { c[0] = c[1] = c[2] = 0; c[3] = 255; if (xmethod < ymethod) { - applymethod(c, xmethod, i, width, xvals); - applymethod(c, ymethod, j, height, yvals); + applyMethod(c, xmethod, i, width, xvals); + applyMethod(c, ymethod, j, height, yvals); } else { - applymethod(c, ymethod, j, height, yvals); - applymethod(c, xmethod, i, width, xvals); + applyMethod(c, ymethod, j, height, yvals); + applyMethod(c, xmethod, i, width, xvals); } - pixels[index++] = ((c[3] << 24) | - (c[0] << 16) | - (c[1] << 8) | - c[2]); + pixels[index++] = ((c[3] << 24) | (c[0] << 16) | (c[1] << 8) + | c[2]); } // Poll once per row to see if we've been told to stop. @@ -191,51 +198,54 @@ public class DitherTest extends Applet implements Runnable { } } return createImage(new MemoryImageSource(width, height, - ColorModel.getRGBdefault(), pixels, 0, width)); + ColorModel.getRGBdefault(), pixels, 0, width)); } - private void applymethod(int c[], int method, int step, - int total, int vals[]) { - if (method == NOOP) { + private void applyMethod(int c[], int methodIndex, int step, + int total, int vals[]) { + DitherMethod method = DitherMethod.values()[methodIndex]; + if (method == DitherMethod.NOOP) { return; } int val = ((total < 2) - ? vals[0] - : vals[0] + ((vals[1] - vals[0]) * step / (total - 1))); + ? vals[0] + : vals[0] + ((vals[1] - vals[0]) * step / (total - 1))); switch (method) { - case RED: - c[0] = val; - break; - case GREEN: - c[1] = val; - break; - case BLUE: - c[2] = val; - break; - case ALPHA: - c[3] = val; - break; - case SATURATION: - int max = Math.max(Math.max(c[0], c[1]), c[2]); - int min = max * (255 - val) / 255; - if (c[0] == 0) { - c[0] = min; - } - if (c[1] == 0) { - c[1] = min; - } - if (c[2] == 0) { - c[2] = min; - } - break; + case RED: + c[0] = val; + break; + case GREEN: + c[1] = val; + break; + case BLUE: + c[2] = val; + break; + case ALPHA: + c[3] = val; + break; + case SATURATION: + int max = Math.max(Math.max(c[0], c[1]), c[2]); + int min = max * (255 - val) / 255; + if (c[0] == 0) { + c[0] = min; + } + if (c[1] == 0) { + c[1] = min; + } + if (c[2] == 0) { + c[2] = min; + } + break; } } + @Override public void start() { runner = new Thread(this); runner.start(); } + @Override public void run() { canvas.setImage(null); // Wipe previous image Image img = calculateImage(); @@ -244,35 +254,43 @@ public class DitherTest extends Applet implements Runnable { } } + @Override public void stop() { runner = null; } + @Override public void destroy() { remove(XControls); remove(YControls); remove(canvas); } + @Override public String getAppletInfo() { return "An interactive demonstration of dithering."; } + @Override public String[][] getParameterInfo() { String[][] info = { - {"xaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}", - "The color of the Y axis. Default is RED."}, - {"yaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}", - "The color of the X axis. Default is BLUE."} + { "xaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}", + "The color of the Y axis. Default is RED." }, + { "yaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}", + "The color of the X axis. Default is BLUE." } }; return info; } } + +@SuppressWarnings("serial") class DitherCanvas extends Canvas { + private Image img; private static String calcString = "Calculating..."; + @Override public void paint(Graphics g) { int w = getSize().width; int h = getSize().height; @@ -288,14 +306,17 @@ class DitherCanvas extends Canvas { } } + @Override public void update(Graphics g) { paint(g); } + @Override public Dimension getMinimumSize() { return new Dimension(20, 20); } + @Override public Dimension getPreferredSize() { return new Dimension(200, 200); } @@ -310,29 +331,29 @@ class DitherCanvas extends Canvas { } } + +@SuppressWarnings("serial") class DitherControls extends Panel implements ActionListener { + private CardinalTextField start; private CardinalTextField end; private Button button; private Choice choice; private DitherTest applet; - private static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER, - 10, 5); + 10, 5); - public DitherControls(DitherTest app, int s, int e, int type, - boolean vertical) { + public DitherControls(DitherTest app, int s, int e, DitherMethod type, + boolean vertical) { applet = app; setLayout(dcLayout); add(new Label(vertical ? "Vertical" : "Horizontal")); add(choice = new Choice()); - choice.addItem("Noop"); - choice.addItem("Red"); - choice.addItem("Green"); - choice.addItem("Blue"); - choice.addItem("Alpha"); - choice.addItem("Saturation"); - choice.select(type); + for (DitherMethod m : DitherMethod.values()) { + choice.addItem(m.toString().substring(0, 1) + + m.toString().substring(1).toLowerCase()); + } + choice.select(type.ordinal()); add(start = new CardinalTextField(Integer.toString(s), 4)); add(end = new CardinalTextField(Integer.toString(e), 4)); } @@ -369,6 +390,7 @@ class DitherControls extends Panel implements ActionListener { } /* called when user clicks the button */ + @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { applet.start(); @@ -376,6 +398,8 @@ class DitherControls extends Panel implements ActionListener { } } + +@SuppressWarnings("serial") class CardinalTextField extends TextField { String oldText = null; @@ -391,6 +415,7 @@ class CardinalTextField extends TextField { // function, but this is neater, since ideally, it would prevent // the text from appearing at all. Sigh. See bugid 4100317/4114565. // + @Override protected void processEvent(AWTEvent evt) { int id = evt.getID(); if (id != KeyEvent.KEY_TYPED) { @@ -420,6 +445,7 @@ class CardinalTextField extends TextField { // Note: it would be easy to extend this to an eight-bit // TextField (range 0-255), but I'll leave it as-is. // + @Override protected void processTextEvent(TextEvent te) { // The empty string is okay, too String newText = getText(); @@ -436,11 +462,8 @@ class CardinalTextField extends TextField { // Returns true for Cardinal (non-negative) numbers // Note that the empty string is not allowed private boolean textIsCardinal(String textToCheck) { - int value = -1; - try { - value = Integer.parseInt(textToCheck, 10); - return (value >= 0); + return Integer.parseInt(textToCheck, 10) >= 0; } catch (NumberFormatException nfe) { return false; } diff --git a/src/share/demo/applets/DrawTest/DrawTest.java b/src/share/demo/applets/DrawTest/DrawTest.java index 2a98482bf4e00069788bee1ba4fec83e831831dd..50af991079e65ae81ed4892ddb9229f065646969 100644 --- a/src/share/demo/applets/DrawTest/DrawTest.java +++ b/src/share/demo/applets/DrawTest/DrawTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,27 +29,46 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.event.*; -import java.awt.*; -import java.applet.*; +import java.applet.Applet; +import java.awt.BorderLayout; +import java.awt.Checkbox; +import java.awt.CheckboxGroup; +import java.awt.Choice; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.util.ArrayList; +import java.util.List; -import java.util.Vector; -public class DrawTest extends Applet{ +@SuppressWarnings("serial") +public class DrawTest extends Applet { + DrawPanel panel; DrawControls controls; + @Override public void init() { setLayout(new BorderLayout()); panel = new DrawPanel(); controls = new DrawControls(panel); add("Center", panel); - add("South",controls); + add("South", controls); } + @Override public void destroy() { remove(panel); remove(controls); @@ -63,22 +82,28 @@ public class DrawTest extends Applet{ f.add("Center", drawTest); f.setSize(300, 300); - f.show(); + f.setVisible(true); } + + @Override public String getAppletInfo() { return "A simple drawing program."; } } + +@SuppressWarnings("serial") class DrawPanel extends Panel implements MouseListener, MouseMotionListener { + public static final int LINES = 0; public static final int POINTS = 1; - int mode = LINES; - Vector lines = new Vector(); - Vector colors = new Vector(); - int x1,y1; - int x2,y2; + int mode = LINES; + List lines = new ArrayList(); + List colors = new ArrayList(); + int x1, y1; + int x2, y2; + @SuppressWarnings("LeakingThisInConstructor") public DrawPanel() { setBackground(Color.white); addMouseMotionListener(this); @@ -87,16 +112,16 @@ class DrawPanel extends Panel implements MouseListener, MouseMotionListener { public void setDrawMode(int mode) { switch (mode) { - case LINES: - case POINTS: - this.mode = mode; - break; - default: - throw new IllegalArgumentException(); + case LINES: + case POINTS: + this.mode = mode; + break; + default: + throw new IllegalArgumentException(); } } - + @Override public void mouseDragged(MouseEvent e) { e.consume(); switch (mode) { @@ -106,8 +131,8 @@ class DrawPanel extends Panel implements MouseListener, MouseMotionListener { break; case POINTS: default: - colors.addElement(getForeground()); - lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY())); + colors.add(getForeground()); + lines.add(new Rectangle(x1, y1, e.getX(), e.getY())); x1 = e.getX(); y1 = e.getY(); break; @@ -115,9 +140,11 @@ class DrawPanel extends Panel implements MouseListener, MouseMotionListener { repaint(); } + @Override public void mouseMoved(MouseEvent e) { } + @Override public void mousePressed(MouseEvent e) { e.consume(); switch (mode) { @@ -128,8 +155,8 @@ class DrawPanel extends Panel implements MouseListener, MouseMotionListener { break; case POINTS: default: - colors.addElement(getForeground()); - lines.addElement(new Rectangle(e.getX(), e.getY(), -1, -1)); + colors.add(getForeground()); + lines.add(new Rectangle(e.getX(), e.getY(), -1, -1)); x1 = e.getX(); y1 = e.getY(); repaint(); @@ -137,12 +164,13 @@ class DrawPanel extends Panel implements MouseListener, MouseMotionListener { } } + @Override public void mouseReleased(MouseEvent e) { e.consume(); switch (mode) { case LINES: - colors.addElement(getForeground()); - lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY())); + colors.add(getForeground()); + lines.add(new Rectangle(x1, y1, e.getX(), e.getY())); x2 = -1; break; case POINTS: @@ -152,23 +180,27 @@ class DrawPanel extends Panel implements MouseListener, MouseMotionListener { repaint(); } + @Override public void mouseEntered(MouseEvent e) { } + @Override public void mouseExited(MouseEvent e) { } + @Override public void mouseClicked(MouseEvent e) { } + @Override public void paint(Graphics g) { int np = lines.size(); /* draw the current lines */ g.setColor(getForeground()); - for (int i=0; i < np; i++) { - Rectangle p = (Rectangle)lines.elementAt(i); - g.setColor((Color)colors.elementAt(i)); + for (int i = 0; i < np; i++) { + Rectangle p = lines.get(i); + g.setColor(colors.get(i)); if (p.width != -1) { g.drawLine(p.x, p.y, p.width, p.height); } else { @@ -185,9 +217,12 @@ class DrawPanel extends Panel implements MouseListener, MouseMotionListener { } +@SuppressWarnings("serial") class DrawControls extends Panel implements ItemListener { + DrawPanel target; + @SuppressWarnings("LeakingThisInConstructor") public DrawControls(DrawPanel target) { this.target = target; setLayout(new FlowLayout()); @@ -222,33 +257,35 @@ class DrawControls extends Panel implements ItemListener { add(shapes); } + @Override public void paint(Graphics g) { Rectangle r = getBounds(); g.setColor(Color.lightGray); g.draw3DRect(0, 0, r.width, r.height, false); int n = getComponentCount(); - for(int i=0; i turtleStack = new Stack(); CLSTurtle turtle; if (g == null) { @@ -172,11 +202,13 @@ public class CLSFractal turtle = new CLSTurtle(startAngle, 0, 0, 0, 0, 1, 1); } else { float frwidth = Xmax - Xmin; - if (frwidth == 0) + if (frwidth == 0) { frwidth = 1; + } float frheight = Ymax - Ymin; - if (frheight == 0) + if (frheight == 0) { frheight = 1; + } float xscale = (getSize().width - border * 2 - 1) / frwidth; float yscale = (getSize().height - border * 2 - 1) / frheight; int xoff = border; @@ -184,84 +216,102 @@ public class CLSFractal if (normalizescaling) { if (xscale < yscale) { yoff += ((getSize().height - border * 2) - - ((Ymax - Ymin) * xscale)) / 2; + - ((Ymax - Ymin) * xscale)) / 2; yscale = xscale; } else if (yscale < xscale) { xoff += ((getSize().width - border * 2) - - ((Xmax - Xmin) * yscale)) / 2; + - ((Xmax - Xmin) * yscale)) / 2; xscale = yscale; } } turtle = new CLSTurtle(startAngle, 0 - Xmin, 0 - Ymin, - xoff, yoff, xscale, yscale); + xoff, yoff, xscale, yscale); } for (int pos = 0; pos < path.length(); pos++) { switch (path.charAt(pos)) { - case '+': - turtle.rotate(rotAngle); - break; - case '-': - turtle.rotate(-rotAngle); - break; - case '[': - turtleStack.push(turtle); - turtle = new CLSTurtle(turtle); - break; - case ']': - turtle = (CLSTurtle) turtleStack.pop(); - break; - case 'f': - turtle.jump(); - break; - case 'F': - if (g == null) { - includePt(turtle.X, turtle.Y); + case '+': + turtle.rotate(rotAngle); + break; + case '-': + turtle.rotate(-rotAngle); + break; + case '[': + turtleStack.push(turtle); + turtle = new CLSTurtle(turtle); + break; + case ']': + turtle = turtleStack.pop(); + break; + case 'f': turtle.jump(); - includePt(turtle.X, turtle.Y); - } else { - turtle.draw(g); - } - break; - default: - break; + break; + case 'F': + if (g == null) { + includePt(turtle.X, turtle.Y); + turtle.jump(); + includePt(turtle.X, turtle.Y); + } else { + turtle.draw(g); + } + break; + default: + break; } } } void includePt(float x, float y) { - if (x < Xmin) + if (x < Xmin) { Xmin = x; - if (x > Xmax) + } + if (x > Xmax) { Xmax = x; - if (y < Ymin) + } + if (y < Ymin) { Ymin = y; - if (y > Ymax) + } + if (y > Ymax) { Ymax = y; + } + } + + @Override + public String getAppletInfo() { + return "Title: CLSFractal 1.1f, 27 Mar 1995 \nAuthor: Jim Graham \nA " + + "(not yet) Context Sensitive L-System production rule. \n" + + "This class encapsulates a production rule for a Context " + + "Sensitive\n L-System \n(pred, succ, lContext, rContext)." + + " The matches() method, however, does not \n(yet) verify " + + "the lContext and rContext parts of the rule."; } - public String getAppletInfo() { - return "Title: CLSFractal 1.1f, 27 Mar 1995 \nAuthor: Jim Graham \nA (not yet) Context Sensitive L-System production rule. \nThis class encapsulates a production rule for a Context Sensitive\n L-System \n(pred, succ, lContext, rContext). The matches() method, however, does not \n(yet) verify the lContext and rContext parts of the rule."; - } - - public String[][] getParameterInfo() { - String[][] info = { - {"level", "int", "Maximum number of recursions. Default is 1."}, - {"incremental","boolean","Whether or not to repaint between recursions. Default is true."}, - {"delay","integer","Sets delay between repaints. Default is 50."}, - {"startAngle","float","Sets the starting angle. Default is 0."}, - {"rotAngle","float","Sets the rotation angle. Default is 45."}, - {"border","integer","Width of border. Default is 2."}, - {"normalizeScale","boolean","Whether or not to normalize the scaling. Default is true."}, - {"pred","String","Initializes the rules for Context Sensitive L-Systems."}, - {"succ","String","Initializes the rules for Context Sensitive L-Systems."}, - {"lContext","String","Initializes the rules for Context Sensitive L-Systems."}, - {"rContext","String","Initializes the rules for Context Sensitive L-Systems."} - }; - return info; - } + @Override + public String[][] getParameterInfo() { + String[][] info = { + { "level", "int", "Maximum number of recursions. Default is 1." }, + { "incremental", "boolean", "Whether or not to repaint between " + + "recursions. Default is true." }, + { "delay", "integer", "Sets delay between repaints. Default is 50." }, + { "startAngle", "float", "Sets the starting angle. Default is 0." }, + { "rotAngle", "float", "Sets the rotation angle. Default is 45." }, + { "border", "integer", "Width of border. Default is 2." }, + { "normalizeScale", "boolean", "Whether or not to normalize " + + "the scaling. Default is true." }, + { "pred", "String", + "Initializes the rules for Context Sensitive L-Systems." }, + { "succ", "String", + "Initializes the rules for Context Sensitive L-Systems." }, + { "lContext", "String", + "Initializes the rules for Context Sensitive L-Systems." }, + { "rContext", "String", + "Initializes the rules for Context Sensitive L-Systems." } + }; + return info; + } } + /** * A Logo turtle class designed to support Context sensitive L-Systems. * @@ -271,6 +321,7 @@ public class CLSFractal * @author Jim Graham */ class CLSTurtle { + float angle; float X; float Y; @@ -280,7 +331,7 @@ class CLSTurtle { int yoff; public CLSTurtle(float ang, float x, float y, - int xorg, int yorg, float sx, float sy) { + int xorg, int yorg, float sx, float sy) { angle = ang; scaleX = sx; scaleY = sy; @@ -313,12 +364,13 @@ class CLSTurtle { float x = X + (float) Math.cos(angle) * scaleX; float y = Y + (float) Math.sin(angle) * scaleY; g.drawLine((int) X + xoff, (int) Y + yoff, - (int) x + xoff, (int) y + yoff); + (int) x + xoff, (int) y + yoff); X = x; Y = y; } } + /** * A (non-)Context sensitive L-System class. * @@ -330,22 +382,23 @@ class CLSTurtle { * @author Jim Graham */ class ContextLSystem { + String axiom; - Vector rules = new Vector(); + List rules = new ArrayList(); int level; public ContextLSystem(java.applet.Applet app) { axiom = app.getParameter("axiom"); int num = 1; while (true) { - String pred = app.getParameter("pred"+num); - String succ = app.getParameter("succ"+num); + String pred = app.getParameter("pred" + num); + String succ = app.getParameter("succ" + num); if (pred == null || succ == null) { break; } - rules.addElement(new CLSRule(pred, succ, - app.getParameter("lContext"+num), - app.getParameter("rContext"+num))); + rules.add(new CLSRule(pred, succ, + app.getParameter("lContext" + num), + app.getParameter("rContext" + num))); num++; } currentPath = new StringBuffer(axiom); @@ -355,7 +408,6 @@ class ContextLSystem { public int getLevel() { return level; } - StringBuffer currentPath; public synchronized String getPath() { @@ -385,7 +437,7 @@ class ContextLSystem { public CLSRule findRule(int pos) { for (int i = 0; i < rules.size(); i++) { - CLSRule rule = (CLSRule) rules.elementAt(i); + CLSRule rule = rules.get(i); if (rule.matches(currentPath, pos)) { return rule; } @@ -394,6 +446,7 @@ class ContextLSystem { } } + /** * A Context sensitive L-System production rule. * @@ -405,6 +458,7 @@ class ContextLSystem { * @author Jim Graham */ class CLSRule { + String pred; String succ; String lContext; diff --git a/src/share/demo/applets/Fractal/example1.html b/src/share/demo/applets/Fractal/example1.html index ac6aab9ad646db03d44120aa6eafa1d978c308cc..12d49e03217d7479cdd6db3b05b5321f58e1cfb9 100644 --- a/src/share/demo/applets/Fractal/example1.html +++ b/src/share/demo/applets/Fractal/example1.html @@ -5,7 +5,7 @@

Fractals 1.1


- + diff --git a/src/share/demo/applets/GraphicsTest/AppletFrame.java b/src/share/demo/applets/GraphicsTest/AppletFrame.java index a4970b1f1f88a0360c9d447b84f32fdeb401664b..bf61a181a7890246f6119c79f9f11a17227f9797 100644 --- a/src/share/demo/applets/GraphicsTest/AppletFrame.java +++ b/src/share/demo/applets/GraphicsTest/AppletFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import java.awt.Frame; import java.awt.Event; @@ -38,66 +36,67 @@ import java.awt.Dimension; import java.applet.Applet; import java.awt.AWTEvent; -// Applet to Application Frame window -class AppletFrame extends Frame -{ + +/** + * Applet to Application Frame window + */ +@SuppressWarnings("serial") +class AppletFrame extends Frame { public static void startApplet(String className, - String title, - String args[]) - { - // local variables - Applet a; - Dimension appletSize; + String title, + String args[]) { + // local variables + Applet a; + Dimension appletSize; - try - { - // create an instance of your applet class - a = (Applet) Class.forName(className).newInstance(); - } - catch (ClassNotFoundException e) { return; } - catch (InstantiationException e) { return; } - catch (IllegalAccessException e) { return; } + try { + // create an instance of your applet class + a = (Applet) Class.forName(className).newInstance(); + } catch (ClassNotFoundException e) { + return; + } catch (InstantiationException e) { + return; + } catch (IllegalAccessException e) { + return; + } - // initialize the applet - a.init(); - a.start(); + // initialize the applet + a.init(); + a.start(); - // create new application frame window - AppletFrame f = new AppletFrame(title); + // create new application frame window + AppletFrame f = new AppletFrame(title); - // add applet to frame window - f.add("Center", a); + // add applet to frame window + f.add("Center", a); - // resize frame window to fit applet - // assumes that the applet sets its own size - // otherwise, you should set a specific size here. - appletSize = a.getSize(); - f.pack(); - f.setSize(appletSize); + // resize frame window to fit applet + // assumes that the applet sets its own size + // otherwise, you should set a specific size here. + appletSize = a.getSize(); + f.pack(); + f.setSize(appletSize); - // show the window - f.show(); + // show the window + f.setVisible(true); } // end startApplet() - // constructor needed to pass window title to class Frame - public AppletFrame(String name) - { - // call java.awt.Frame(String) constructor - super(name); + public AppletFrame(String name) { + // call java.awt.Frame(String) constructor + super(name); } // needed to allow window close - public void processEvent(AWTEvent e) - { - // Window Destroy event - if (e.getID() == Event.WINDOW_DESTROY) - { - // exit the program - System.exit(0); - } - } // end handleEvent() - + @Override + public void processEvent(AWTEvent e) { + // Window Destroy event + if (e.getID() == Event.WINDOW_DESTROY) { + // exit the program + System.exit(0); + } + } // end handleEvent() } // end class AppletFrame + diff --git a/src/share/demo/applets/GraphicsTest/GraphicsTest.java b/src/share/demo/applets/GraphicsTest/GraphicsTest.java index e34c9e8c4e4f0f005aaa39d531de31acc7a04d31..821b119e50a4dc2d0bafdc6d2cba141cf8aa48e9 100644 --- a/src/share/demo/applets/GraphicsTest/GraphicsTest.java +++ b/src/share/demo/applets/GraphicsTest/GraphicsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,22 +29,23 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import java.awt.*; import java.util.*; import java.awt.event.*; import java.applet.Applet; + +@SuppressWarnings("serial") class GraphicsPanel extends Panel { + ActionListener al; ItemListener il; public GraphicsCards cards; - GraphicsPanel(EventListener listener) { - al = (ActionListener)listener; - il = (ItemListener)listener; + GraphicsPanel(EventListener listener) { + al = (ActionListener) listener; + il = (ItemListener) listener; setLayout(new BorderLayout()); @@ -78,62 +79,75 @@ class GraphicsPanel extends Panel { setSize(400, 400); } + @Override public Dimension getPreferredSize() { return new Dimension(200, 100); } } + +@SuppressWarnings("serial") public class GraphicsTest extends Applet -implements ActionListener, ItemListener { + implements ActionListener, ItemListener { + GraphicsPanel mainPanel; + @Override public void init() { setLayout(new BorderLayout()); add("Center", mainPanel = new GraphicsPanel(this)); } + @Override public void destroy() { remove(mainPanel); } + @Override public void actionPerformed(ActionEvent e) { String arg = e.getActionCommand(); if ("next".equals(arg)) { - ((CardLayout)mainPanel.cards.getLayout()).next(mainPanel.cards); - } - else if ("previous".equals(arg)) { - ((CardLayout)mainPanel.cards.getLayout()).previous(mainPanel.cards); + ((CardLayout) mainPanel.cards.getLayout()).next(mainPanel.cards); + } else if ("previous".equals(arg)) { + ((CardLayout) mainPanel.cards.getLayout()).previous(mainPanel.cards); } } + @Override public void itemStateChanged(ItemEvent e) { - ((CardLayout)mainPanel.cards.getLayout()).show(mainPanel.cards,(String)e.getItem()); + ((CardLayout) mainPanel.cards.getLayout()).show(mainPanel.cards, + (String) e.getItem()); } public static void main(String args[]) { AppletFrame.startApplet("GraphicsTest", "Graphics Test", args); } + @Override public String getAppletInfo() { return "An interactive demonstration of some graphics."; } } // end class GraphicsTest +@SuppressWarnings("serial") class GraphicsCards extends Panel { + public GraphicsCards() { setLayout(new CardLayout()); add("Arc", new ArcCard()); - add("Oval", new ShapeTest( new OvalShape() ) ); - add("Polygon", new ShapeTest( new PolygonShape() ) ); - add("Rect", new ShapeTest( new RectShape() ) ); - add("RoundRect", new ShapeTest( new RoundRectShape() ) ); + add("Oval", new ShapeTest(new OvalShape())); + add("Polygon", new ShapeTest(new PolygonShape())); + add("Rect", new ShapeTest(new RectShape())); + add("RoundRect", new ShapeTest(new RoundRectShape())); } } // end class GraphicsCards +@SuppressWarnings("serial") class ArcCard extends Panel { + public ArcCard() { setLayout(new GridLayout(0, 2)); add(new ArcPanel(true)); @@ -144,7 +158,9 @@ class ArcCard extends Panel { } // end class ArcCard +@SuppressWarnings("serial") class ArcDegreePanel extends Panel { + boolean filled; public ArcDegreePanel(boolean filled) { @@ -152,290 +168,262 @@ class ArcDegreePanel extends Panel { } void arcSteps(Graphics g, - int step, - int x, - int y, - int w, - int h, - Color c1, - Color c2) { - int a1 = 0; - int a2 = step; - int progress = 0; - g.setColor(c1); - for (; (a1+a2) <= 360; a1 = a1+a2, a2 += 1) { - if (g.getColor() == c1) { - g.setColor(c2); - } - else { - g.setColor(c1); - } + int step, + int x, + int y, + int w, + int h, + Color c1, + Color c2) { + int a1 = 0; + int a2 = step; + int progress = 0; + g.setColor(c1); + for (; (a1 + a2) <= 360; a1 = a1 + a2, a2 += 1) { + if (g.getColor() == c1) { + g.setColor(c2); + } else { + g.setColor(c1); + } - if (filled) { - g.fillArc(x, y, w, h, a1, a2); - } - else { - g.drawArc(x, y, w, h, a1, a2); - } + if (filled) { + g.fillArc(x, y, w, h, a1, a2); + } else { + g.drawArc(x, y, w, h, a1, a2); + } - progress = a1+a2; - } // end for + progress = a1 + a2; + } // end for - if (progress != 360) { - if (filled) { - g.fillArc(x, y, w, h, a1, 360 - progress); - } - else { - g.drawArc(x, y, w, h, a1, 360 - progress); - } - } // end if - } // end arcSteps() + if (progress != 360) { + if (filled) { + g.fillArc(x, y, w, h, a1, 360 - progress); + } else { + g.drawArc(x, y, w, h, a1, 360 - progress); + } + } // end if + } // end arcSteps() + @Override public void paint(Graphics g) { Rectangle r = getBounds(); arcSteps(g, 3, 0, 0, r.width, r.height, Color.orange, Color.blue); arcSteps(g, - 2, - r.width / 4, - r.height / 4, - r.width / 2, - r.height / 2, - Color.yellow, - Color.green); + 2, + r.width / 4, + r.height / 4, + r.width / 2, + r.height / 2, + Color.yellow, + Color.green); arcSteps(g, - 1, - (r.width * 3) / 8, - (r.height * 3) / 8, - r.width / 4, - r.height / 4, - Color.magenta, - Color.white); - - } // end paint() + 1, + (r.width * 3) / 8, + (r.height * 3) / 8, + r.width / 4, + r.height / 4, + Color.magenta, + Color.white); + + } // end paint() } // end class ArcDegreePanel +@SuppressWarnings("serial") class ArcPanel extends Panel { + boolean filled; public ArcPanel(boolean filled) { - this.filled = filled; - } - - public void paint(Graphics g) - { - Rectangle r = getBounds(); - - g.setColor(Color.yellow); - if (filled) - { - g.fillArc(0, 0, r.width, r.height, 0, 45); - } - else - { - g.drawArc(0, 0, r.width, r.height, 0, 45); - } - - g.setColor(Color.green); - if (filled) - { - g.fillArc(0, 0, r.width, r.height, 90, -45); - } - else - { - g.drawArc(0, 0, r.width, r.height, 90, -45); - } - - g.setColor(Color.orange); - if (filled) - { - g.fillArc(0, 0, r.width, r.height, 135, -45); - } - else - { - g.drawArc(0, 0, r.width, r.height, 135, -45); - } - - g.setColor(Color.magenta); - - if (filled) - { - g.fillArc(0, 0, r.width, r.height, -225, 45); - } - else - { - g.drawArc(0, 0, r.width, r.height, -225, 45); - } - - g.setColor(Color.yellow); - if (filled) - { - g.fillArc(0, 0, r.width, r.height, 225, -45); - } - else - { - g.drawArc(0, 0, r.width, r.height, 225, -45); - } - - g.setColor(Color.green); - if (filled) - { - g.fillArc(0, 0, r.width, r.height, -135, 45); - } - else - { - g.drawArc(0, 0, r.width, r.height, -135, 45); - } - - g.setColor(Color.orange); - if (filled) - { - g.fillArc(0, 0, r.width, r.height, -45, -45); - } - else - { - g.drawArc(0, 0, r.width, r.height, -45, -45); - } - - g.setColor(Color.magenta); - if (filled) - { - g.fillArc(0, 0, r.width, r.height, 315, 45); - } - else - { - g.drawArc(0, 0, r.width, r.height, 315, 45); - } - - } // end paint() + this.filled = filled; + } + + @Override + public void paint(Graphics g) { + Rectangle r = getBounds(); + + g.setColor(Color.yellow); + if (filled) { + g.fillArc(0, 0, r.width, r.height, 0, 45); + } else { + g.drawArc(0, 0, r.width, r.height, 0, 45); + } + + g.setColor(Color.green); + if (filled) { + g.fillArc(0, 0, r.width, r.height, 90, -45); + } else { + g.drawArc(0, 0, r.width, r.height, 90, -45); + } + + g.setColor(Color.orange); + if (filled) { + g.fillArc(0, 0, r.width, r.height, 135, -45); + } else { + g.drawArc(0, 0, r.width, r.height, 135, -45); + } + + g.setColor(Color.magenta); + + if (filled) { + g.fillArc(0, 0, r.width, r.height, -225, 45); + } else { + g.drawArc(0, 0, r.width, r.height, -225, 45); + } + + g.setColor(Color.yellow); + if (filled) { + g.fillArc(0, 0, r.width, r.height, 225, -45); + } else { + g.drawArc(0, 0, r.width, r.height, 225, -45); + } + + g.setColor(Color.green); + if (filled) { + g.fillArc(0, 0, r.width, r.height, -135, 45); + } else { + g.drawArc(0, 0, r.width, r.height, -135, 45); + } + + g.setColor(Color.orange); + if (filled) { + g.fillArc(0, 0, r.width, r.height, -45, -45); + } else { + g.drawArc(0, 0, r.width, r.height, -45, -45); + } + + g.setColor(Color.magenta); + if (filled) { + g.fillArc(0, 0, r.width, r.height, 315, 45); + } else { + g.drawArc(0, 0, r.width, r.height, 315, 45); + } + } // end paint() } // end class ArcPanel -abstract class Shape -{ - abstract void draw(Graphics g, int x, int y, int w, int h); - abstract void fill(Graphics g, int x, int y, int w, int h); +abstract class Shape { + + abstract void draw(Graphics g, int x, int y, int w, int h); + + abstract void fill(Graphics g, int x, int y, int w, int h); } -class RectShape extends Shape -{ - void draw(Graphics g, int x, int y, int w, int h) - { - g.drawRect(x, y, w, h); - } +class RectShape extends Shape { + + @Override + void draw(Graphics g, int x, int y, int w, int h) { + g.drawRect(x, y, w, h); + } - void fill(Graphics g, int x, int y, int w, int h) - { - g.fillRect(x, y, w, h); - } + @Override + void fill(Graphics g, int x, int y, int w, int h) { + g.fillRect(x, y, w, h); + } } -class OvalShape extends Shape -{ - void draw(Graphics g, int x, int y, int w, int h) - { - g.drawOval(x, y, w, h); - } +class OvalShape extends Shape { + + @Override + void draw(Graphics g, int x, int y, int w, int h) { + g.drawOval(x, y, w, h); + } - void fill(Graphics g, int x, int y, int w, int h) - { - g.fillOval(x, y, w, h); - } + @Override + void fill(Graphics g, int x, int y, int w, int h) { + g.fillOval(x, y, w, h); + } } -class RoundRectShape extends Shape -{ - void draw(Graphics g, int x, int y, int w, int h) - { - g.drawRoundRect(x, y, w, h, 10, 10); - } +class RoundRectShape extends Shape { + + @Override + void draw(Graphics g, int x, int y, int w, int h) { + g.drawRoundRect(x, y, w, h, 10, 10); + } - void fill(Graphics g, int x, int y, int w, int h) - { - g.fillRoundRect(x, y, w, h, 10, 10); - } + @Override + void fill(Graphics g, int x, int y, int w, int h) { + g.fillRoundRect(x, y, w, h, 10, 10); + } } -class PolygonShape extends Shape -{ - // class variables - Polygon p; - Polygon pBase; - - public PolygonShape() - { - pBase = new Polygon(); - pBase.addPoint(0, 0); - pBase.addPoint(10, 0); - pBase.addPoint(5, 15); - pBase.addPoint(10, 20); - pBase.addPoint(5, 20); - pBase.addPoint(0, 10); - pBase.addPoint(0, 0); - } - - void scalePolygon(float w, float h) - { - p = new Polygon(); - for (int i = 0; i < pBase.npoints; ++i) - { - p.addPoint( (int) (pBase.xpoints[i] * w), - (int) (pBase.ypoints[i] * h) ); - } - - } - - void draw(Graphics g, int x, int y, int w, int h) - { - Graphics ng = g.create(); - try { - ng.translate(x, y); - scalePolygon( (float) ( (float) w / (float) 10 ), - (float) ( (float) h / (float) 20 ) ); - ng.drawPolygon(p); - } finally { - ng.dispose(); + +class PolygonShape extends Shape { + // class variables + + Polygon p; + Polygon pBase; + + public PolygonShape() { + pBase = new Polygon(); + pBase.addPoint(0, 0); + pBase.addPoint(10, 0); + pBase.addPoint(5, 15); + pBase.addPoint(10, 20); + pBase.addPoint(5, 20); + pBase.addPoint(0, 10); + pBase.addPoint(0, 0); } - } - - void fill(Graphics g, int x, int y, int w, int h) - { - Graphics ng = g.create(); - try { - ng.translate(x, y); - scalePolygon( (float) ( (float) w / (float) 10 ), - (float) ( (float) h / (float) 20 ) ); - ng.fillPolygon(p); - } finally { - ng.dispose(); + + void scalePolygon(float w, float h) { + p = new Polygon(); + for (int i = 0; i < pBase.npoints; ++i) { + p.addPoint((int) (pBase.xpoints[i] * w), + (int) (pBase.ypoints[i] * h)); + } + + } + + @Override + void draw(Graphics g, int x, int y, int w, int h) { + Graphics ng = g.create(); + try { + ng.translate(x, y); + scalePolygon(((float) w / 10f), ((float) h / 20f)); + ng.drawPolygon(p); + } finally { + ng.dispose(); + } + } + + @Override + void fill(Graphics g, int x, int y, int w, int h) { + Graphics ng = g.create(); + try { + ng.translate(x, y); + scalePolygon(((float) w / 10f), ((float) h / 20f)); + ng.fillPolygon(p); + } finally { + ng.dispose(); + } } - } } -class ShapeTest extends Panel -{ - Shape shape; - int step; +@SuppressWarnings("serial") +class ShapeTest extends Panel { - public ShapeTest(Shape shape, int step) - { - this.shape = shape; - this.step = step; - } + Shape shape; + int step; + + public ShapeTest(Shape shape, int step) { + this.shape = shape; + this.step = step; + } - public ShapeTest(Shape shape) - { - this(shape, 10); - } + public ShapeTest(Shape shape) { + this(shape, 10); + } + @Override public void paint(Graphics g) { Rectangle bounds = getBounds(); @@ -443,35 +431,22 @@ class ShapeTest extends Panel Color color; - for (color=Color.red, - cx=bounds.x, - cy=bounds.y, - cw=bounds.width / 2, - ch=bounds.height; - cw > 0 && ch > 0; - - cx+=step, - cy += step, - cw -= (step * 2), - ch -= (step * 2), - color=ColorUtils.darker(color, 0.9) ) { + for (color = Color.red, cx = bounds.x, cy = bounds.y, + cw = bounds.width / 2, ch = bounds.height; + cw > 0 && ch > 0; + cx += step, cy += step, cw -= (step * 2), ch -= (step * 2), + color = ColorUtils.darker(color, 0.9)) { g.setColor(color); shape.draw(g, cx, cy, cw, ch); } - for (cx=bounds.x + bounds.width / 2, - cy=bounds.y, - cw=bounds.width / 2, ch=bounds.height; - cw > 0 && ch > 0; - - cx+=step, - cy += step, - cw -= (step * 2), - ch -= (step * 2) ) { + for (cx = bounds.x + bounds.width / 2, cy = bounds.y, + cw = bounds.width / 2, ch = bounds.height; + cw > 0 && ch > 0; + cx += step, cy += step, cw -= (step * 2), ch -= (step * 2)) { if (g.getColor() == Color.red) { g.setColor(Color.blue); - } - else { + } else { g.setColor(Color.red); } @@ -480,16 +455,18 @@ class ShapeTest extends Panel } // end paint() } // end class ShapeTest + class ColorUtils { + static Color brighter(Color c, double factor) { - return new Color( Math.min((int)(c.getRed() *(1/factor)), 255), - Math.min((int)(c.getGreen()*(1/factor)), 255), - Math.min((int)(c.getBlue() *(1/factor)), 255) ); + return new Color(Math.min((int) (c.getRed() * (1 / factor)), 255), + Math.min((int) (c.getGreen() * (1 / factor)), 255), + Math.min((int) (c.getBlue() * (1 / factor)), 255)); } static Color darker(Color c, double factor) { - return new Color( Math.max((int)(c.getRed() *factor), 0), - Math.max((int)(c.getGreen()*factor), 0), - Math.max((int)(c.getBlue() *factor), 0) ); + return new Color(Math.max((int) (c.getRed() * factor), 0), + Math.max((int) (c.getGreen() * factor), 0), + Math.max((int) (c.getBlue() * factor), 0)); } } diff --git a/src/share/demo/applets/MoleculeViewer/Matrix3D.java b/src/share/demo/applets/MoleculeViewer/Matrix3D.java index bc5939d54bd8bb9574cfcd5c1b0c71710ad6edca..0dda042c3c9a6faeadc7d2d7f27f99112432d2ff 100644 --- a/src/share/demo/applets/MoleculeViewer/Matrix3D.java +++ b/src/share/demo/applets/MoleculeViewer/Matrix3D.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,22 +29,23 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ /** A fairly conventional 3D matrix object that can transform sets of - 3D points and perform a variety of manipulations on the transform */ +3D points and perform a variety of manipulations on the transform */ class Matrix3D { + float xx, xy, xz, xo; float yx, yy, yz, yo; float zx, zy, zz, zo; static final double pi = 3.14159265; + /** Create a new unit matrix */ - Matrix3D () { + Matrix3D() { xx = 1.0f; yy = 1.0f; zz = 1.0f; } + /** Scale by f in all dimensions */ void scale(float f) { xx *= f; @@ -60,6 +61,7 @@ class Matrix3D { zz *= f; zo *= f; } + /** Scale along each axis independently */ void scale(float xf, float yf, float zf) { xx *= xf; @@ -75,12 +77,14 @@ class Matrix3D { zz *= zf; zo *= zf; } + /** Translate the origin */ void translate(float x, float y, float z) { xo += x; yo += y; zo += z; } + /** rotate theta degrees about the y axis */ void yrot(double theta) { theta *= (pi / 180); @@ -106,6 +110,7 @@ class Matrix3D { zy = Nzy; zz = Nzz; } + /** rotate theta degrees about the x axis */ void xrot(double theta) { theta *= (pi / 180); @@ -131,6 +136,7 @@ class Matrix3D { zy = Nzy; zz = Nzz; } + /** rotate theta degrees about the z axis */ void zrot(double theta) { theta *= (pi / 180); @@ -156,6 +162,7 @@ class Matrix3D { xy = Nxy; xz = Nxz; } + /** Multiply this matrix by a second: M = M*R */ void mult(Matrix3D rhs) { float lxx = xx * rhs.xx + yx * rhs.xy + zx * rhs.xz; @@ -204,10 +211,11 @@ class Matrix3D { zy = 0; zz = 1; } + /** Transform nvert points from v into tv. v contains the input - coordinates in floating point. Three successive entries in - the array constitute a point. tv ends up holding the transformed - points as integers; three successive entries per point */ + coordinates in floating point. Three successive entries in + the array constitute a point. tv ends up holding the transformed + points as integers; three successive entries per point */ void transform(float v[], int tv[], int nvert) { float lxx = xx, lxy = xy, lxz = xz, lxo = xo; float lyx = yx, lyy = yy, lyz = yz, lyo = yo; @@ -216,11 +224,13 @@ class Matrix3D { float x = v[i]; float y = v[i + 1]; float z = v[i + 2]; - tv[i ] = (int) (x * lxx + y * lxy + z * lxz + lxo); + tv[i] = (int) (x * lxx + y * lxy + z * lxz + lxo); tv[i + 1] = (int) (x * lyx + y * lyy + z * lyz + lyo); tv[i + 2] = (int) (x * lzx + y * lzy + z * lzz + lzo); } } + + @Override public String toString() { return ("[" + xo + "," + xx + "," + xy + "," + xz + ";" + yo + "," + yx + "," + yy + "," + yz + ";" diff --git a/src/share/demo/applets/MoleculeViewer/XYZApp.java b/src/share/demo/applets/MoleculeViewer/XYZApp.java index 719e6f55ef551bc3a9cdb8aa22afcddd832099ec..78717bef21f07580c134d50bf4020e9e88c4d29c 100644 --- a/src/share/demo/applets/MoleculeViewer/XYZApp.java +++ b/src/share/demo/applets/MoleculeViewer/XYZApp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,37 +29,43 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ - -/* - * A set of classes to parse, represent and display Chemical compounds in - * .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html) - */ import java.applet.Applet; import java.awt.Image; -import java.awt.Event; import java.awt.Graphics; import java.awt.Dimension; -import java.io.*; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; import java.net.URL; -import java.util.Hashtable; import java.awt.image.IndexColorModel; -import java.awt.image.ColorModel; import java.awt.image.MemoryImageSource; -import java.awt.event.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StreamTokenizer; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +/* + * A set of classes to parse, represent and display Chemical compounds in + * .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html) + */ /** The representation of a Chemical .xyz model */ -class XYZChemModel { +final class XYZChemModel { + float vert[]; Atom atoms[]; int tvert[]; int ZsortMap[]; int nvert, maxvert; - - static Hashtable atomTable = new Hashtable(); + static final Map atomTable = new HashMap(); static Atom defaultAtom; + static { atomTable.put("c", new Atom(0, 0, 0)); atomTable.put("h", new Atom(210, 210, 210)); @@ -70,77 +76,72 @@ class XYZChemModel { atomTable.put("hn", new Atom(150, 255, 150)); /* !!*/ defaultAtom = new Atom(255, 100, 200); } - boolean transformed; Matrix3D mat; - float xmin, xmax, ymin, ymax, zmin, zmax; - - XYZChemModel () { + XYZChemModel() { mat = new Matrix3D(); mat.xrot(20); mat.yrot(30); } + /** Create a Chemical model by parsing an input stream */ + XYZChemModel(InputStream is) throws Exception { + this(); + StreamTokenizer st = new StreamTokenizer( + new BufferedReader(new InputStreamReader(is, "UTF-8"))); + st.eolIsSignificant(true); + st.commentChar('#'); + + try { + scan: + while (true) { + switch (st.nextToken()) { + case StreamTokenizer.TT_EOF: + break scan; + default: + break; + case StreamTokenizer.TT_WORD: + String name = st.sval; + double x = 0, + y = 0, + z = 0; + if (st.nextToken() == StreamTokenizer.TT_NUMBER) { + x = st.nval; + if (st.nextToken() == StreamTokenizer.TT_NUMBER) { + y = st.nval; + if (st.nextToken() == StreamTokenizer.TT_NUMBER) { + z = st.nval; + } + } + } + addVert(name, (float) x, (float) y, (float) z); + while (st.ttype != StreamTokenizer.TT_EOL + && st.ttype != StreamTokenizer.TT_EOF) { + st.nextToken(); + } + + } // end Switch + + } // end while + + is.close(); + + } // end Try + catch (IOException e) { + } - /** Create a Cehmical model by parsing an input stream */ - XYZChemModel (InputStream is) throws Exception - { - this(); - StreamTokenizer st = new StreamTokenizer( - new BufferedReader(new InputStreamReader(is, "UTF-8"))); - st.eolIsSignificant(true); - st.commentChar('#'); - int slot = 0; - - try - { -scan: - while (true) - { - switch ( st.nextToken() ) - { - case StreamTokenizer.TT_EOF: - break scan; - default: - break; - case StreamTokenizer.TT_WORD: - String name = st.sval; - double x = 0, y = 0, z = 0; - if (st.nextToken() == StreamTokenizer.TT_NUMBER) - { - x = st.nval; - if (st.nextToken() == StreamTokenizer.TT_NUMBER) - { - y = st.nval; - if (st.nextToken() == StreamTokenizer.TT_NUMBER) - z = st.nval; - } - } - addVert(name, (float) x, (float) y, (float) z); - while( st.ttype != StreamTokenizer.TT_EOL && - st.ttype != StreamTokenizer.TT_EOF ) - st.nextToken(); - - } // end Switch - - } // end while - - is.close(); - - } // end Try - catch( IOException e) {} - - if (st.ttype != StreamTokenizer.TT_EOF) - throw new Exception(st.toString()); + if (st.ttype != StreamTokenizer.TT_EOF) { + throw new Exception(st.toString()); + } } // end XYZChemModel() /** Add a vertex to this model */ int addVert(String name, float x, float y, float z) { int i = nvert; - if (i >= maxvert) + if (i >= maxvert) { if (vert == null) { maxvert = 100; vert = new float[maxvert * 3]; @@ -154,8 +155,11 @@ scan: System.arraycopy(atoms, 0, na, 0, atoms.length); atoms = na; } - Atom a = (Atom) atomTable.get(name.toLowerCase()); - if (a == null) a = defaultAtom; + } + Atom a = atomTable.get(name.toLowerCase()); + if (a == null) { + a = defaultAtom; + } atoms[i] = a; i *= 3; vert[i] = x; @@ -166,29 +170,32 @@ scan: /** Transform all the points in this model */ void transform() { - if (transformed || nvert <= 0) + if (transformed || nvert <= 0) { return; - if (tvert == null || tvert.length < nvert * 3) + } + if (tvert == null || tvert.length < nvert * 3) { tvert = new int[nvert * 3]; + } mat.transform(vert, tvert, nvert); transformed = true; } - /** Paint this model to a graphics context. It uses the matrix associated - with this model to map from model space to screen space. - The next version of the browser should have double buffering, - which will make this *much* nicer */ + with this model to map from model space to screen space. + The next version of the browser should have double buffering, + which will make this *much* nicer */ void paint(Graphics g) { - if (vert == null || nvert <= 0) + if (vert == null || nvert <= 0) { return; + } transform(); int v[] = tvert; int zs[] = ZsortMap; if (zs == null) { ZsortMap = zs = new int[nvert]; - for (int i = nvert; --i >= 0;) + for (int i = nvert; --i >= 0;) { zs[i] = i * 3; + } } /* @@ -209,24 +216,26 @@ scan: flipped = true; } } - if (!flipped) + if (!flipped) { break; + } } - int lg = 0; int lim = nvert; - Atom ls[] = atoms; - if (lim <= 0 || nvert <= 0) + if (lim <= 0 || nvert <= 0) { return; + } for (int i = 0; i < lim; i++) { int j = zs[i]; int grey = v[j + 2]; - if (grey < 0) + if (grey < 0) { grey = 0; - if (grey > 15) + } + if (grey > 15) { grey = 15; + } // g.drawString(names[i], v[j], v[j+1]); - atoms[j/3].paint(g, v[j], v[j + 1], grey); + atoms[j / 3].paint(g, v[j], v[j + 1], grey); // g.drawImage(iBall, v[j] - (iBall.width >> 1), v[j + 1] - // (iBall.height >> 1)); } @@ -234,47 +243,55 @@ scan: /** Find the bounding box of this model */ void findBB() { - if (nvert <= 0) + if (nvert <= 0) { return; + } float v[] = vert; - float xmin = v[0], xmax = xmin; - float ymin = v[1], ymax = ymin; - float zmin = v[2], zmax = zmin; + float _xmin = v[0], _xmax = _xmin; + float _ymin = v[1], _ymax = _ymin; + float _zmin = v[2], _zmax = _zmin; for (int i = nvert * 3; (i -= 3) > 0;) { float x = v[i]; - if (x < xmin) - xmin = x; - if (x > xmax) - xmax = x; + if (x < _xmin) { + _xmin = x; + } + if (x > _xmax) { + _xmax = x; + } float y = v[i + 1]; - if (y < ymin) - ymin = y; - if (y > ymax) - ymax = y; + if (y < _ymin) { + _ymin = y; + } + if (y > _ymax) { + _ymax = y; + } float z = v[i + 2]; - if (z < zmin) - zmin = z; - if (z > zmax) - zmax = z; + if (z < _zmin) { + _zmin = z; + } + if (z > _zmax) { + _zmax = z; + } } - this.xmax = xmax; - this.xmin = xmin; - this.ymax = ymax; - this.ymin = ymin; - this.zmax = zmax; - this.zmin = zmin; + this.xmax = _xmax; + this.xmin = _xmin; + this.ymax = _ymax; + this.ymin = _ymin; + this.zmax = _zmax; + this.zmin = _zmin; } } + /** An applet to put a Chemical model into a page */ -public class XYZApp - extends Applet - implements Runnable, MouseListener, MouseMotionListener { +@SuppressWarnings("serial") +public class XYZApp extends Applet implements Runnable, MouseListener, + MouseMotionListener { + XYZChemModel md; boolean painted = true; float xfac; int prevx, prevy; - float xtheta, ytheta; float scalefudge = 1; Matrix3D amat = new Matrix3D(), tmat = new Matrix3D(); String mdname = null; @@ -283,7 +300,6 @@ public class XYZApp Graphics backGC; Dimension backSize; - private synchronized void newBackBuffer() { backBuffer = createImage(getSize().width, getSize().height); if (backGC != null) { @@ -293,164 +309,190 @@ public class XYZApp backSize = getSize(); } + @Override public void init() { mdname = getParameter("model"); try { scalefudge = Float.valueOf(getParameter("scale")).floatValue(); - } catch(Exception e) { - }; + } catch (Exception ignored) { + } amat.yrot(20); amat.xrot(20); - if (mdname == null) + if (mdname == null) { mdname = "model.obj"; + } resize(getSize().width <= 20 ? 400 : getSize().width, - getSize().height <= 20 ? 400 : getSize().height); + getSize().height <= 20 ? 400 : getSize().height); newBackBuffer(); addMouseListener(this); addMouseMotionListener(this); } + @Override public void destroy() { removeMouseListener(this); removeMouseMotionListener(this); } + @Override public void run() { InputStream is = null; try { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); is = new URL(getDocumentBase(), mdname).openStream(); - XYZChemModel m = new XYZChemModel (is); + XYZChemModel m = new XYZChemModel(is); Atom.setApplet(this); md = m; m.findBB(); float xw = m.xmax - m.xmin; float yw = m.ymax - m.ymin; float zw = m.zmax - m.zmin; - if (yw > xw) + if (yw > xw) { xw = yw; - if (zw > xw) + } + if (zw > xw) { xw = zw; + } float f1 = getSize().width / xw; float f2 = getSize().height / xw; xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge; - } catch(Exception e) { - e.printStackTrace(); + } catch (Exception e) { + Logger.getLogger(XYZApp.class.getName()).log(Level.SEVERE, null, e); md = null; message = e.toString(); } try { - if (is != null) + if (is != null) { is.close(); - } catch(Exception e) { + } + } catch (Exception ignored) { } repaint(); } + + @Override public void start() { - if (md == null && message == null) + if (md == null && message == null) { new Thread(this).start(); + } } + + @Override public void stop() { } - /* event handling */ - public void mouseClicked(MouseEvent e) { - } - public void mousePressed(MouseEvent e) { - prevx = e.getX(); - prevy = e.getY(); - e.consume(); - } - public void mouseReleased(MouseEvent e) { - } - public void mouseEntered(MouseEvent e) { - } - public void mouseExited(MouseEvent e) { - } - public void mouseDragged(MouseEvent e) { - int x = e.getX(); - int y = e.getY(); - tmat.unit(); - float xtheta = (prevy - y) * (360.0f / getSize().width); - float ytheta = (x - prevx) * (360.0f / getSize().height); - tmat.xrot(xtheta); - tmat.yrot(ytheta); - amat.mult(tmat); - if (painted) { - painted = false; - repaint(); + /* event handling */ + + @Override + public void mouseClicked(MouseEvent e) { } - prevx = x; - prevy = y; - e.consume(); - } - public void mouseMoved(MouseEvent e) { - } + @Override + public void mousePressed(MouseEvent e) { + prevx = e.getX(); + prevy = e.getY(); + e.consume(); + } + + @Override + public void mouseReleased(MouseEvent e) { + } + + @Override + public void mouseEntered(MouseEvent e) { + } + + @Override + public void mouseExited(MouseEvent e) { + } + + @Override + public void mouseDragged(MouseEvent e) { + int x = e.getX(); + int y = e.getY(); + tmat.unit(); + float xtheta = (prevy - y) * (360.0f / getSize().width); + float ytheta = (x - prevx) * (360.0f / getSize().height); + tmat.xrot(xtheta); + tmat.yrot(ytheta); + amat.mult(tmat); + if (painted) { + painted = false; + repaint(); + } + prevx = x; + prevy = y; + e.consume(); + } + + @Override + public void mouseMoved(MouseEvent e) { + } + + @Override public void update(Graphics g) { - if (backBuffer == null) + if (backBuffer == null) { g.clearRect(0, 0, getSize().width, getSize().height); + } paint(g); } + @Override public void paint(Graphics g) { if (md != null) { md.mat.unit(); md.mat.translate(-(md.xmin + md.xmax) / 2, - -(md.ymin + md.ymax) / 2, - -(md.zmin + md.zmax) / 2); + -(md.ymin + md.ymax) / 2, + -(md.zmin + md.zmax) / 2); md.mat.mult(amat); // md.mat.scale(xfac, -xfac, 8 * xfac / getSize().width); md.mat.scale(xfac, -xfac, 16 * xfac / getSize().width); md.mat.translate(getSize().width / 2, getSize().height / 2, 8); md.transformed = false; if (backBuffer != null) { - if (!backSize.equals(getSize())) + if (!backSize.equals(getSize())) { newBackBuffer(); + } backGC.setColor(getBackground()); - backGC.fillRect(0,0,getSize().width,getSize().height); + backGC.fillRect(0, 0, getSize().width, getSize().height); md.paint(backGC); g.drawImage(backBuffer, 0, 0, this); - } - else + } else { md.paint(g); + } setPainted(); } else if (message != null) { g.drawString("Error in model:", 3, 20); g.drawString(message, 10, 40); } } + private synchronized void setPainted() { painted = true; notifyAll(); } - private synchronized void waitPainted() - { - while (!painted) - { - try - { - wait(); - } - catch (InterruptedException e) {} - } - painted = false; + @Override + public String getAppletInfo() { + return "Title: XYZApp \nAuthor: James Gosling \nAn applet to put" + + " a Chemical model into a page."; } - public String getAppletInfo() { - return "Title: XYZApp \nAuthor: James Gosling \nAn applet to put a Chemical model into a page."; - } - - public String[][] getParameterInfo() { - String[][] info = { - {"model", "path string", "The path to the model to be displayed in .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html). Default is model.obj."}, - {"scale", "float", "Scale factor. Default is 1 (i.e. no scale)."} - }; - return info; - } + @Override + public String[][] getParameterInfo() { + String[][] info = { + { "model", "path string", "The path to the model to be displayed" + + " in .xyz format " + + "(see http://chem.leeds.ac.uk/Project/MIME.html)." + + " Default is model.obj." }, + { "scale", "float", "Scale factor. Default is 1 (i.e. no scale)." } + }; + return info; + } } // end class XYZApp + class Atom { + private static Applet applet; private static byte[] data; private final static int R = 40; @@ -459,7 +501,6 @@ class Atom { private final static int bgGrey = 192; private final static int nBalls = 16; private static int maxr; - private int Rl; private int Gl; private int Bl; @@ -475,24 +516,29 @@ class Atom { int x = X + hx; int y = Y - R + hy; int r = (int) (Math.sqrt(x * x + y * y) + 0.5); - if (r > mr) + if (r > mr) { mr = r; + } data[p++] = r <= 0 ? 1 : (byte) r; } } maxr = mr; } + static void setApplet(Applet app) { applet = app; } + Atom(int Rl, int Gl, int Bl) { this.Rl = Rl; this.Gl = Gl; this.Bl = Bl; } - private final int blend(int fg, int bg, float fgfactor) { + + private int blend(int fg, int bg, float fgfactor) { return (int) (bg + (fg - bg) * fgfactor); } + private void Setup() { balls = new Image[nBalls]; byte red[] = new byte[256]; @@ -502,7 +548,7 @@ class Atom { byte blue[] = new byte[256]; blue[0] = (byte) bgGrey; for (int r = 0; r < nBalls; r++) { - float b = (float) (r+1) / nBalls; + float b = (float) (r + 1) / nBalls; for (int i = maxr; i >= 1; --i) { float d = (float) i / maxr; red[i] = (byte) blend(blend(Rl, 255, d), bgGrey, b); @@ -510,11 +556,12 @@ class Atom { blue[i] = (byte) blend(blend(Bl, 255, d), bgGrey, b); } IndexColorModel model = new IndexColorModel(8, maxr + 1, - red, green, blue, 0); + red, green, blue, 0); balls[r] = applet.createImage( - new MemoryImageSource(R*2, R*2, model, data, 0, R*2)); + new MemoryImageSource(R * 2, R * 2, model, data, 0, R * 2)); } } + void paint(Graphics gc, int x, int y, int r) { Image ba[] = balls; if (ba == null) { diff --git a/src/share/demo/applets/MoleculeViewer/example1.html b/src/share/demo/applets/MoleculeViewer/example1.html index f8b708136c396e60f28f007d81f2c9287f252bbf..de2e84b09431d4d8086372bec08e3fc79af14a82 100644 --- a/src/share/demo/applets/MoleculeViewer/example1.html +++ b/src/share/demo/applets/MoleculeViewer/example1.html @@ -6,7 +6,7 @@

MoleculeViewer (example 1)


- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag! diff --git a/src/share/demo/applets/MoleculeViewer/example2.html b/src/share/demo/applets/MoleculeViewer/example2.html index 5570180908815af48391cb3130b095f7318cbb27..bb8f93a0b3184076953fd56b9ff3772300d86b94 100644 --- a/src/share/demo/applets/MoleculeViewer/example2.html +++ b/src/share/demo/applets/MoleculeViewer/example2.html @@ -6,7 +6,7 @@

MoleculeViewer (example 2)


- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag! diff --git a/src/share/demo/applets/MoleculeViewer/example3.html b/src/share/demo/applets/MoleculeViewer/example3.html index 2542706f1bf2adf81d8de9e0f7c8b33e9258ced7..952bc8d5cbd977775c04560b55ff570a36eec28a 100644 --- a/src/share/demo/applets/MoleculeViewer/example3.html +++ b/src/share/demo/applets/MoleculeViewer/example3.html @@ -6,25 +6,25 @@

MoleculeViewer (example 3)


- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag!

- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag!

- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag!

- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag! diff --git a/src/share/demo/applets/NervousText/NervousText.java b/src/share/demo/applets/NervousText/NervousText.java index e36b61ddb85d784cbde92123b59760d1d348659a..c3d8d0889e0f0a689670cc6bbc181fa85e9b5a41 100644 --- a/src/share/demo/applets/NervousText/NervousText.java +++ b/src/share/demo/applets/NervousText/NervousText.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,37 +29,37 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.event.*; import java.awt.Graphics; import java.awt.Font; import java.applet.Applet; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + /** * An applet that displays jittering text on the screen. * * @author Daniel Wyszynski 04/12/95 - * @modified 05/09/95 kwalrath Changed string; added thread suspension - * @modified 02/06/98 madbot removed use of suspend and resume and cleaned up + * @author 05/09/95 kwalrath Changed string; added thread suspension + * @author 02/06/98 madbot removed use of suspend and resume and cleaned up */ - +@SuppressWarnings("serial") public class NervousText extends Applet implements Runnable, MouseListener { + String banner; // The text to be displayed char bannerChars[]; // The same text as an array of characters char attributes[]; // Character attributes ('^' for superscript) Thread runner = null; // The thread that is displaying the text boolean threadSuspended; // True when thread suspended (via mouse click) - static final int REGULAR_WD = 15; static final int REGULAR_HT = 36; static final int SMALL_WD = 12; static final int SMALL_HT = 24; - Font regularFont = new Font("Serif", Font.BOLD, REGULAR_HT); Font smallFont = new Font("Serif", Font.BOLD, SMALL_HT); + @Override public void init() { banner = getParameter("text"); if (banner == null) { @@ -67,8 +67,8 @@ public class NervousText extends Applet implements Runnable, MouseListener { } int bannerLength = banner.length(); - StringBuffer bc = new StringBuffer(bannerLength); - StringBuffer attrs = new StringBuffer(bannerLength); + StringBuilder bc = new StringBuilder(bannerLength); + StringBuilder attrs = new StringBuilder(bannerLength); int wd = 0; for (int i = 0; i < bannerLength; i++) { char c = banner.charAt(i); @@ -89,7 +89,7 @@ public class NervousText extends Applet implements Runnable, MouseListener { } bannerLength = bc.length(); - bannerChars = new char[bannerLength]; + bannerChars = new char[bannerLength]; attributes = new char[bannerLength]; bc.getChars(0, bannerLength, bannerChars, 0); attrs.getChars(0, bannerLength, attributes, 0); @@ -99,15 +99,18 @@ public class NervousText extends Applet implements Runnable, MouseListener { addMouseListener(this); } + @Override public void destroy() { removeMouseListener(this); } + @Override public void start() { runner = new Thread(this); runner.start(); } + @Override public synchronized void stop() { runner = null; if (threadSuspended) { @@ -116,22 +119,24 @@ public class NervousText extends Applet implements Runnable, MouseListener { } } + @Override public void run() { Thread me = Thread.currentThread(); while (runner == me) { try { Thread.sleep(100); - synchronized(this) { + synchronized (this) { while (threadSuspended) { wait(); } } - } catch (InterruptedException e){ + } catch (InterruptedException e) { } repaint(); } } + @Override public void paint(Graphics g) { int length = bannerChars.length; for (int i = 0, x = 0; i < length; i++) { @@ -152,33 +157,41 @@ public class NervousText extends Applet implements Runnable, MouseListener { } } + @Override public synchronized void mousePressed(MouseEvent e) { e.consume(); threadSuspended = !threadSuspended; - if (!threadSuspended) + if (!threadSuspended) { notify(); + } } + @Override public void mouseReleased(MouseEvent e) { } + @Override public void mouseEntered(MouseEvent e) { } + @Override public void mouseExited(MouseEvent e) { } + @Override public void mouseClicked(MouseEvent e) { } + @Override public String getAppletInfo() { - return "Title: NervousText\nAuthor: Daniel Wyszynski\nDisplays a text banner that jitters."; + return "Title: NervousText\nAuthor: Daniel Wyszynski\n" + + "Displays a text banner that jitters."; } + @Override public String[][] getParameterInfo() { String pinfo[][] = { - {"text", "string", "Text to display"}, - }; + { "text", "string", "Text to display" }, }; return pinfo; } } diff --git a/src/share/demo/applets/SimpleGraph/GraphApplet.java b/src/share/demo/applets/SimpleGraph/GraphApplet.java index 833d86c1aa038c98389fafcb7ff84fd4cc9df50a..b1d166a050a48971c786548ea67a99f2f5ae5d8d 100644 --- a/src/share/demo/applets/SimpleGraph/GraphApplet.java +++ b/src/share/demo/applets/SimpleGraph/GraphApplet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,22 +29,26 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import java.awt.Graphics; + +@SuppressWarnings("serial") public class GraphApplet extends java.applet.Applet { + double f(double x) { - return (Math.cos(x/5) + Math.sin(x/7) + 2) * getSize().height / 4; + return (Math.cos(x / 5) + Math.sin(x / 7) + 2) * getSize().height / 4; } + @Override public void paint(Graphics g) { - for (int x = 0 ; x < getSize().width ; x++) { - g.drawLine(x, (int)f(x), x + 1, (int)f(x + 1)); + for (int x = 0; x < getSize().width; x++) { + g.drawLine(x, (int) f(x), x + 1, (int) f(x + 1)); } } - public String getAppletInfo() { - return "Draws a sin graph."; - } + + @Override + public String getAppletInfo() { + return "Draws a sin graph."; + } } diff --git a/src/share/demo/applets/SortDemo/BidirBubbleSortAlgorithm.java b/src/share/demo/applets/SortDemo/BidirBubbleSortAlgorithm.java index 24496b8aaa26f1d8f29cc21b19330535b3f44c9e..6a54d649d1b66fd60df09cf7bc4ee7866e338ce2 100644 --- a/src/share/demo/applets/SortDemo/BidirBubbleSortAlgorithm.java +++ b/src/share/demo/applets/SortDemo/BidirBubbleSortAlgorithm.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ /** * A bi-directional bubble sort demonstration algorithm @@ -39,6 +37,8 @@ * @author James Gosling */ class BidirBubbleSortAlgorithm extends SortAlgorithm { + + @Override void sort(int a[]) throws Exception { int j; int limit = a.length; @@ -61,9 +61,9 @@ class BidirBubbleSortAlgorithm extends SortAlgorithm { } if (!swapped) { return; - } - else + } else { swapped = false; + } for (j = limit; --j >= st;) { if (stopRequested) { return; diff --git a/src/share/demo/applets/SortDemo/BubbleSortAlgorithm.java b/src/share/demo/applets/SortDemo/BubbleSortAlgorithm.java index 40f54c8cd7a77c7617c522ed6e8af7ef842de5d4..62be88cc58690ab12833ef7f8da3557de59d4d2d 100644 --- a/src/share/demo/applets/SortDemo/BubbleSortAlgorithm.java +++ b/src/share/demo/applets/SortDemo/BubbleSortAlgorithm.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ /** * A bubble sort demonstration algorithm @@ -39,23 +37,26 @@ * @author James Gosling */ class BubbleSortAlgorithm extends SortAlgorithm { + + @Override void sort(int a[]) throws Exception { - for (int i = a.length; --i>=0; ) { + for (int i = a.length; --i >= 0;) { boolean swapped = false; - for (int j = 0; j a[j+1]) { + if (a[j] > a[j + 1]) { int T = a[j]; - a[j] = a[j+1]; - a[j+1] = T; + a[j] = a[j + 1]; + a[j + 1] = T; swapped = true; } - pause(i,j); + pause(i, j); } - if (!swapped) + if (!swapped) { return; + } } } } diff --git a/src/share/demo/applets/SortDemo/QSortAlgorithm.java b/src/share/demo/applets/SortDemo/QSortAlgorithm.java index 37108713852b9a1d5120b4c376041687f5a080b2..7fa48903e5051dba8465a4cece57d538a374ef9f 100644 --- a/src/share/demo/applets/SortDemo/QSortAlgorithm.java +++ b/src/share/demo/applets/SortDemo/QSortAlgorithm.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ /** * A quick sort demonstration algorithm @@ -39,8 +37,7 @@ * @author James Gosling * @author Kevin A. Smith */ -public class QSortAlgorithm extends SortAlgorithm -{ +public class QSortAlgorithm extends SortAlgorithm { /** * A version of pause() that makes it easier to ensure that we pause @@ -51,84 +48,83 @@ public class QSortAlgorithm extends SortAlgorithm return true; } - /** This is a generic version of C.A.R Hoare's Quick Sort - * algorithm. This will handle arrays that are already - * sorted, and arrays with duplicate keys.
- * - * If you think of a one dimensional array as going from - * the lowest index on the left to the highest index on the right - * then the parameters to this function are lowest index or - * left and highest index or right. The first time you call - * this function it will be with the parameters 0, a.length - 1. - * - * @param a an integer array - * @param lo0 left boundary of array partition - * @param hi0 right boundary of array partition - */ - void QuickSort(int a[], int lo0, int hi0) throws Exception - { - int lo = lo0; - int hi = hi0; - int mid; - - if ( hi0 > lo0) - { + /** This is a generic version of C.A.R Hoare's Quick Sort + * algorithm. This will handle arrays that are already + * sorted, and arrays with duplicate keys.
+ * + * If you think of a one dimensional array as going from + * the lowest index on the left to the highest index on the right + * then the parameters to this function are lowest index or + * left and highest index or right. The first time you call + * this function it will be with the parameters 0, a.length - 1. + * + * @param a an integer array + * @param lo0 left boundary of array partition + * @param hi0 right boundary of array partition + */ + void QuickSort(int a[], int lo0, int hi0) throws Exception { + int lo = lo0; + int hi = hi0; + int mid; - /* Arbitrarily establishing partition element as the midpoint of - * the array. - */ - mid = a[ ( lo0 + hi0 ) / 2 ]; + if (hi0 > lo0) { - // loop through the array until indices cross - while( lo <= hi ) - { - /* find the first element that is greater than or equal to - * the partition element starting from the left Index. + /* Arbitrarily establishing partition element as the midpoint of + * the array. */ - while( ( lo < hi0 ) && pauseTrue(lo0, hi0) && ( a[lo] < mid )) - ++lo; + mid = a[(lo0 + hi0) / 2]; - /* find an element that is smaller than or equal to - * the partition element starting from the right Index. - */ - while( ( hi > lo0 ) && pauseTrue(lo0, hi0) && ( a[hi] > mid )) - --hi; + // loop through the array until indices cross + while (lo <= hi) { + /* find the first element that is greater than or equal to + * the partition element starting from the left Index. + */ + while ((lo < hi0) && pauseTrue(lo0, hi0) && (a[lo] < mid)) { + ++lo; + } + + /* find an element that is smaller than or equal to + * the partition element starting from the right Index. + */ + while ((hi > lo0) && pauseTrue(lo0, hi0) && (a[hi] > mid)) { + --hi; + } - // if the indexes have not crossed, swap - if( lo <= hi ) - { - swap(a, lo, hi); - ++lo; - --hi; + // if the indexes have not crossed, swap + if (lo <= hi) { + swap(a, lo, hi); + ++lo; + --hi; + } } - } - /* If the right index has not reached the left side of array - * must now sort the left partition. - */ - if( lo0 < hi ) - QuickSort( a, lo0, hi ); + /* If the right index has not reached the left side of array + * must now sort the left partition. + */ + if (lo0 < hi) { + QuickSort(a, lo0, hi); + } - /* If the left index has not reached the right side of array - * must now sort the right partition. - */ - if( lo < hi0 ) - QuickSort( a, lo, hi0 ); + /* If the left index has not reached the right side of array + * must now sort the right partition. + */ + if (lo < hi0) { + QuickSort(a, lo, hi0); + } - } - } + } + } - private void swap(int a[], int i, int j) - { - int T; - T = a[i]; - a[i] = a[j]; - a[j] = T; + private void swap(int a[], int i, int j) { + int T; + T = a[i]; + a[i] = a[j]; + a[j] = T; - } + } - public void sort(int a[]) throws Exception - { - QuickSort(a, 0, a.length - 1); - } + @Override + public void sort(int a[]) throws Exception { + QuickSort(a, 0, a.length - 1); + } } diff --git a/src/share/demo/applets/SortDemo/SortAlgorithm.java b/src/share/demo/applets/SortDemo/SortAlgorithm.java index c97a6266c124198d7879c4d62d812dc70080ecb2..8917cf94189036408c338652df6685105602756c 100644 --- a/src/share/demo/applets/SortDemo/SortAlgorithm.java +++ b/src/share/demo/applets/SortDemo/SortAlgorithm.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ /** * A generic sort demonstration algorithm @@ -38,13 +36,12 @@ * * @author James Gosling */ - class SortAlgorithm { + /** * The sort item. */ private SortItem parent; - /** * When true stop sorting. */ diff --git a/src/share/demo/applets/SortDemo/SortItem.java b/src/share/demo/applets/SortDemo/SortItem.java index da466c1cbfd68e26a6d59adf2888eae9d5992b1d..9a155e37bd7709d80978955e085a991f12be1dde 100644 --- a/src/share/demo/applets/SortDemo/SortItem.java +++ b/src/share/demo/applets/SortDemo/SortItem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,57 +29,50 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.*; -import java.awt.event.*; -import java.io.InputStream; -import java.util.Hashtable; -import java.net.*; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + /** * A simple applet class to demonstrate a sort algorithm. * You can specify a sorting algorithm using the "alg" - * attribyte. When you click on the applet, a thread is + * attribute. When you click on the applet, a thread is * forked which animates the sorting algorithm. * * @author James Gosling */ -public class SortItem - extends java.applet.Applet - implements Runnable, MouseListener { +@SuppressWarnings("serial") +public class SortItem extends java.applet.Applet implements Runnable, + MouseListener { /** * The thread that is sorting (or null). */ private Thread kicker; - /** * The array that is being sorted. */ int arr[]; - /** * The high water mark. */ int h1 = -1; - /** * The low water mark. */ int h2 = -1; - /** * The name of the algorithm. */ String algName; - /** * The sorting algorithm (or null). */ SortAlgorithm algorithm; - Dimension initialSize = null; /** @@ -91,10 +84,10 @@ public class SortItem double f = initialSize.width / (double) a.length; for (int i = a.length; --i >= 0;) { - a[i] = (int)(i * f); + a[i] = (int) (i * f); } for (int i = a.length; --i >= 0;) { - int j = (int)(i * Math.random()); + int j = (int) (i * Math.random()); int t = a[i]; a[i] = a[j]; a[j] = t; @@ -128,12 +121,16 @@ public class SortItem if (kicker != null) { repaint(); } - try {Thread.sleep(20);} catch (InterruptedException e){} + try { + Thread.sleep(20); + } catch (InterruptedException e) { + } } /** * Initialize the applet. */ + @Override public void init() { String at = getParameter("alg"); if (at == null) { @@ -147,6 +144,7 @@ public class SortItem addMouseListener(this); } + @Override public void start() { h1 = h2 = -1; scramble(); @@ -157,6 +155,7 @@ public class SortItem /** * Deallocate resources of applet. */ + @Override public void destroy() { removeMouseListener(this); } @@ -165,10 +164,11 @@ public class SortItem * Paint the array of numbers as a list * of horizontal lines of varying lengths. */ + @Override public void paint(Graphics g) { int a[] = arr; int y = 0; - int deltaY = 0, deltaX = 0, evenY = 0, evenX = 0; + int deltaY = 0, deltaX = 0, evenY = 0; Dimension currentSize = getSize(); int currentHeight = currentSize.height; @@ -184,7 +184,6 @@ public class SortItem // even size. if (!currentSize.equals(initialSize)) { evenY = (currentHeight - initialSize.height) % 2; - evenX = (currentWidth - initialSize.width) % 2; deltaY = (currentHeight - initialSize.height) / 2; deltaX = (currentWidth - initialSize.width) / 2; @@ -194,7 +193,6 @@ public class SortItem } if (deltaX < 0) { deltaX = 0; - evenX = 0; } } @@ -227,6 +225,7 @@ public class SortItem /** * Update without erasing the background. */ + @Override public void update(Graphics g) { paint(g); } @@ -238,15 +237,16 @@ public class SortItem * @see java.lang.Thread#run * @see SortItem#mouseUp */ + @Override public void run() { try { if (algorithm == null) { - algorithm = (SortAlgorithm)Class.forName(algName).newInstance(); + algorithm = (SortAlgorithm) Class.forName(algName).newInstance(); algorithm.setParent(this); } algorithm.init(); algorithm.sort(arr); - } catch(Exception e) { + } catch (Exception e) { } } @@ -254,8 +254,9 @@ public class SortItem * Stop the applet. Kill any sorting algorithm that * is still sorting. */ + @Override public synchronized void stop() { - if (algorithm != null){ + if (algorithm != null) { try { algorithm.stop(); } catch (IllegalThreadStateException e) { @@ -279,35 +280,42 @@ public class SortItem } } - + @Override public void mouseClicked(MouseEvent e) { showStatus(getParameter("alg")); } + @Override public void mousePressed(MouseEvent e) { } /** * The user clicked in the applet. Start the clock! */ + @Override public void mouseReleased(MouseEvent e) { startSort(); e.consume(); } + @Override public void mouseEntered(MouseEvent e) { } + @Override public void mouseExited(MouseEvent e) { } + @Override public String getAppletInfo() { return "Title: SortDemo \nAuthor: James Gosling 1.17f, 10 Apr 1995 \nA simple applet class to demonstrate a sort algorithm. \nYou can specify a sorting algorithm using the 'alg' attribute. \nWhen you click on the applet, a thread is forked which animates \nthe sorting algorithm."; } + @Override public String[][] getParameterInfo() { String[][] info = { - {"alg", "string", "The name of the algorithm to run. You can choose from the provided algorithms or suppply your own, as long as the classes are runnable as threads and their names end in 'Algorithm.' BubbleSort is the default. Example: Use 'QSort' to run the QSortAlgorithm class."} + { "alg", "string", + "The name of the algorithm to run. You can choose from the provided algorithms or suppply your own, as long as the classes are runnable as threads and their names end in 'Algorithm.' BubbleSort is the default. Example: Use 'QSort' to run the QSortAlgorithm class." } }; return info; } diff --git a/src/share/demo/applets/SortDemo/example1.html b/src/share/demo/applets/SortDemo/example1.html index deab540d22cf4520ae6e5d5f35fe8c44cbe11077..537494518fabb29bfa911a2d7f41edb05f3b3ea1 100644 --- a/src/share/demo/applets/SortDemo/example1.html +++ b/src/share/demo/applets/SortDemo/example1.html @@ -6,7 +6,7 @@

The Sorting Algorithm Demo (1.1)


- +
diff --git a/src/share/demo/applets/SpreadSheet/SpreadSheet.java b/src/share/demo/applets/SpreadSheet/SpreadSheet.java index 6f0c664465b6f3311b8814054e7e2994384ec1bb..d221e342def11d902a48f0c69d5fe86d1c400b0d 100644 --- a/src/share/demo/applets/SpreadSheet/SpreadSheet.java +++ b/src/share/demo/applets/SpreadSheet/SpreadSheet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,39 +29,38 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.io.*; -import java.lang.*; import java.net.*; -public class SpreadSheet - extends Applet - implements MouseListener, KeyListener { - String title; - Font titleFont; - Color cellColor; - Color inputColor; - int cellWidth = 100; - int cellHeight = 15; - int titleHeight = 15; - int rowLabelWidth = 15; - Font inputFont; - boolean isStopped = false; - boolean fullUpdate = true; - int rows; - int columns; - int currentKey = -1; - int selectedRow = -1; - int selectedColumn = -1; - SpreadSheetInput inputArea; - Cell cells[][]; - Cell current = null; +@SuppressWarnings("serial") +public class SpreadSheet extends Applet implements MouseListener, KeyListener { + + String title; + Font titleFont; + Color cellColor; + Color inputColor; + int cellWidth = 100; + int cellHeight = 15; + int titleHeight = 15; + int rowLabelWidth = 15; + Font inputFont; + boolean isStopped = false; + boolean fullUpdate = true; + int rows; + int columns; + int currentKey = -1; + int selectedRow = -1; + int selectedColumn = -1; + SpreadSheetInput inputArea; + Cell cells[][]; + Cell current = null; + + @Override public synchronized void init() { String rs; @@ -87,17 +86,17 @@ public class SpreadSheet } cells = new Cell[rows][columns]; char l[] = new char[1]; - for (int i=0; i < rows; i++) { - for (int j=0; j < columns; j++) { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { cells[i][j] = new Cell(this, - Color.lightGray, - Color.black, - cellColor, - cellWidth - 2, - cellHeight - 2); - l[0] = (char)((int)'a' + j); - rs = getParameter("" + new String(l) + (i+1)); + Color.lightGray, + Color.black, + cellColor, + cellWidth - 2, + cellHeight - 2); + l[0] = (char) ((int) 'a' + j); + rs = getParameter("" + new String(l) + (i + 1)); if (rs != null) { cells[i][j].setUnparsedValue(rs); } @@ -106,9 +105,9 @@ public class SpreadSheet Dimension d = getSize(); inputArea = new SpreadSheetInput(null, this, d.width - 2, cellHeight - 1, - inputColor, Color.white); + inputColor, Color.white); resize(columns * cellWidth + rowLabelWidth, - (rows + 3) * cellHeight + titleHeight); + (rows + 3) * cellHeight + titleHeight); addMouseListener(this); addKeyListener(this); } @@ -121,19 +120,22 @@ public class SpreadSheet repaint(); } + @Override public void stop() { isStopped = true; } + @Override public void start() { isStopped = false; } + @Override public void destroy() { - for (int i=0; i < rows; i++) { - for (int j=0; j < columns; j++) { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { if (cells[i][j].type == Cell.URL) { - cells[i][j].updaterThread.stop(); + cells[i][j].updaterThread.run = false; } } } @@ -147,16 +149,17 @@ public class SpreadSheet repaint(); } + @Override public void update(Graphics g) { - if (! fullUpdate) { + if (!fullUpdate) { int cx, cy; g.setFont(titleFont); - for (int i=0; i < rows; i++) { - for (int j=0; j < columns; j++) { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { if (cells[i][j].needRedisplay) { cx = (j * cellWidth) + 2 + rowLabelWidth; - cy = ((i+1) * cellHeight) + 2 + titleHeight; + cy = ((i + 1) * cellHeight) + 2 + titleHeight; cells[i][j].paint(g, cx, cy); } } @@ -168,13 +171,14 @@ public class SpreadSheet } public void recalculate() { - int i,j; + int i, j; //System.out.println("SpreadSheet.recalculate"); - for (i=0; i < rows; i++) { - for (j=0; j < columns; j++) { + for (i = 0; i < rows; i++) { + for (j = 0; j < columns; j++) { if (cells[i][j] != null && cells[i][j].type == Cell.FORMULA) { - cells[i][j].setRawValue(evaluateFormula(cells[i][j].parseRoot)); + cells[i][j].setRawValue(evaluateFormula( + cells[i][j].parseRoot)); cells[i][j].needRedisplay = true; } } @@ -182,8 +186,8 @@ public class SpreadSheet repaint(); } - public float evaluateFormula(Node n) { - float val = 0.0f; + float evaluateFormula(Node n) { + float val = 0.0f; //System.out.println("evaluateFormula:"); //n.print(3); @@ -192,43 +196,40 @@ public class SpreadSheet return val; } switch (n.type) { - case Node.OP: - val = evaluateFormula(n.left); - switch (n.op) { - case '+': - val += evaluateFormula(n.right); - break; - case '*': - val *= evaluateFormula(n.right); - break; - case '-': - val -= evaluateFormula(n.right); - break; - case '/': - val /= evaluateFormula(n.right); + case Node.OP: + val = evaluateFormula(n.left); + switch (n.op) { + case '+': + val += evaluateFormula(n.right); + break; + case '*': + val *= evaluateFormula(n.right); + break; + case '-': + val -= evaluateFormula(n.right); + break; + case '/': + val /= evaluateFormula(n.right); + break; + } break; - } - break; - case Node.VALUE: - //System.out.println("=>" + n.value); - return n.value; - case Node.CELL: - if (n == null) { - //System.out.println("NULL at 192"); - } else { + case Node.VALUE: + //System.out.println("=>" + n.value); + return n.value; + case Node.CELL: if (cells[n.row][n.column] == null) { //System.out.println("NULL at 193"); } else { //System.out.println("=>" + cells[n.row][n.column].value); return cells[n.row][n.column].value; } - } } //System.out.println("=>" + val); return val; } + @Override public synchronized void paint(Graphics g) { int i, j; int cx, cy; @@ -240,40 +241,40 @@ public class SpreadSheet g.setFont(titleFont); i = g.getFontMetrics().stringWidth(title); g.drawString((title == null) ? "Spreadsheet" : title, - (d.width - i) / 2, 12); + (d.width - i) / 2, 12); g.setColor(inputColor); g.fillRect(0, cellHeight, d.width, cellHeight); g.setFont(titleFont); - for (i=0; i < rows+1; i++) { - cy = (i+2) * cellHeight; + for (i = 0; i < rows + 1; i++) { + cy = (i + 2) * cellHeight; g.setColor(getBackground()); g.draw3DRect(0, cy, d.width, 2, true); if (i < rows) { g.setColor(Color.red); - g.drawString("" + (i+1), 2, cy + 12); + g.drawString("" + (i + 1), 2, cy + 12); } } g.setColor(Color.red); - cy = (rows+3) * cellHeight + (cellHeight / 2); - for (i=0; i < columns; i++) { + cy = (rows + 3) * cellHeight + (cellHeight / 2); + for (i = 0; i < columns; i++) { cx = i * cellWidth; g.setColor(getBackground()); g.draw3DRect(cx + rowLabelWidth, - 2 * cellHeight, 1, d.height, true); + 2 * cellHeight, 1, d.height, true); if (i < columns) { g.setColor(Color.red); - l[0] = (char)((int)'A' + i); + l[0] = (char) ((int) 'A' + i); g.drawString(new String(l), - cx + rowLabelWidth + (cellWidth / 2), - cy); + cx + rowLabelWidth + (cellWidth / 2), + cy); } } - for (i=0; i < rows; i++) { - for (j=0; j < columns; j++) { + for (i = 0; i < rows; i++) { + for (j = 0; j < columns; j++) { cx = (j * cellWidth) + 2 + rowLabelWidth; - cy = ((i+1) * cellHeight) + 2 + titleHeight; + cy = ((i + 1) * cellHeight) + 2 + titleHeight; if (cells[i][j] != null) { cells[i][j].paint(g, cx, cy); } @@ -282,141 +283,152 @@ public class SpreadSheet g.setColor(getBackground()); g.draw3DRect(0, titleHeight, - d.width, - d.height - titleHeight, - false); + d.width, + d.height - titleHeight, + false); inputArea.paint(g, 1, titleHeight + 1); } - //1.1 event handling - - public void mouseClicked(MouseEvent e) - {} - - public void mousePressed(MouseEvent e) - { - int x = e.getX(); - int y = e.getY(); - Cell cell; - if (y < (titleHeight + cellHeight)) { - selectedRow = -1; - if (y <= titleHeight && current != null) { - current.deselect(); - current = null; - } - e.consume(); - } - if (x < rowLabelWidth) { - selectedRow = -1; - if (current != null) { - current.deselect(); - current = null; - } - e.consume(); - - } - selectedRow = ((y - cellHeight - titleHeight) / cellHeight); - selectedColumn = (x - rowLabelWidth) / cellWidth; - if (selectedRow > rows || - selectedColumn >= columns) { - selectedRow = -1; - if (current != null) { - current.deselect(); - current = null; - } - } else { - if (selectedRow >= rows) { - selectedRow = -1; - if (current != null) { - current.deselect(); - current = null; - } - e.consume(); - } - if (selectedRow != -1) { - cell = cells[selectedRow][selectedColumn]; - inputArea.setText(new String(cell.getPrintString())); - if (current != null) { - current.deselect(); - } - current = cell; - current.select(); - requestFocus(); - fullUpdate = true; - repaint(); - } - e.consume(); + //1.1 event handling + @Override + public void mouseClicked(MouseEvent e) { } - } - public void mouseReleased(MouseEvent e) - {} + @Override + public void mousePressed(MouseEvent e) { + int x = e.getX(); + int y = e.getY(); + Cell cell; + if (y < (titleHeight + cellHeight)) { + selectedRow = -1; + if (y <= titleHeight && current != null) { + current.deselect(); + current = null; + } + e.consume(); + } + if (x < rowLabelWidth) { + selectedRow = -1; + if (current != null) { + current.deselect(); + current = null; + } + e.consume(); - public void mouseEntered(MouseEvent e) - {} + } + selectedRow = ((y - cellHeight - titleHeight) / cellHeight); + selectedColumn = (x - rowLabelWidth) / cellWidth; + if (selectedRow > rows + || selectedColumn >= columns) { + selectedRow = -1; + if (current != null) { + current.deselect(); + current = null; + } + } else { + if (selectedRow >= rows) { + selectedRow = -1; + if (current != null) { + current.deselect(); + current = null; + } + e.consume(); + } + if (selectedRow != -1) { + cell = cells[selectedRow][selectedColumn]; + inputArea.setText(cell.getPrintString()); + if (current != null) { + current.deselect(); + } + current = cell; + current.select(); + requestFocus(); + fullUpdate = true; + repaint(); + } + e.consume(); + } + } - public void mouseExited(MouseEvent e) - {} + @Override + public void mouseReleased(MouseEvent e) { + } - public void keyPressed(KeyEvent e) - { - } + @Override + public void mouseEntered(MouseEvent e) { + } - public void keyTyped(KeyEvent e) { - fullUpdate=true; - inputArea.processKey(e); - e.consume(); - } + @Override + public void mouseExited(MouseEvent e) { + } - public void keyReleased(KeyEvent e) - {} + @Override + public void keyPressed(KeyEvent e) { + } - public String getAppletInfo() { - return "Title: SpreadSheet \nAuthor: Sami Shaio \nA simple spread sheet."; - } + @Override + public void keyTyped(KeyEvent e) { + fullUpdate = true; + inputArea.processKey(e); + e.consume(); + } - public String[][] getParameterInfo() { - String[][] info = { - {"title", "string", "The title of the spread sheet. Default is 'Spreadsheet'"}, - {"rows", "int", "The number of rows. Default is 9."}, - {"columns", "int", "The number of columns. Default is 5."} - }; - return info; - } + @Override + public void keyReleased(KeyEvent e) { + } + @Override + public String getAppletInfo() { + return "Title: SpreadSheet \nAuthor: Sami Shaio \nA simple spread sheet."; + } + @Override + public String[][] getParameterInfo() { + String[][] info = { + { "title", "string", + "The title of the spread sheet. Default is 'Spreadsheet'" }, + { "rows", "int", "The number of rows. Default is 9." }, + { "columns", "int", "The number of columns. Default is 5." } + }; + return info; + } } + class CellUpdater extends Thread { - Cell target; + + Cell target; InputStream dataStream = null; StreamTokenizer tokenStream; + public volatile boolean run = true; public CellUpdater(Cell c) { super("cell updater"); target = c; } + @Override public void run() { try { dataStream = new URL(target.app.getDocumentBase(), - target.getValueString()).openStream(); - tokenStream = new StreamTokenizer(new BufferedReader(new InputStreamReader(dataStream))); + target.getValueString()).openStream(); + tokenStream = new StreamTokenizer(new BufferedReader( + new InputStreamReader(dataStream))); tokenStream.eolIsSignificant(false); - while (true) { + while (run) { switch (tokenStream.nextToken()) { - case StreamTokenizer.TT_EOF: - dataStream.close(); - return; - default: - break; - case StreamTokenizer.TT_NUMBER: - target.setTransientValue((float)tokenStream.nval); - if (! target.app.isStopped && ! target.paused) { - target.app.repaint(); - } - break; + case StreamTokenizer.TT_EOF: + dataStream.close(); + return; + default: + break; + case StreamTokenizer.TT_NUMBER: + target.setTransientValue((float) tokenStream.nval); + if (!target.app.isStopped && !target.paused) { + target.app.repaint(); + } + break; } try { Thread.sleep(2000); @@ -430,35 +442,36 @@ class CellUpdater extends Thread { } } + class Cell { + public static final int VALUE = 0; public static final int LABEL = 1; - public static final int URL = 2; + public static final int URL = 2; public static final int FORMULA = 3; - - Node parseRoot; - boolean needRedisplay; + Node parseRoot; + boolean needRedisplay; boolean selected = false; boolean transientValue = false; - public int type = Cell.VALUE; - String valueString = ""; - String printString = "v"; - float value; - Color bgColor; - Color fgColor; - Color highlightColor; - int width; - int height; + public int type = Cell.VALUE; + String valueString = ""; + String printString = "v"; + float value; + Color bgColor; + Color fgColor; + Color highlightColor; + int width; + int height; SpreadSheet app; CellUpdater updaterThread; - boolean paused = false; + boolean paused = false; public Cell(SpreadSheet app, - Color bgColor, - Color fgColor, - Color highlightColor, - int width, - int height) { + Color bgColor, + Color fgColor, + Color highlightColor, + int width, + int height) { this.app = app; this.bgColor = bgColor; this.fgColor = fgColor; @@ -472,6 +485,7 @@ class Cell { valueString = Float.toString(f); value = f; } + public void setValue(float f) { setRawValue(f); printString = "v" + valueString; @@ -490,18 +504,18 @@ class Cell { public void setUnparsedValue(String s) { switch (s.charAt(0)) { - case 'v': - setValue(Cell.VALUE, s.substring(1)); - break; - case 'f': - setValue(Cell.FORMULA, s.substring(1)); - break; - case 'l': - setValue(Cell.LABEL, s.substring(1)); - break; - case 'u': - setValue(Cell.URL, s.substring(1)); - break; + case 'v': + setValue(Cell.VALUE, s.substring(1)); + break; + case 'f': + setValue(Cell.FORMULA, s.substring(1)); + break; + case 'l': + setValue(Cell.LABEL, s.substring(1)); + break; + case 'u': + setValue(Cell.URL, s.substring(1)); + break; } } @@ -519,8 +533,6 @@ class Cell { public String parseFormula(String formula, Node node) { String subformula; String restFormula; - float value; - int length = formula.length(); Node left; Node right; char op; @@ -534,52 +546,53 @@ class Cell { //System.out.println("Parse succeeded"); return null; } - if (subformula == formula) { + if (subformula.equals(formula)) { //System.out.println("Parse failed"); return formula; } // parse an operator and then another value switch (op = subformula.charAt(0)) { - case 0: - //System.out.println("Parse succeeded"); - return null; - case ')': - //System.out.println("Returning subformula=" + subformula); - return subformula; - case '+': - case '*': - case '-': - case '/': - restFormula = subformula.substring(1); - subformula = parseValue(restFormula, right=new Node()); - //System.out.println("subformula(2) = " + subformula); - if (subformula != restFormula) { + case 0: //System.out.println("Parse succeeded"); - left = new Node(node); - node.left = left; - node.right = right; - node.op = op; - node.type = Node.OP; - //node.print(3); + return null; + case ')': + //System.out.println("Returning subformula=" + subformula); return subformula; - } else { - //System.out.println("Parse failed"); + case '+': + case '*': + case '-': + case '/': + restFormula = subformula.substring(1); + subformula = parseValue(restFormula, right = new Node()); + //System.out.println("subformula(2) = " + subformula); + if (subformula == null ? restFormula != null : !subformula. + equals(restFormula)) { + //System.out.println("Parse succeeded"); + left = new Node(node); + node.left = left; + node.right = right; + node.op = op; + node.type = Node.OP; + //node.print(3); + return subformula; + } else { + //System.out.println("Parse failed"); + return formula; + } + default: + //System.out.println("Parse failed (bad operator): " + subformula); return formula; - } - default: - //System.out.println("Parse failed (bad operator): " + subformula); - return formula; } } public String parseValue(String formula, Node node) { - char c = formula.charAt(0); - String subformula; - String restFormula; - float value; - int row; - int column; + char c = formula.charAt(0); + String subformula; + String restFormula; + float _value; + int row; + int column; //System.out.println("parseValue: " + formula); restFormula = formula; @@ -588,11 +601,11 @@ class Cell { restFormula = formula.substring(1); subformula = parseFormula(restFormula, node); //System.out.println("rest=(" + subformula + ")"); - if (subformula == null || - subformula.length() == restFormula.length()) { + if (subformula == null + || subformula.length() == restFormula.length()) { //System.out.println("Failed"); return formula; - } else if (! (subformula.charAt(0) == ')')) { + } else if (!(subformula.charAt(0) == ')')) { //System.out.println("Failed (missing parentheses)"); return formula; } @@ -601,31 +614,31 @@ class Cell { int i; //System.out.println("formula=" + formula); - for (i=0; i < formula.length(); i++) { + for (i = 0; i < formula.length(); i++) { c = formula.charAt(i); if ((c < '0' || c > '9') && c != '.') { break; } } try { - value = Float.valueOf(formula.substring(0, i)).floatValue(); + _value = Float.valueOf(formula.substring(0, i)).floatValue(); } catch (NumberFormatException e) { //System.out.println("Failed (number format error)"); return formula; } node.type = Node.VALUE; - node.value = value; + node.value = _value; //node.print(3); restFormula = formula.substring(i); //System.out.println("value= " + value + " i=" + i + - // " rest = " + restFormula); + // " rest = " + restFormula); return restFormula; } else if (c >= 'A' && c <= 'Z') { int i; column = c - 'A'; restFormula = formula.substring(1); - for (i=0; i < restFormula.length(); i++) { + for (i = 0; i < restFormula.length(); i++) { c = restFormula.charAt(i); if (c < '0' || c > '9') { break; @@ -650,33 +663,32 @@ class Cell { return restFormula; } - public void setValue(int type, String s) { paused = false; if (this.type == Cell.URL) { - updaterThread.stop(); + updaterThread.run = false; updaterThread = null; } - valueString = new String(s); + valueString = s; this.type = type; needRedisplay = true; switch (type) { - case Cell.VALUE: - setValue(Float.valueOf(s).floatValue()); - break; - case Cell.LABEL: - printString = "l" + valueString; - break; - case Cell.URL: - printString = "u" + valueString; - updaterThread = new CellUpdater(this); - updaterThread.start(); - break; - case Cell.FORMULA: - parseFormula(valueString, parseRoot = new Node()); - printString = "f" + valueString; - break; + case Cell.VALUE: + setValue(Float.valueOf(s).floatValue()); + break; + case Cell.LABEL: + printString = "l" + valueString; + break; + case Cell.URL: + printString = "u" + valueString; + updaterThread = new CellUpdater(this); + updaterThread.start(); + break; + case Cell.FORMULA: + parseFormula(valueString, parseRoot = new Node()); + printString = "f" + valueString; + break; } app.recalculate(); } @@ -693,12 +705,14 @@ class Cell { selected = true; paused = true; } + public void deselect() { selected = false; paused = false; needRedisplay = true; app.repaint(); } + public void paint(Graphics g, int x, int y) { if (selected) { g.setColor(highlightColor); @@ -708,23 +722,23 @@ class Cell { g.fillRect(x, y, width - 1, height); if (valueString != null) { switch (type) { - case Cell.VALUE: - case Cell.LABEL: - g.setColor(fgColor); - break; - case Cell.FORMULA: - g.setColor(Color.red); - break; - case Cell.URL: - g.setColor(Color.blue); - break; + case Cell.VALUE: + case Cell.LABEL: + g.setColor(fgColor); + break; + case Cell.FORMULA: + g.setColor(Color.red); + break; + case Cell.URL: + g.setColor(Color.blue); + break; } - if (transientValue){ + if (transientValue) { g.drawString("" + value, x, y + (height / 2) + 5); } else { if (valueString.length() > 14) { g.drawString(valueString.substring(0, 14), - x, y + (height / 2) + 5); + x, y + (height / 2) + 5); } else { g.drawString(valueString, x, y + (height / 2) + 5); } @@ -734,18 +748,19 @@ class Cell { } } + class Node { + public static final int OP = 0; public static final int VALUE = 1; public static final int CELL = 2; - - int type; - Node left; - Node right; - int row; - int column; - float value; - char op; + int type; + Node left; + Node right; + int row; + int column; + float value; + char op; public Node() { left = null; @@ -756,6 +771,7 @@ class Node { op = 0; type = Node.VALUE; } + public Node(Node n) { left = n.left; right = n.right; @@ -765,47 +781,51 @@ class Node { op = n.op; type = n.type; } + public void indent(int ind) { for (int i = 0; i < ind; i++) { System.out.print(" "); } } + public void print(int indentLevel) { char l[] = new char[1]; indent(indentLevel); System.out.println("NODE type=" + type); indent(indentLevel); switch (type) { - case Node.VALUE: - System.out.println(" value=" + value); - break; - case Node.CELL: - l[0] = (char)((int)'A' + column); - System.out.println(" cell=" + new String(l) + (row+1)); - break; - case Node.OP: - System.out.println(" op=" + op); - left.print(indentLevel + 3); - right.print(indentLevel + 3); - break; + case Node.VALUE: + System.out.println(" value=" + value); + break; + case Node.CELL: + l[0] = (char) ((int) 'A' + column); + System.out.println(" cell=" + new String(l) + (row + 1)); + break; + case Node.OP: + System.out.println(" op=" + op); + left.print(indentLevel + 3); + right.print(indentLevel + 3); + break; } } } + class InputField { - int maxchars = 50; - int cursorPos = 0; - Applet app; - String sval; - char buffer[]; - int nChars; - int width; - int height; - Color bgColor; - Color fgColor; + + int maxchars = 50; + int cursorPos = 0; + Applet app; + String sval; + char buffer[]; + int nChars; + int width; + int height; + Color bgColor; + Color fgColor; public InputField(String initValue, Applet app, int width, int height, - Color bgColor, Color fgColor) { + Color bgColor, Color fgColor) { this.width = width; this.height = height; this.bgColor = bgColor; @@ -823,7 +843,7 @@ class InputField { public void setText(String val) { int i; - for (i=0; i < maxchars; i++) { + for (i = 0; i < maxchars; i++) { buffer[i] = 0; } if (val == null) { @@ -876,47 +896,52 @@ class InputField { } } + class SpreadSheetInput - extends InputField { + extends InputField { - public SpreadSheetInput(String initValue, - SpreadSheet app, - int width, - int height, - Color bgColor, - Color fgColor) { - super(initValue, app, width, height, bgColor, fgColor); - } + public SpreadSheetInput(String initValue, + SpreadSheet app, + int width, + int height, + Color bgColor, + Color fgColor) { + super(initValue, app, width, height, bgColor, fgColor); + } + @Override public void selected() { float f; - sval = ("".equals(sval)) ? "v":sval; + sval = ("".equals(sval)) ? "v" : sval; switch (sval.charAt(0)) { - case 'v': - String s= sval.substring(1); - try { - int i; - for (i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c < '0' || c > '9') - break; + case 'v': + String s = sval.substring(1); + try { + int i; + for (i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c < '0' || c > '9') { + break; + } + } + s = s.substring(0, i); + f = Float.valueOf(s).floatValue(); + ((SpreadSheet) app).setCurrentValue(f); + } catch (NumberFormatException e) { + System.out.println("Not a float: '" + s + "'"); } - s = s.substring(0, i); - f = Float.valueOf(s).floatValue(); - ((SpreadSheet)app).setCurrentValue(f); - } catch (NumberFormatException e) { - System.out.println("Not a float: '" + s + "'"); - } - break; - case 'l': - ((SpreadSheet)app).setCurrentValue(Cell.LABEL, sval.substring(1)); - break; - case 'u': - ((SpreadSheet)app).setCurrentValue(Cell.URL, sval.substring(1)); - break; - case 'f': - ((SpreadSheet)app).setCurrentValue(Cell.FORMULA, sval.substring(1)); - break; + break; + case 'l': + ((SpreadSheet) app).setCurrentValue(Cell.LABEL, + sval.substring(1)); + break; + case 'u': + ((SpreadSheet) app).setCurrentValue(Cell.URL, sval.substring(1)); + break; + case 'f': + ((SpreadSheet) app).setCurrentValue(Cell.FORMULA, + sval.substring(1)); + break; } } } diff --git a/src/share/demo/applets/WireFrame/Matrix3D.java b/src/share/demo/applets/WireFrame/Matrix3D.java index bc5939d54bd8bb9574cfcd5c1b0c71710ad6edca..0dda042c3c9a6faeadc7d2d7f27f99112432d2ff 100644 --- a/src/share/demo/applets/WireFrame/Matrix3D.java +++ b/src/share/demo/applets/WireFrame/Matrix3D.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,22 +29,23 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ /** A fairly conventional 3D matrix object that can transform sets of - 3D points and perform a variety of manipulations on the transform */ +3D points and perform a variety of manipulations on the transform */ class Matrix3D { + float xx, xy, xz, xo; float yx, yy, yz, yo; float zx, zy, zz, zo; static final double pi = 3.14159265; + /** Create a new unit matrix */ - Matrix3D () { + Matrix3D() { xx = 1.0f; yy = 1.0f; zz = 1.0f; } + /** Scale by f in all dimensions */ void scale(float f) { xx *= f; @@ -60,6 +61,7 @@ class Matrix3D { zz *= f; zo *= f; } + /** Scale along each axis independently */ void scale(float xf, float yf, float zf) { xx *= xf; @@ -75,12 +77,14 @@ class Matrix3D { zz *= zf; zo *= zf; } + /** Translate the origin */ void translate(float x, float y, float z) { xo += x; yo += y; zo += z; } + /** rotate theta degrees about the y axis */ void yrot(double theta) { theta *= (pi / 180); @@ -106,6 +110,7 @@ class Matrix3D { zy = Nzy; zz = Nzz; } + /** rotate theta degrees about the x axis */ void xrot(double theta) { theta *= (pi / 180); @@ -131,6 +136,7 @@ class Matrix3D { zy = Nzy; zz = Nzz; } + /** rotate theta degrees about the z axis */ void zrot(double theta) { theta *= (pi / 180); @@ -156,6 +162,7 @@ class Matrix3D { xy = Nxy; xz = Nxz; } + /** Multiply this matrix by a second: M = M*R */ void mult(Matrix3D rhs) { float lxx = xx * rhs.xx + yx * rhs.xy + zx * rhs.xz; @@ -204,10 +211,11 @@ class Matrix3D { zy = 0; zz = 1; } + /** Transform nvert points from v into tv. v contains the input - coordinates in floating point. Three successive entries in - the array constitute a point. tv ends up holding the transformed - points as integers; three successive entries per point */ + coordinates in floating point. Three successive entries in + the array constitute a point. tv ends up holding the transformed + points as integers; three successive entries per point */ void transform(float v[], int tv[], int nvert) { float lxx = xx, lxy = xy, lxz = xz, lxo = xo; float lyx = yx, lyy = yy, lyz = yz, lyo = yo; @@ -216,11 +224,13 @@ class Matrix3D { float x = v[i]; float y = v[i + 1]; float z = v[i + 2]; - tv[i ] = (int) (x * lxx + y * lxy + z * lxz + lxo); + tv[i] = (int) (x * lxx + y * lxy + z * lxz + lxo); tv[i + 1] = (int) (x * lyx + y * lyy + z * lyz + lyo); tv[i + 2] = (int) (x * lzx + y * lzy + z * lzz + lzo); } } + + @Override public String toString() { return ("[" + xo + "," + xx + "," + xy + "," + xz + ";" + yo + "," + yx + "," + yy + "," + yz + ";" diff --git a/src/share/demo/applets/WireFrame/ThreeD.java b/src/share/demo/applets/WireFrame/ThreeD.java index 81aa0d04c6e62ced5ff832cc58ac380bff50e4bf..7f228331f7e335e61a3b16a1d872051e328acedb 100644 --- a/src/share/demo/applets/WireFrame/ThreeD.java +++ b/src/share/demo/applets/WireFrame/ThreeD.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,28 +29,29 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ - -/* A set of classes to parse, represent and display 3D wireframe models - represented in Wavefront .obj format. */ import java.applet.Applet; import java.awt.Graphics; import java.awt.Color; -import java.awt.Event; import java.awt.event.*; import java.io.*; import java.net.URL; + +/* A set of classes to parse, represent and display 3D wireframe models +represented in Wavefront .obj format. */ +@SuppressWarnings("serial") class FileFormatException extends Exception { + public FileFormatException(String s) { super(s); } } + /** The representation of a 3D model */ -class Model3D { +final class Model3D { + float vert[]; int tvert[]; int nvert, maxvert; @@ -58,78 +59,90 @@ class Model3D { int ncon, maxcon; boolean transformed; Matrix3D mat; - float xmin, xmax, ymin, ymax, zmin, zmax; - Model3D () { - mat = new Matrix3D (); + Model3D() { + mat = new Matrix3D(); mat.xrot(20); mat.yrot(30); } + /** Create a 3D model by parsing an input stream */ - Model3D (InputStream is) throws IOException, FileFormatException { - this(); - StreamTokenizer st = new StreamTokenizer( - new BufferedReader(new InputStreamReader(is, "UTF-8"))); - st.eolIsSignificant(true); - st.commentChar('#'); - scan: + Model3D(InputStream is) throws IOException, FileFormatException { + this(); + StreamTokenizer st = new StreamTokenizer( + new BufferedReader(new InputStreamReader(is, "UTF-8"))); + st.eolIsSignificant(true); + st.commentChar('#'); + scan: while (true) { switch (st.nextToken()) { - default: - break scan; - case StreamTokenizer.TT_EOL: - break; - case StreamTokenizer.TT_WORD: - if ("v".equals(st.sval)) { - double x = 0, y = 0, z = 0; - if (st.nextToken() == StreamTokenizer.TT_NUMBER) { - x = st.nval; + default: + break scan; + case StreamTokenizer.TT_EOL: + break; + case StreamTokenizer.TT_WORD: + if ("v".equals(st.sval)) { + double x = 0, y = 0, z = 0; if (st.nextToken() == StreamTokenizer.TT_NUMBER) { - y = st.nval; - if (st.nextToken() == StreamTokenizer.TT_NUMBER) - z = st.nval; + x = st.nval; + if (st.nextToken() == StreamTokenizer.TT_NUMBER) { + y = st.nval; + if (st.nextToken() == StreamTokenizer.TT_NUMBER) { + z = st.nval; + } + } } - } - addVert((float) x, (float) y, (float) z); - while (st.ttype != StreamTokenizer.TT_EOL && - st.ttype != StreamTokenizer.TT_EOF) - st.nextToken(); - } else if ("f".equals(st.sval) || "fo".equals(st.sval) || "l".equals(st.sval)) { - int start = -1; - int prev = -1; - int n = -1; - while (true) - if (st.nextToken() == StreamTokenizer.TT_NUMBER) { - n = (int) st.nval; - if (prev >= 0) - add(prev - 1, n - 1); - if (start < 0) - start = n; - prev = n; - } else if (st.ttype == '/') + addVert((float) x, (float) y, (float) z); + while (st.ttype != StreamTokenizer.TT_EOL && st.ttype + != StreamTokenizer.TT_EOF) { st.nextToken(); - else - break; - if (start >= 0) - add(start - 1, prev - 1); - if (st.ttype != StreamTokenizer.TT_EOL) - break scan; - } else { - while (st.nextToken() != StreamTokenizer.TT_EOL - && st.ttype != StreamTokenizer.TT_EOF); - } + } + } else if ("f".equals(st.sval) || "fo".equals(st.sval) || "l". + equals(st.sval)) { + int start = -1; + int prev = -1; + int n = -1; + while (true) { + if (st.nextToken() == StreamTokenizer.TT_NUMBER) { + n = (int) st.nval; + if (prev >= 0) { + add(prev - 1, n - 1); + } + if (start < 0) { + start = n; + } + prev = n; + } else if (st.ttype == '/') { + st.nextToken(); + } else { + break; + } + } + if (start >= 0) { + add(start - 1, prev - 1); + } + if (st.ttype != StreamTokenizer.TT_EOL) { + break scan; + } + } else { + while (st.nextToken() != StreamTokenizer.TT_EOL + && st.ttype != StreamTokenizer.TT_EOF) { + // no-op + } + } } } is.close(); - if (st.ttype != StreamTokenizer.TT_EOF) + if (st.ttype != StreamTokenizer.TT_EOF) { throw new FileFormatException(st.toString()); + } } /** Add a vertex to this model */ int addVert(float x, float y, float z) { int i = nvert; - if (i >= maxvert) + if (i >= maxvert) { if (vert == null) { maxvert = 100; vert = new float[maxvert * 3]; @@ -139,18 +152,21 @@ class Model3D { System.arraycopy(vert, 0, nv, 0, vert.length); vert = nv; } + } i *= 3; vert[i] = x; vert[i + 1] = y; vert[i + 2] = z; return nvert++; } + /** Add a line from vertex p1 to vertex p2 */ void add(int p1, int p2) { int i = ncon; - if (p1 >= nvert || p2 >= nvert) + if (p1 >= nvert || p2 >= nvert) { return; - if (i >= maxcon) + } + if (i >= maxcon) { if (con == null) { maxcon = 100; con = new int[maxcon]; @@ -160,6 +176,7 @@ class Model3D { System.arraycopy(con, 0, nv, 0, con.length); con = nv; } + } if (p1 > p2) { int t = p1; p1 = p2; @@ -168,79 +185,79 @@ class Model3D { con[i] = (p1 << 16) | p2; ncon = i + 1; } + /** Transform all the points in this model */ void transform() { - if (transformed || nvert <= 0) + if (transformed || nvert <= 0) { return; - if (tvert == null || tvert.length < nvert * 3) - tvert = new int[nvert*3]; + } + if (tvert == null || tvert.length < nvert * 3) { + tvert = new int[nvert * 3]; + } mat.transform(vert, tvert, nvert); transformed = true; } - /* Quick Sort implementation - */ - private void quickSort(int a[], int left, int right) - { - int leftIndex = left; - int rightIndex = right; - int partionElement; - if ( right > left) - { - - /* Arbitrarily establishing partition element as the midpoint of - * the array. - */ - partionElement = a[ ( left + right ) / 2 ]; - - // loop through the array until indices cross - while( leftIndex <= rightIndex ) - { - /* find the first element that is greater than or equal to - * the partionElement starting from the leftIndex. - */ - while( ( leftIndex < right ) && ( a[leftIndex] < partionElement ) ) - ++leftIndex; + /* Quick Sort implementation + */ + private void quickSort(int a[], int left, int right) { + int leftIndex = left; + int rightIndex = right; + int partionElement; + if (right > left) { - /* find an element that is smaller than or equal to - * the partionElement starting from the rightIndex. + /* Arbitrarily establishing partition element as the midpoint of + * the array. */ - while( ( rightIndex > left ) && - ( a[rightIndex] > partionElement ) ) - --rightIndex; - - // if the indexes have not crossed, swap - if( leftIndex <= rightIndex ) - { - swap(a, leftIndex, rightIndex); - ++leftIndex; - --rightIndex; - } - } + partionElement = a[(left + right) / 2]; + + // loop through the array until indices cross + while (leftIndex <= rightIndex) { + /* find the first element that is greater than or equal to + * the partionElement starting from the leftIndex. + */ + while ((leftIndex < right) && (a[leftIndex] < partionElement)) { + ++leftIndex; + } - /* If the right index has not reached the left side of array - * must now sort the left partition. - */ - if( left < rightIndex ) - quickSort( a, left, rightIndex ); + /* find an element that is smaller than or equal to + * the partionElement starting from the rightIndex. + */ + while ((rightIndex > left) && (a[rightIndex] > partionElement)) { + --rightIndex; + } + + // if the indexes have not crossed, swap + if (leftIndex <= rightIndex) { + swap(a, leftIndex, rightIndex); + ++leftIndex; + --rightIndex; + } + } - /* If the left index has not reached the right side of array - * must now sort the right partition. - */ - if( leftIndex < right ) - quickSort( a, leftIndex, right ); + /* If the right index has not reached the left side of array + * must now sort the left partition. + */ + if (left < rightIndex) { + quickSort(a, left, rightIndex); + } - } - } + /* If the left index has not reached the right side of array + * must now sort the right partition. + */ + if (leftIndex < right) { + quickSort(a, leftIndex, right); + } - private void swap(int a[], int i, int j) - { - int T; - T = a[i]; - a[i] = a[j]; - a[j] = T; - } + } + } + private void swap(int a[], int i, int j) { + int T; + T = a[i]; + a[i] = a[j]; + a[j] = T; + } /** eliminate duplicate lines */ void compress() { @@ -259,21 +276,21 @@ class Model3D { } ncon = d; } - static Color gr[]; /** Paint this model to a graphics context. It uses the matrix associated - with this model to map from model space to screen space. - The next version of the browser should have double buffering, - which will make this *much* nicer */ + with this model to map from model space to screen space. + The next version of the browser should have double buffering, + which will make this *much* nicer */ void paint(Graphics g) { - if (vert == null || nvert <= 0) + if (vert == null || nvert <= 0) { return; + } transform(); if (gr == null) { gr = new Color[16]; for (int i = 0; i < 16; i++) { - int grey = (int) (170*(1-Math.pow(i/15.0, 2.3))); + int grey = (int) (170 * (1 - Math.pow(i / 15.0, 2.3))); gr[i] = new Color(grey, grey, grey); } } @@ -281,151 +298,181 @@ class Model3D { int lim = ncon; int c[] = con; int v[] = tvert; - if (lim <= 0 || nvert <= 0) + if (lim <= 0 || nvert <= 0) { return; + } for (int i = 0; i < lim; i++) { int T = c[i]; int p1 = ((T >> 16) & 0xFFFF) * 3; int p2 = (T & 0xFFFF) * 3; int grey = v[p1 + 2] + v[p2 + 2]; - if (grey < 0) + if (grey < 0) { grey = 0; - if (grey > 15) + } + if (grey > 15) { grey = 15; + } if (grey != lg) { lg = grey; g.setColor(gr[grey]); } g.drawLine(v[p1], v[p1 + 1], - v[p2], v[p2 + 1]); + v[p2], v[p2 + 1]); } } /** Find the bounding box of this model */ void findBB() { - if (nvert <= 0) + if (nvert <= 0) { return; + } float v[] = vert; - float xmin = v[0], xmax = xmin; - float ymin = v[1], ymax = ymin; - float zmin = v[2], zmax = zmin; + float _xmin = v[0], _xmax = _xmin; + float _ymin = v[1], _ymax = _ymin; + float _zmin = v[2], _zmax = _zmin; for (int i = nvert * 3; (i -= 3) > 0;) { float x = v[i]; - if (x < xmin) - xmin = x; - if (x > xmax) - xmax = x; + if (x < _xmin) { + _xmin = x; + } + if (x > _xmax) { + _xmax = x; + } float y = v[i + 1]; - if (y < ymin) - ymin = y; - if (y > ymax) - ymax = y; + if (y < _ymin) { + _ymin = y; + } + if (y > _ymax) { + _ymax = y; + } float z = v[i + 2]; - if (z < zmin) - zmin = z; - if (z > zmax) - zmax = z; + if (z < _zmin) { + _zmin = z; + } + if (z > _zmax) { + _zmax = z; + } } - this.xmax = xmax; - this.xmin = xmin; - this.ymax = ymax; - this.ymin = ymin; - this.zmax = zmax; - this.zmin = zmin; + this.xmax = _xmax; + this.xmin = _xmin; + this.ymax = _ymax; + this.ymin = _ymin; + this.zmax = _zmax; + this.zmin = _zmin; } } + /** An applet to put a 3D model into a page */ +@SuppressWarnings("serial") public class ThreeD extends Applet - implements Runnable, MouseListener, MouseMotionListener { + implements Runnable, MouseListener, MouseMotionListener { + Model3D md; boolean painted = true; float xfac; int prevx, prevy; - float xtheta, ytheta; float scalefudge = 1; Matrix3D amat = new Matrix3D(), tmat = new Matrix3D(); String mdname = null; String message = null; + @Override public void init() { mdname = getParameter("model"); try { scalefudge = Float.valueOf(getParameter("scale")).floatValue(); - }catch(Exception e){}; + } catch (Exception ignored) { + // fall back to default scalefudge = 1 + } amat.yrot(20); amat.xrot(20); - if (mdname == null) + if (mdname == null) { mdname = "model.obj"; + } resize(getSize().width <= 20 ? 400 : getSize().width, - getSize().height <= 20 ? 400 : getSize().height); + getSize().height <= 20 ? 400 : getSize().height); addMouseListener(this); addMouseMotionListener(this); } + @Override public void destroy() { removeMouseListener(this); removeMouseMotionListener(this); } + @Override public void run() { InputStream is = null; try { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); is = new URL(getDocumentBase(), mdname).openStream(); - Model3D m = new Model3D (is); + Model3D m = new Model3D(is); md = m; m.findBB(); m.compress(); float xw = m.xmax - m.xmin; float yw = m.ymax - m.ymin; float zw = m.zmax - m.zmin; - if (yw > xw) + if (yw > xw) { xw = yw; - if (zw > xw) + } + if (zw > xw) { xw = zw; + } float f1 = getSize().width / xw; float f2 = getSize().height / xw; xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge; - } catch(Exception e) { + } catch (Exception e) { md = null; message = e.toString(); } try { - if (is != null) + if (is != null) { is.close(); - } catch(Exception e) { + } + } catch (Exception e) { } repaint(); } + @Override public void start() { - if (md == null && message == null) + if (md == null && message == null) { new Thread(this).start(); + } } + @Override public void stop() { } - public void mouseClicked(MouseEvent e) { + @Override + public void mouseClicked(MouseEvent e) { } - public void mousePressed(MouseEvent e) { + @Override + public void mousePressed(MouseEvent e) { prevx = e.getX(); prevy = e.getY(); e.consume(); } - public void mouseReleased(MouseEvent e) { + @Override + public void mouseReleased(MouseEvent e) { } - public void mouseEntered(MouseEvent e) { + @Override + public void mouseEntered(MouseEvent e) { } - public void mouseExited(MouseEvent e) { + @Override + public void mouseExited(MouseEvent e) { } - public void mouseDragged(MouseEvent e) { + @Override + public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); @@ -444,15 +491,17 @@ public class ThreeD extends Applet e.consume(); } - public void mouseMoved(MouseEvent e) { + @Override + public void mouseMoved(MouseEvent e) { } + @Override public void paint(Graphics g) { if (md != null) { md.mat.unit(); md.mat.translate(-(md.xmin + md.xmax) / 2, - -(md.ymin + md.ymax) / 2, - -(md.zmin + md.zmax) / 2); + -(md.ymin + md.ymax) / 2, + -(md.zmin + md.zmax) / 2); md.mat.mult(amat); md.mat.scale(xfac, -xfac, 16 * xfac / getSize().width); md.mat.translate(getSize().width / 2, getSize().height / 2, 8); @@ -469,20 +518,18 @@ public class ThreeD extends Applet painted = true; notifyAll(); } -// private synchronized void waitPainted() { -// while (!painted) -// wait(); -// painted = false; -// } + @Override public String getAppletInfo() { - return "Title: ThreeD \nAuthor: James Gosling? \nAn applet to put a 3D model into a page."; + return "Title: ThreeD \nAuthor: James Gosling? \n" + + "An applet to put a 3D model into a page."; } + @Override public String[][] getParameterInfo() { String[][] info = { - {"model", "path string", "The path to the model to be displayed."}, - {"scale", "float", "The scale of the model. Default is 1."} + { "model", "path string", "The path to the model to be displayed." }, + { "scale", "float", "The scale of the model. Default is 1." } }; return info; } diff --git a/src/share/demo/applets/WireFrame/example1.html b/src/share/demo/applets/WireFrame/example1.html index bd909f46c2a84407e7801f264e0e1b91fcb4368b..1992ee53a2661ac649ee2e42ec68e8b6dadd92c7 100644 --- a/src/share/demo/applets/WireFrame/example1.html +++ b/src/share/demo/applets/WireFrame/example1.html @@ -6,7 +6,7 @@

3D Model: Cube


- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag! diff --git a/src/share/demo/applets/WireFrame/example2.html b/src/share/demo/applets/WireFrame/example2.html index 7e5fd621523ad0f73c383ce0703fe3344c68e89e..eec2b1d429f04e11496b009167e4929509296280 100644 --- a/src/share/demo/applets/WireFrame/example2.html +++ b/src/share/demo/applets/WireFrame/example2.html @@ -6,7 +6,7 @@

3D Model: Dinosaur


- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag! diff --git a/src/share/demo/applets/WireFrame/example3.html b/src/share/demo/applets/WireFrame/example3.html index 9fdd0a57305f53c51c4af0f6794db48e67d6f9a1..2b49d118ec78a74824d595b349924ae47a403a54 100644 --- a/src/share/demo/applets/WireFrame/example3.html +++ b/src/share/demo/applets/WireFrame/example3.html @@ -6,7 +6,7 @@

3D Model: Hughes


- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag! diff --git a/src/share/demo/applets/WireFrame/example4.html b/src/share/demo/applets/WireFrame/example4.html index e8db8830773149cf3123b76410bd7811ab2fde1b..faf409254a1e00c772ba077a13644711cbb5eabf 100644 --- a/src/share/demo/applets/WireFrame/example4.html +++ b/src/share/demo/applets/WireFrame/example4.html @@ -6,7 +6,7 @@

3D Model: knoxS


- + alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag! diff --git a/src/share/demo/jfc/CodePointIM/CodePointIM.java b/src/share/demo/jfc/CodePointIM/CodePointIM.java index 61542daefcc6c5283fb594a433d4d13343cb9daa..6d02ecdc9f2d470ee570b3177bc0eb6eee5c17e3 100644 --- a/src/share/demo/jfc/CodePointIM/CodePointIM.java +++ b/src/share/demo/jfc/CodePointIM/CodePointIM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,12 +29,12 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ + import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; + public class CodePointIM { // Actually, the main method is not required for InputMethod. @@ -42,11 +42,11 @@ public class CodePointIM { // not correct and encourage their reading README.txt. public static void main(String[] args) { try { - ResourceBundle resource = ResourceBundle.getBundle("resources.codepoint", - Locale.getDefault()); + ResourceBundle resource = ResourceBundle.getBundle( + "resources.codepoint", + Locale.getDefault()); System.err.println(resource.getString("warning")); - } - catch (MissingResourceException e) { + } catch (MissingResourceException e) { System.err.println(e.toString()); } diff --git a/src/share/demo/jfc/CodePointIM/CodePointInputMethod.java b/src/share/demo/jfc/CodePointIM/CodePointInputMethod.java index ff7a5769de7f5abc1a54017d671909f3f3e7ce54..67ff106c6826137095eb31747bbbb3c274b2e8cd 100644 --- a/src/share/demo/jfc/CodePointIM/CodePointInputMethod.java +++ b/src/share/demo/jfc/CodePointIM/CodePointInputMethod.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,13 +28,8 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - -/* - */ - package com.sun.inputmethods.internal.codepointim; -import java.text.AttributedCharacterIterator; -import java.util.Map; + import java.awt.AWTEvent; import java.awt.Toolkit; @@ -50,6 +45,7 @@ import java.io.IOException; import java.text.AttributedString; import java.util.Locale; + /** * The Code Point Input Method is a simple input method that allows Unicode * characters to be entered using their code point or code unit values. See the @@ -59,18 +55,16 @@ import java.util.Locale; */ public class CodePointInputMethod implements InputMethod { - private static final int UNSET = 0; - private static final int ESCAPE = 1; // \u0000 - \uFFFF - private static final int SPECIAL_ESCAPE = 2; // \U000000 - \U10FFFF - private static final int SURROGATE_PAIR = 3; // \uD800\uDC00 - \uDBFF\uDFFF - + private static final int UNSET = 0; + private static final int ESCAPE = 1; // \u0000 - \uFFFF + private static final int SPECIAL_ESCAPE = 2; // \U000000 - \U10FFFF + private static final int SURROGATE_PAIR = 3; // \uD800\uDC00 - \uDBFF\uDFFF private InputMethodContext context; private Locale locale; private StringBuffer buffer; private int insertionPoint; private int format = UNSET; - public CodePointInputMethod() throws IOException { } @@ -90,7 +84,7 @@ public class CodePointInputMethod implements InputMethod { if (eventID == KeyEvent.KEY_PRESSED) { // If we are not in composition mode, pass through - if (notInCompositionMode) { + if (notInCompositionMode) { return; } @@ -106,7 +100,7 @@ public class CodePointInputMethod implements InputMethod { char c = e.getKeyChar(); // If we are not in composition mode, wait a back slash - if (notInCompositionMode) { + if (notInCompositionMode) { // If the type character is not a back slash, pass through if (c != '\\') { return; @@ -115,30 +109,30 @@ public class CodePointInputMethod implements InputMethod { startComposition(); // Enter to composition mode } else { switch (c) { - case ' ': // Exit from composition mode - finishComposition(); - break; - case '\u007f': // Delete - deleteCharacter(); - break; - case '\b': // BackSpace - deletePreviousCharacter(); - break; - case '\u001b': // Escape - cancelComposition(); - break; - case '\n': // Return - case '\t': // Tab - sendCommittedText(); - break; - default: - composeUnicodeEscape(c); - break; + case ' ': // Exit from composition mode + finishComposition(); + break; + case '\u007f': // Delete + deleteCharacter(); + break; + case '\b': // BackSpace + deletePreviousCharacter(); + break; + case '\u001b': // Escape + cancelComposition(); + break; + case '\n': // Return + case '\t': // Tab + sendCommittedText(); + break; + default: + composeUnicodeEscape(c); + break; } } } else { // KeyEvent.KEY_RELEASED // If we are not in composition mode, pass through - if (notInCompositionMode) { + if (notInCompositionMode) { return; } } @@ -148,7 +142,7 @@ public class CodePointInputMethod implements InputMethod { private void composeUnicodeEscape(char c) { switch (buffer.length()) { - case 1: // \\ + case 1: // \\ waitEscapeCharacter(c); break; case 2: // \\u or \\U @@ -221,7 +215,7 @@ public class CodePointInputMethod implements InputMethod { private void waitDigit2(char c) { if (Character.digit(c, 16) != -1) { buffer.insert(insertionPoint++, c); - char codePoint = (char)getCodePoint(buffer, 2, 5); + char codePoint = (char) getCodePoint(buffer, 2, 5); if (Character.isHighSurrogate(codePoint)) { format = SURROGATE_PAIR; buffer.append("\\u"); @@ -261,11 +255,11 @@ public class CodePointInputMethod implements InputMethod { private void sendComposedText() { AttributedString as = new AttributedString(buffer.toString()); as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT, - InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT); + InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT); context.dispatchInputMethodEvent( - InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, - as.getIterator(), 0, - TextHitInfo.leading(insertionPoint), null); + InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, + as.getIterator(), 0, + TextHitInfo.leading(insertionPoint), null); } /** @@ -274,9 +268,9 @@ public class CodePointInputMethod implements InputMethod { private void sendCommittedText() { AttributedString as = new AttributedString(buffer.toString()); context.dispatchInputMethodEvent( - InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, - as.getIterator(), buffer.length(), - TextHitInfo.leading(insertionPoint), null); + InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, + as.getIterator(), buffer.length(), + TextHitInfo.leading(insertionPoint), null); buffer.setLength(0); insertionPoint = 0; @@ -298,9 +292,9 @@ public class CodePointInputMethod implements InputMethod { } context.dispatchInputMethodEvent( - InputMethodEvent.CARET_POSITION_CHANGED, - null, 0, - TextHitInfo.leading(insertionPoint), null); + InputMethodEvent.CARET_POSITION_CHANGED, + null, 0, + TextHitInfo.leading(insertionPoint), null); } /** @@ -314,9 +308,9 @@ public class CodePointInputMethod implements InputMethod { } context.dispatchInputMethodEvent( - InputMethodEvent.CARET_POSITION_CHANGED, - null, 0, - TextHitInfo.leading(insertionPoint), null); + InputMethodEvent.CARET_POSITION_CHANGED, + null, 0, + TextHitInfo.leading(insertionPoint), null); } /** @@ -383,7 +377,7 @@ public class CodePointInputMethod implements InputMethod { private void finishComposition() { int len = buffer.length(); if (len == 6 && format != SPECIAL_ESCAPE) { - char codePoint = (char)getCodePoint(buffer, 2, 5); + char codePoint = (char) getCodePoint(buffer, 2, 5); if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) { buffer.setLength(0); buffer.append(codePoint); @@ -400,11 +394,11 @@ public class CodePointInputMethod implements InputMethod { } } else if (len == 12 && format == SURROGATE_PAIR) { char[] codePoint = { - (char)getCodePoint(buffer, 2, 5), - (char)getCodePoint(buffer, 8, 11) + (char) getCodePoint(buffer, 2, 5), + (char) getCodePoint(buffer, 8, 11) }; - if (Character.isHighSurrogate(codePoint[0]) && - Character.isLowSurrogate(codePoint[1])) { + if (Character.isHighSurrogate(codePoint[0]) && Character. + isLowSurrogate(codePoint[1])) { buffer.setLength(0); buffer.append(codePoint); sendCommittedText(); @@ -418,7 +412,7 @@ public class CodePointInputMethod implements InputMethod { private int getCodePoint(StringBuffer sb, int from, int to) { int value = 0; for (int i = from; i <= to; i++) { - value = (value<<4) + Character.digit(sb.charAt(i), 16); + value = (value << 4) + Character.digit(sb.charAt(i), 16); } return value; } @@ -427,7 +421,6 @@ public class CodePointInputMethod implements InputMethod { Toolkit.getDefaultToolkit().beep(); } - public void activate() { if (buffer == null) { buffer = new StringBuffer(12); diff --git a/src/share/demo/jfc/CodePointIM/CodePointInputMethodDescriptor.java b/src/share/demo/jfc/CodePointIM/CodePointInputMethodDescriptor.java index 812e51eff00c2d5a8fc8f3c7e0d830abb24359cc..1ee62162b180f72a1b661e4047a25f0a68486578 100644 --- a/src/share/demo/jfc/CodePointIM/CodePointInputMethodDescriptor.java +++ b/src/share/demo/jfc/CodePointIM/CodePointInputMethodDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,17 +28,15 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - -/* - */ - package com.sun.inputmethods.internal.codepointim; + import java.awt.Image; import java.awt.im.spi.InputMethodDescriptor; import java.awt.im.spi.InputMethod; import java.util.Locale; + /** * The CodePointInputMethod is a simple input method that allows Unicode * characters to be entered via their hexadecimal code point values. @@ -68,12 +66,12 @@ public class CodePointInputMethodDescriptor implements InputMethodDescriptor { */ public Locale[] getAvailableLocales() { Locale[] locales = { - new Locale("","",""), - }; + new Locale("", "", ""), }; return locales; } - public synchronized String getInputMethodDisplayName(Locale inputLocale, Locale displayLanguage) { + public synchronized String getInputMethodDisplayName(Locale inputLocale, + Locale displayLanguage) { return "CodePoint Input Method"; } diff --git a/src/share/demo/jfc/FileChooserDemo/ExampleFileSystemView.java b/src/share/demo/jfc/FileChooserDemo/ExampleFileSystemView.java index ec1ba0f612861bd384d15aa101c68245d10b4a63..3a0897b1c4d2261c48fa50842cdc4fad37fef355 100644 --- a/src/share/demo/jfc/FileChooserDemo/ExampleFileSystemView.java +++ b/src/share/demo/jfc/FileChooserDemo/ExampleFileSystemView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,13 +29,12 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import java.io.File; import java.io.IOException; import javax.swing.filechooser.FileSystemView; + /** * This is a simple example that uses the FileSystemView class. * You can provide a superclass of the FileSystemView class with your own functionality. @@ -43,6 +42,7 @@ import javax.swing.filechooser.FileSystemView; * @author Pavel Porvatov */ public class ExampleFileSystemView extends FileSystemView { + /** * Creates a new folder with the default name "New folder". This method is invoked * when the user presses the "New folder" button. @@ -65,8 +65,9 @@ public class ExampleFileSystemView extends FileSystemView { * Returns a list which appears in a drop-down list of the FileChooser component. * In this implementation only the home directory is returned. */ + @Override public File[] getRoots() { - return new File[]{getHomeDirectory()}; + return new File[] { getHomeDirectory() }; } /** @@ -74,9 +75,11 @@ public class ExampleFileSystemView extends FileSystemView { * A string with all upper case letters is returned for a directory. * A string with all lower case letters is returned for a file. */ + @Override public String getSystemDisplayName(File f) { String displayName = super.getSystemDisplayName(f); - return f.isDirectory() ? displayName.toUpperCase() : displayName.toLowerCase(); + return f.isDirectory() ? displayName.toUpperCase() : displayName. + toLowerCase(); } } diff --git a/src/share/demo/jfc/FileChooserDemo/ExampleFileView.java b/src/share/demo/jfc/FileChooserDemo/ExampleFileView.java index 6add94197dc472bc15b3eb4dfe2dfbd38240d205..cec4e721c1c0f47c88455a7a5b17eb022aa975f1 100644 --- a/src/share/demo/jfc/FileChooserDemo/ExampleFileView.java +++ b/src/share/demo/jfc/FileChooserDemo/ExampleFileView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,14 +29,13 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import javax.swing.*; import javax.swing.filechooser.*; - import java.io.File; -import java.util.Hashtable; +import java.util.HashMap; +import java.util.Map; + /** * A convenience implementation of the FileView interface that @@ -61,15 +60,19 @@ import java.util.Hashtable; * @author Jeff Dinkins */ public class ExampleFileView extends FileView { - private final Hashtable icons = new Hashtable(); - private final Hashtable fileDescriptions = new Hashtable(); - private final Hashtable typeDescriptions = new Hashtable(); + + private final Map icons = new HashMap(); + private final Map fileDescriptions = + new HashMap(); + private final Map typeDescriptions = + new HashMap(); /** * The name of the file. Do nothing special here. Let * the system file view handle this. * @see FileView#getName */ + @Override public String getName(File f) { return null; } @@ -86,6 +89,7 @@ public class ExampleFileView extends FileView { * * @see FileView#getDescription */ + @Override public String getDescription(File f) { return fileDescriptions.get(f); } @@ -112,6 +116,7 @@ public class ExampleFileView extends FileView { * * @see FileView#getTypeDescription */ + @Override public String getTypeDescription(File f) { return typeDescriptions.get(getExtension(f)); } @@ -122,12 +127,12 @@ public class ExampleFileView extends FileView { */ private String getExtension(File f) { String name = f.getName(); - if(name != null) { + if (name != null) { int extensionIndex = name.lastIndexOf('.'); - if(extensionIndex < 0) { + if (extensionIndex < 0) { return null; } - return name.substring(extensionIndex+1).toLowerCase(); + return name.substring(extensionIndex + 1).toLowerCase(); } return null; } @@ -147,10 +152,11 @@ public class ExampleFileView extends FileView { * * @see FileView#getIcon */ + @Override public Icon getIcon(File f) { Icon icon = null; String extension = getExtension(f); - if(extension != null) { + if (extension != null) { icon = icons.get(extension); } return icon; @@ -168,11 +174,11 @@ public class ExampleFileView extends FileView { * * @see FileView#isTraversable */ + @Override public Boolean isTraversable(File f) { // if (some_reason) { // return Boolean.FALSE; // } return null; // Use default from FileSystemView } - } diff --git a/src/share/demo/jfc/FileChooserDemo/FileChooserDemo.java b/src/share/demo/jfc/FileChooserDemo/FileChooserDemo.java index 97045fb84a555cb1027875f906b94d0a58e09a4b..67e1daee1e8e655e21dcc9f1eacb792efbe95762 100644 --- a/src/share/demo/jfc/FileChooserDemo/FileChooserDemo.java +++ b/src/share/demo/jfc/FileChooserDemo/FileChooserDemo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,34 +29,75 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import javax.swing.*; -import javax.swing.filechooser.*; +import java.lang.reflect.InvocationTargetException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.UIManager.LookAndFeelInfo; +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.util.List; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ButtonGroup; +import javax.swing.DefaultComboBoxModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextField; +import javax.swing.JToggleButton; +import javax.swing.LookAndFeel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.WindowConstants; +import javax.swing.filechooser.FileFilter; +import javax.swing.filechooser.FileNameExtensionFilter; +import javax.swing.filechooser.FileSystemView; +import java.util.ArrayList; import javax.swing.plaf.FileChooserUI; import javax.swing.plaf.basic.BasicFileChooserUI; - -import java.awt.*; import java.io.File; -import java.awt.event.*; -import java.beans.*; -import java.util.Vector; - import static javax.swing.JFileChooser.*; + /** * * A demo which makes extensive use of the file chooser. * * @author Jeff Dinkins */ +@SuppressWarnings("serial") public class FileChooserDemo extends JPanel implements ActionListener { + + public static final String NIMBUS_LAF_NAME = "Nimbus"; private static JFrame frame; + private final List supportedLaFs = + new ArrayList(); + private static SupportedLaF nimbusLaF; - private final Vector supportedLaFs = new Vector(); private static class SupportedLaF { + private final String name; private final LookAndFeel laf; @@ -65,18 +106,15 @@ public class FileChooserDemo extends JPanel implements ActionListener { this.laf = laf; } + @Override public String toString() { return name; } } - - private JButton showButton; - private JCheckBox showAllFilesFilterCheckBox; private JCheckBox showImageFilesFilterCheckBox; private JCheckBox showFullDescriptionCheckBox; - private JCheckBox useFileViewCheckBox; private JCheckBox useFileSystemViewCheckBox; private JCheckBox accessoryCheckBox; @@ -84,46 +122,44 @@ public class FileChooserDemo extends JPanel implements ActionListener { private JCheckBox useEmbedInWizardCheckBox; private JCheckBox useControlsCheckBox; private JCheckBox enableDragCheckBox; - private JRadioButton singleSelectionRadioButton; private JRadioButton multiSelectionRadioButton; - private JRadioButton openRadioButton; private JRadioButton saveRadioButton; private JRadioButton customButton; - private JComboBox lafComboBox; - private JRadioButton justFilesRadioButton; private JRadioButton justDirectoriesRadioButton; private JRadioButton bothFilesAndDirectoriesRadioButton; - private JTextField customField; - private final ExampleFileView fileView; - private final ExampleFileSystemView fileSystemView; - - private final static Dimension hpad10 = new Dimension(10,1); - private final static Dimension vpad20 = new Dimension(1,20); + private final static Dimension hpad10 = new Dimension(10, 1); + private final static Dimension vpad20 = new Dimension(1, 20); private final static Dimension vpad7 = new Dimension(1, 7); private final static Dimension vpad4 = new Dimension(1, 4); private final static Insets insets = new Insets(5, 10, 0, 10); - private final FilePreviewer previewer; private final JFileChooser chooser; + @SuppressWarnings("LeakingThisInConstructor") public FileChooserDemo() { - UIManager.LookAndFeelInfo[] installedLafs = UIManager.getInstalledLookAndFeels(); + UIManager.LookAndFeelInfo[] installedLafs = UIManager. + getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo lafInfo : installedLafs) { try { - Class lnfClass = Class.forName(lafInfo.getClassName()); - LookAndFeel laf = (LookAndFeel)(lnfClass.newInstance()); + Class lnfClass = Class.forName(lafInfo.getClassName()); + LookAndFeel laf = (LookAndFeel) (lnfClass.newInstance()); if (laf.isSupportedLookAndFeel()) { String name = lafInfo.getName(); - supportedLaFs.add(new SupportedLaF(name, laf)); + SupportedLaF supportedLaF = new SupportedLaF(name, laf); + supportedLaFs.add(supportedLaF); + if (NIMBUS_LAF_NAME.equals(name)) { + nimbusLaF = supportedLaF; + } } - } catch (Exception e) { // If ANYTHING weird happens, don't add it + } catch (Exception ignored) { + // If ANYTHING weird happens, don't add this L&F } } @@ -134,8 +170,10 @@ public class FileChooserDemo extends JPanel implements ActionListener { // Create Custom FileView fileView = new ExampleFileView(); - fileView.putIcon("jpg", new ImageIcon(getClass().getResource("/resources/images/jpgIcon.jpg"))); - fileView.putIcon("gif", new ImageIcon(getClass().getResource("/resources/images/gifIcon.gif"))); + fileView.putIcon("jpg", new ImageIcon(getClass().getResource( + "/resources/images/jpgIcon.jpg"))); + fileView.putIcon("gif", new ImageIcon(getClass().getResource( + "/resources/images/gifIcon.gif"))); // Create Custom FileSystemView fileSystemView = new ExampleFileSystemView(); @@ -155,8 +193,11 @@ public class FileChooserDemo extends JPanel implements ActionListener { customButton.addActionListener(optionListener); customField = new JTextField(8) { + + @Override public Dimension getMaximumSize() { - return new Dimension(getPreferredSize().width, getPreferredSize().height); + return new Dimension(getPreferredSize().width, + getPreferredSize().height); } }; customField.setText("Doit"); @@ -220,7 +261,8 @@ public class FileChooserDemo extends JPanel implements ActionListener { group3.add(justDirectoriesRadioButton); justDirectoriesRadioButton.addActionListener(optionListener); - bothFilesAndDirectoriesRadioButton = new JRadioButton("Select Files or Directories"); + bothFilesAndDirectoriesRadioButton = new JRadioButton( + "Select Files or Directories"); group3.add(bothFilesAndDirectoriesRadioButton); bothFilesAndDirectoriesRadioButton.addActionListener(optionListener); @@ -241,7 +283,8 @@ public class FileChooserDemo extends JPanel implements ActionListener { showButton.setMnemonic('s'); // Create laf combo box - lafComboBox = new JComboBox(supportedLaFs); + lafComboBox = new JComboBox(supportedLaFs.toArray()); + lafComboBox.setSelectedItem(nimbusLaF); lafComboBox.setEditable(false); lafComboBox.addActionListener(optionListener); @@ -317,7 +360,8 @@ public class FileChooserDemo extends JPanel implements ActionListener { // ************* File & Directory Options ***************** // ******************************************************** JPanel control4 = new InsetPanel(insets); - control4.setBorder(BorderFactory.createTitledBorder("File and Directory Options")); + control4.setBorder(BorderFactory.createTitledBorder( + "File and Directory Options")); control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS)); control4.add(Box.createRigidArea(vpad20)); control4.add(justFilesRadioButton); @@ -379,7 +423,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { // clear the preview from the previous display of the chooser JComponent accessory = chooser.getAccessory(); if (accessory != null) { - ((FilePreviewer)accessory).loadImage(null); + ((FilePreviewer) accessory).loadImage(null); } if (useEmbedInWizardCheckBox.isSelected()) { @@ -393,25 +437,28 @@ public class FileChooserDemo extends JPanel implements ActionListener { if (retval == APPROVE_OPTION) { JOptionPane.showMessageDialog(frame, getResultString()); } else if (retval == CANCEL_OPTION) { - JOptionPane.showMessageDialog(frame, "User cancelled operation. No file was chosen."); + JOptionPane.showMessageDialog(frame, + "User cancelled operation. No file was chosen."); } else if (retval == ERROR_OPTION) { - JOptionPane.showMessageDialog(frame, "An error occured. No file was chosen."); + JOptionPane.showMessageDialog(frame, + "An error occured. No file was chosen."); } else { JOptionPane.showMessageDialog(frame, "Unknown operation occured."); } } private void resetFileFilters(boolean enableFilters, - boolean showExtensionInDescription) { + boolean showExtensionInDescription) { chooser.resetChoosableFileFilters(); if (enableFilters) { - FileFilter jpgFilter = createFileFilter("JPEG Compressed Image Files", - showExtensionInDescription, "jpg"); + FileFilter jpgFilter = createFileFilter( + "JPEG Compressed Image Files", + showExtensionInDescription, "jpg"); FileFilter gifFilter = createFileFilter("GIF Image Files", - showExtensionInDescription, "gif"); + showExtensionInDescription, "gif"); FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files", - showExtensionInDescription, "jpg", - "gif"); + showExtensionInDescription, "jpg", + "gif"); chooser.addChoosableFileFilter(bothFilter); chooser.addChoosableFileFilter(jpgFilter); chooser.addChoosableFileFilter(gifFilter); @@ -419,7 +466,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { } private FileFilter createFileFilter(String description, - boolean showExtensionInDescription, String...extensions) { + boolean showExtensionInDescription, String... extensions) { if (showExtensionInDescription) { description = createFileNameFilterDescriptionFromExtensions( description, extensions); @@ -429,8 +476,8 @@ public class FileChooserDemo extends JPanel implements ActionListener { private String createFileNameFilterDescriptionFromExtensions( String description, String[] extensions) { - String fullDescription = (description == null) ? - "(" : description + " ("; + String fullDescription = (description == null) ? "(" : description + + " ("; // build the description from the extension list fullDescription += "." + extensions[0]; for (int i = 1; i < extensions.length; i++) { @@ -441,12 +488,15 @@ public class FileChooserDemo extends JPanel implements ActionListener { return fullDescription; } + private class WizardDialog extends JDialog implements ActionListener { + CardLayout cardLayout; JPanel cardPanel; JLabel messageLabel; JButton backButton, nextButton, closeButton; + @SuppressWarnings("LeakingThisInConstructor") WizardDialog(JFrame frame, boolean modal) { super(frame, "Embedded JFileChooser Demo", modal); @@ -494,15 +544,16 @@ public class FileChooserDemo extends JPanel implements ActionListener { // Workaround for bug 4528663. This is necessary to // pick up the contents of the file chooser text field. // This will trigger an APPROVE_SELECTION action. - ((BasicFileChooserUI)ui).getApproveSelectionAction().actionPerformed(null); + ((BasicFileChooserUI) ui).getApproveSelectionAction(). + actionPerformed(null); } else { next(); } } else if (src == closeButton) { close(); - } else if (cmd == APPROVE_SELECTION) { + } else if (APPROVE_SELECTION.equals(cmd)) { next(); - } else if (cmd == CANCEL_SELECTION) { + } else if (CANCEL_SELECTION.equals(cmd)) { close(); } } @@ -528,6 +579,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { setVisible(false); } + @Override public void dispose() { chooser.removeActionListener(this); @@ -542,13 +594,18 @@ public class FileChooserDemo extends JPanel implements ActionListener { private String getResultString() { String resultString; - String filter = chooser.getFileFilter().getDescription(); + String filter; + if (chooser.getFileFilter() == null) { + filter = ""; + } else { + filter = chooser.getFileFilter().getDescription(); + } String path = null; boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY); boolean isMulti = chooser.isMultiSelectionEnabled(); if (isMulti) { - File [] files = chooser.getSelectedFiles(); + File[] files = chooser.getSelectedFiles(); if (files != null && files.length > 0) { path = ""; for (File file : files) { @@ -565,11 +622,10 @@ public class FileChooserDemo extends JPanel implements ActionListener { path = path.replace(" ", " "); filter = filter.replace(" ", " "); resultString = - "You chose " + (isMulti ? "these" : "this") + " " + - (isDirMode ? (isMulti ? "directories" : "directory") - : (isMulti ? "files" : "file")) + - ": " + path + - "

with filter:
" + filter; + "You chose " + (isMulti ? "these" : "this") + " " + (isDirMode ? (isMulti + ? "directories" : "directory") + : (isMulti ? "files" : "file")) + ": " + path + + "

with filter:
" + filter; } else { resultString = "Nothing was chosen"; } @@ -577,15 +633,14 @@ public class FileChooserDemo extends JPanel implements ActionListener { } - - /** An ActionListener that listens to the radio buttons. */ private class OptionListener implements ActionListener { + public void actionPerformed(ActionEvent e) { JComponent c = (JComponent) e.getSource(); boolean selected = false; if (c instanceof JToggleButton) { - selected = ((JToggleButton)c).isSelected(); + selected = ((JToggleButton) c).isSelected(); } if (c == openRadioButton) { @@ -612,7 +667,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { chooser.setAcceptAllFileFilterUsed(selected); } else if (c == showImageFilesFilterCheckBox) { resetFileFilters(selected, - showFullDescriptionCheckBox.isSelected()); + showFullDescriptionCheckBox.isSelected()); showFullDescriptionCheckBox.setEnabled(selected); } else if (c == setHiddenCheckBox) { chooser.setFileHidingEnabled(!selected); @@ -637,7 +692,7 @@ public class FileChooserDemo extends JPanel implements ActionListener { } } else if (c == showFullDescriptionCheckBox) { resetFileFilters(showImageFilesFilterCheckBox.isSelected(), - selected); + selected); } else if (c == justFilesRadioButton) { chooser.setFileSelectionMode(FILES_ONLY); } else if (c == justDirectoriesRadioButton) { @@ -653,27 +708,33 @@ public class FileChooserDemo extends JPanel implements ActionListener { chooser.setMultiSelectionEnabled(true); } } else if (c == lafComboBox) { - SupportedLaF supportedLaF = ((SupportedLaF)lafComboBox.getSelectedItem()); + SupportedLaF supportedLaF = ((SupportedLaF) lafComboBox. + getSelectedItem()); LookAndFeel laf = supportedLaF.laf; try { UIManager.setLookAndFeel(laf); SwingUtilities.updateComponentTreeUI(frame); - if(chooser != null) { + if (chooser != null) { SwingUtilities.updateComponentTreeUI(chooser); } frame.pack(); } catch (UnsupportedLookAndFeelException exc) { // This should not happen because we already checked - ((DefaultComboBoxModel)lafComboBox.getModel()).removeElement(supportedLaF); + ((DefaultComboBoxModel) lafComboBox.getModel()). + removeElement(supportedLaF); } } } } - private class FilePreviewer extends JComponent implements PropertyChangeListener { + + private class FilePreviewer extends JComponent implements + PropertyChangeListener { + ImageIcon thumbnail = null; + @SuppressWarnings("LeakingThisInConstructor") public FilePreviewer(JFileChooser fc) { setPreferredSize(new Dimension(100, 50)); fc.addPropertyChangeListener(this); @@ -684,9 +745,10 @@ public class FileChooserDemo extends JPanel implements ActionListener { thumbnail = null; } else { ImageIcon tmpIcon = new ImageIcon(f.getPath()); - if(tmpIcon.getIconWidth() > 90) { + if (tmpIcon.getIconWidth() > 90) { thumbnail = new ImageIcon( - tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT)); + tmpIcon.getImage().getScaledInstance(90, -1, + Image.SCALE_DEFAULT)); } else { thumbnail = tmpIcon; } @@ -695,23 +757,24 @@ public class FileChooserDemo extends JPanel implements ActionListener { public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); - if (prop == SELECTED_FILE_CHANGED_PROPERTY) { - if(isShowing()) { + if (SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) { + if (isShowing()) { loadImage((File) e.getNewValue()); repaint(); } } } + @Override public void paint(Graphics g) { - if(thumbnail != null) { - int x = getWidth()/2 - thumbnail.getIconWidth()/2; - int y = getHeight()/2 - thumbnail.getIconHeight()/2; - if(y < 0) { + if (thumbnail != null) { + int x = getWidth() / 2 - thumbnail.getIconWidth() / 2; + int y = getHeight() / 2 - thumbnail.getIconHeight() / 2; + if (y < 0) { y = 0; } - if(x < 5) { + if (x < 5) { x = 5; } thumbnail.paintIcon(this, g, x, y); @@ -720,46 +783,57 @@ public class FileChooserDemo extends JPanel implements ActionListener { } public static void main(String s[]) { - /* - NOTE: By default, the look and feel will be set to the - Cross Platform Look and Feel (which is currently Metal). - The user may someday be able to override the default - via a system property. If you as the developer want to - be sure that a particular L&F is set, you can do so - by calling UIManager.setLookAndFeel(). For example, the - first code snippet below forcibly sets the UI to be the - System Look and Feel. The second code snippet forcibly - sets the look and feel to the Cross Platform L&F. - - Snippet 1: - try { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch (Exception exc) { - System.err.println("Error loading L&F: " + exc); - } - - Snippet 2: - try { - UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); - } catch (Exception exc) { - System.err.println("Error loading L&F: " + exc); - } - */ - - FileChooserDemo panel = new FileChooserDemo(); - - frame = new JFrame("FileChooserDemo"); - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - frame.getContentPane().add("Center", panel); - frame.pack(); - frame.setVisible(true); + try { + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + /* + * NOTE: By default, the look and feel will be set to the + * Cross Platform Look and Feel (which is currently Metal). + * The following code tries to set the Look and Feel to Nimbus. + * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html + */ + try { + for (LookAndFeelInfo info : UIManager. + getInstalledLookAndFeels()) { + if (NIMBUS_LAF_NAME.equals(info.getName())) { + UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (Exception ignored) { + } + + FileChooserDemo panel = new FileChooserDemo(); + + frame = new JFrame("FileChooserDemo"); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.getContentPane().add("Center", panel); + frame.pack(); + frame.setVisible(true); + } + }); + } catch (InterruptedException ex) { + Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE, + null, + ex); + } catch (InvocationTargetException ex) { + Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE, + null, + ex); + } } + private static class InsetPanel extends JPanel { + Insets i; + InsetPanel(Insets i) { this.i = i; } + + @Override public Insets getInsets() { return i; } diff --git a/src/share/demo/jfc/Metalworks/AquaMetalTheme.java b/src/share/demo/jfc/Metalworks/AquaMetalTheme.java index 52cf5e12e62e2bd4628e9159e128ae87ed62e205..363a0cfb9dcede0843e452c9a3272b824a424a6a 100644 --- a/src/share/demo/jfc/Metalworks/AquaMetalTheme.java +++ b/src/share/demo/jfc/Metalworks/AquaMetalTheme.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,31 +29,39 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ +import javax.swing.plaf.ColorUIResource; +import javax.swing.plaf.metal.DefaultMetalTheme; -import javax.swing.plaf.*; -import javax.swing.plaf.metal.*; -import javax.swing.*; -import javax.swing.border.*; -import java.awt.*; /** * This class describes a theme using "blue-green" colors. * * @author Steve Wilson + * @author Alexander Kouznetsov */ public class AquaMetalTheme extends DefaultMetalTheme { - public String getName() { return "Oxide"; } - + @Override + public String getName() { + return "Oxide"; + } private final ColorUIResource primary1 = new ColorUIResource(102, 153, 153); private final ColorUIResource primary2 = new ColorUIResource(128, 192, 192); private final ColorUIResource primary3 = new ColorUIResource(159, 235, 235); - protected ColorUIResource getPrimary1() { return primary1; } - protected ColorUIResource getPrimary2() { return primary2; } - protected ColorUIResource getPrimary3() { return primary3; } + @Override + protected ColorUIResource getPrimary1() { + return primary1; + } + + @Override + protected ColorUIResource getPrimary2() { + return primary2; + } + @Override + protected ColorUIResource getPrimary3() { + return primary3; + } } diff --git a/src/share/demo/jfc/Metalworks/BigContrastMetalTheme.java b/src/share/demo/jfc/Metalworks/BigContrastMetalTheme.java index b89918c55682dd0eaba326ad682c3f75a906a7e3..3402320a0976a67f077f1b0b73dc1b433bca101c 100644 --- a/src/share/demo/jfc/Metalworks/BigContrastMetalTheme.java +++ b/src/share/demo/jfc/Metalworks/BigContrastMetalTheme.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,9 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ - import javax.swing.plaf.*; import javax.swing.plaf.metal.*; @@ -39,54 +36,91 @@ import javax.swing.*; import javax.swing.border.*; import java.awt.*; + /** * This class describes a theme using "green" colors. * * @author Steve Wilson + * @author Alexander Kouznetsov */ public class BigContrastMetalTheme extends ContrastMetalTheme { - public String getName() { return "Low Vision"; } + @Override + public String getName() { + return "Low Vision"; + } + private final FontUIResource controlFont = new FontUIResource("Dialog", + Font.BOLD, 24); + private final FontUIResource systemFont = new FontUIResource("Dialog", + Font.PLAIN, 24); + private final FontUIResource windowTitleFont = new FontUIResource("Dialog", + Font.BOLD, 24); + private final FontUIResource userFont = new FontUIResource("SansSerif", + Font.PLAIN, 24); + private final FontUIResource smallFont = new FontUIResource("Dialog", + Font.PLAIN, 20); + + @Override + public FontUIResource getControlTextFont() { + return controlFont; + } - private final FontUIResource controlFont = new FontUIResource("Dialog", Font.BOLD, 24); - private final FontUIResource systemFont = new FontUIResource("Dialog", Font.PLAIN, 24); - private final FontUIResource windowTitleFont = new FontUIResource("Dialog", Font.BOLD, 24); - private final FontUIResource userFont = new FontUIResource("SansSerif", Font.PLAIN, 24); - private final FontUIResource smallFont = new FontUIResource("Dialog", Font.PLAIN, 20); + @Override + public FontUIResource getSystemTextFont() { + return systemFont; + } + @Override + public FontUIResource getUserTextFont() { + return userFont; + } + + @Override + public FontUIResource getMenuTextFont() { + return controlFont; + } - public FontUIResource getControlTextFont() { return controlFont;} - public FontUIResource getSystemTextFont() { return systemFont;} - public FontUIResource getUserTextFont() { return userFont;} - public FontUIResource getMenuTextFont() { return controlFont;} - public FontUIResource getWindowTitleFont() { return windowTitleFont;} - public FontUIResource getSubTextFont() { return smallFont;} + @Override + public FontUIResource getWindowTitleFont() { + return windowTitleFont; + } + + @Override + public FontUIResource getSubTextFont() { + return smallFont; + } + @Override public void addCustomEntriesToTable(UIDefaults table) { - super.addCustomEntriesToTable(table); + super.addCustomEntriesToTable(table); - final int internalFrameIconSize = 30; - table.put("InternalFrame.closeIcon", MetalIconFactory.getInternalFrameCloseIcon(internalFrameIconSize)); - table.put("InternalFrame.maximizeIcon", MetalIconFactory.getInternalFrameMaximizeIcon(internalFrameIconSize)); - table.put("InternalFrame.iconifyIcon", MetalIconFactory.getInternalFrameMinimizeIcon(internalFrameIconSize)); - table.put("InternalFrame.minimizeIcon", MetalIconFactory.getInternalFrameAltMaximizeIcon(internalFrameIconSize)); + final int internalFrameIconSize = 30; + table.put("InternalFrame.closeIcon", MetalIconFactory. + getInternalFrameCloseIcon(internalFrameIconSize)); + table.put("InternalFrame.maximizeIcon", MetalIconFactory. + getInternalFrameMaximizeIcon(internalFrameIconSize)); + table.put("InternalFrame.iconifyIcon", MetalIconFactory. + getInternalFrameMinimizeIcon(internalFrameIconSize)); + table.put("InternalFrame.minimizeIcon", MetalIconFactory. + getInternalFrameAltMaximizeIcon(internalFrameIconSize)); - Border blackLineBorder = new BorderUIResource( new MatteBorder( 2,2,2,2, Color.black) ); + Border blackLineBorder = new BorderUIResource(new MatteBorder(2, 2, 2, 2, + Color.black)); Border textBorder = blackLineBorder; - table.put( "ToolTip.border", blackLineBorder); - table.put( "TitledBorder.border", blackLineBorder); + table.put("ToolTip.border", blackLineBorder); + table.put("TitledBorder.border", blackLineBorder); - table.put( "TextField.border", textBorder); - table.put( "PasswordField.border", textBorder); - table.put( "TextArea.border", textBorder); - table.put( "TextPane.font", textBorder); + table.put("TextField.border", textBorder); + table.put("PasswordField.border", textBorder); + table.put("TextArea.border", textBorder); + table.put("TextPane.font", textBorder); - table.put( "ScrollPane.border", blackLineBorder); + table.put("ScrollPane.border", blackLineBorder); - table.put( "ScrollBar.width", new Integer(25) ); + table.put("ScrollBar.width", 25); diff --git a/src/share/demo/jfc/Metalworks/ContrastMetalTheme.java b/src/share/demo/jfc/Metalworks/ContrastMetalTheme.java index 0b99567bb6429b01a024e9c7bfd9a934cd42ffb0..62d7f39e65bcddc3b076bd103da1eedf15b1f053 100644 --- a/src/share/demo/jfc/Metalworks/ContrastMetalTheme.java +++ b/src/share/demo/jfc/Metalworks/ContrastMetalTheme.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,75 +29,131 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import javax.swing.plaf.*; -import javax.swing.plaf.basic.*; -import javax.swing.plaf.metal.*; -import javax.swing.*; -import javax.swing.border.*; -import java.awt.*; +import javax.swing.UIDefaults; +import javax.swing.border.Border; +import javax.swing.border.CompoundBorder; +import javax.swing.border.LineBorder; +import javax.swing.plaf.BorderUIResource; +import javax.swing.plaf.ColorUIResource; +import javax.swing.plaf.basic.BasicBorders; +import javax.swing.plaf.metal.DefaultMetalTheme; + /** * This class describes a higher-contrast Metal Theme. * * @author Michael C. Albers + * @author Alexander Kouznetsov */ - public class ContrastMetalTheme extends DefaultMetalTheme { - public String getName() { return "Contrast"; } - + @Override + public String getName() { + return "Contrast"; + } private final ColorUIResource primary1 = new ColorUIResource(0, 0, 0); private final ColorUIResource primary2 = new ColorUIResource(204, 204, 204); private final ColorUIResource primary3 = new ColorUIResource(255, 255, 255); - private final ColorUIResource primaryHighlight = new ColorUIResource(102,102,102); + private final ColorUIResource primaryHighlight = new ColorUIResource(102, + 102, 102); + private final ColorUIResource secondary2 = + new ColorUIResource(204, 204, 204); + private final ColorUIResource secondary3 = + new ColorUIResource(255, 255, 255); + + @Override + protected ColorUIResource getPrimary1() { + return primary1; + } - private final ColorUIResource secondary2 = new ColorUIResource(204, 204, 204); - private final ColorUIResource secondary3 = new ColorUIResource(255, 255, 255); - private final ColorUIResource controlHighlight = new ColorUIResource(102,102,102); + @Override + protected ColorUIResource getPrimary2() { + return primary2; + } - protected ColorUIResource getPrimary1() { return primary1; } - protected ColorUIResource getPrimary2() { return primary2; } - protected ColorUIResource getPrimary3() { return primary3; } - public ColorUIResource getPrimaryControlHighlight() { return primaryHighlight;} + @Override + protected ColorUIResource getPrimary3() { + return primary3; + } - protected ColorUIResource getSecondary2() { return secondary2; } - protected ColorUIResource getSecondary3() { return secondary3; } - public ColorUIResource getControlHighlight() { return super.getSecondary3(); } + @Override + public ColorUIResource getPrimaryControlHighlight() { + return primaryHighlight; + } - public ColorUIResource getFocusColor() { return getBlack(); } + @Override + protected ColorUIResource getSecondary2() { + return secondary2; + } - public ColorUIResource getTextHighlightColor() { return getBlack(); } - public ColorUIResource getHighlightedTextColor() { return getWhite(); } + @Override + protected ColorUIResource getSecondary3() { + return secondary3; + } - public ColorUIResource getMenuSelectedBackground() { return getBlack(); } - public ColorUIResource getMenuSelectedForeground() { return getWhite(); } - public ColorUIResource getAcceleratorForeground() { return getBlack(); } - public ColorUIResource getAcceleratorSelectedForeground() { return getWhite(); } + @Override + public ColorUIResource getControlHighlight() { + return super.getSecondary3(); + } + @Override + public ColorUIResource getFocusColor() { + return getBlack(); + } + @Override + public ColorUIResource getTextHighlightColor() { + return getBlack(); + } + + @Override + public ColorUIResource getHighlightedTextColor() { + return getWhite(); + } + + @Override + public ColorUIResource getMenuSelectedBackground() { + return getBlack(); + } + + @Override + public ColorUIResource getMenuSelectedForeground() { + return getWhite(); + } + + @Override + public ColorUIResource getAcceleratorForeground() { + return getBlack(); + } + + @Override + public ColorUIResource getAcceleratorSelectedForeground() { + return getWhite(); + } + + @Override public void addCustomEntriesToTable(UIDefaults table) { - Border blackLineBorder = new BorderUIResource(new LineBorder( getBlack() )); - Border whiteLineBorder = new BorderUIResource(new LineBorder( getWhite() )); + Border blackLineBorder = + new BorderUIResource(new LineBorder(getBlack())); + Border whiteLineBorder = + new BorderUIResource(new LineBorder(getWhite())); - Object textBorder = new BorderUIResource( new CompoundBorder( - blackLineBorder, - new BasicBorders.MarginBorder())); + Object textBorder = new BorderUIResource(new CompoundBorder( + blackLineBorder, + new BasicBorders.MarginBorder())); - table.put( "ToolTip.border", blackLineBorder); - table.put( "TitledBorder.border", blackLineBorder); - table.put( "Table.focusCellHighlightBorder", whiteLineBorder); - table.put( "Table.focusCellForeground", getWhite()); + table.put("ToolTip.border", blackLineBorder); + table.put("TitledBorder.border", blackLineBorder); + table.put("Table.focusCellHighlightBorder", whiteLineBorder); + table.put("Table.focusCellForeground", getWhite()); - table.put( "TextField.border", textBorder); - table.put( "PasswordField.border", textBorder); - table.put( "TextArea.border", textBorder); - table.put( "TextPane.font", textBorder); + table.put("TextField.border", textBorder); + table.put("PasswordField.border", textBorder); + table.put("TextArea.border", textBorder); + table.put("TextPane.font", textBorder); } - } diff --git a/src/share/demo/jfc/Metalworks/DemoMetalTheme.java b/src/share/demo/jfc/Metalworks/DemoMetalTheme.java index 30f560729d7fe48d86ef53fb7661e588ad0984a0..3724630ff36d94170d2860543031efc2f569c736 100644 --- a/src/share/demo/jfc/Metalworks/DemoMetalTheme.java +++ b/src/share/demo/jfc/Metalworks/DemoMetalTheme.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,15 +29,13 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ +import java.awt.Font; +import javax.swing.UIDefaults; +import javax.swing.plaf.FontUIResource; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalIconFactory; -import javax.swing.plaf.*; -import javax.swing.plaf.metal.*; -import javax.swing.*; -import javax.swing.border.*; -import java.awt.*; /** * This class describes a theme using large fonts. @@ -45,37 +43,71 @@ import java.awt.*; * where people will have trouble seeing what you're doing. * * @author Steve Wilson + * @author Alexander Kouznetsov */ public class DemoMetalTheme extends DefaultMetalTheme { - public String getName() { return "Presentation"; } + @Override + public String getName() { + return "Presentation"; + } + private final FontUIResource controlFont = new FontUIResource("Dialog", + Font.BOLD, 18); + private final FontUIResource systemFont = new FontUIResource("Dialog", + Font.PLAIN, 18); + private final FontUIResource userFont = new FontUIResource("SansSerif", + Font.PLAIN, 18); + private final FontUIResource smallFont = new FontUIResource("Dialog", + Font.PLAIN, 14); + + @Override + public FontUIResource getControlTextFont() { + return controlFont; + } + + @Override + public FontUIResource getSystemTextFont() { + return systemFont; + } + + @Override + public FontUIResource getUserTextFont() { + return userFont; + } - private final FontUIResource controlFont = new FontUIResource("Dialog", Font.BOLD, 18); - private final FontUIResource systemFont = new FontUIResource("Dialog", Font.PLAIN, 18); - private final FontUIResource userFont = new FontUIResource("SansSerif", Font.PLAIN, 18); - private final FontUIResource smallFont = new FontUIResource("Dialog", Font.PLAIN, 14); + @Override + public FontUIResource getMenuTextFont() { + return controlFont; + } - public FontUIResource getControlTextFont() { return controlFont;} - public FontUIResource getSystemTextFont() { return systemFont;} - public FontUIResource getUserTextFont() { return userFont;} - public FontUIResource getMenuTextFont() { return controlFont;} - public FontUIResource getWindowTitleFont() { return controlFont;} - public FontUIResource getSubTextFont() { return smallFont;} + @Override + public FontUIResource getWindowTitleFont() { + return controlFont; + } + @Override + public FontUIResource getSubTextFont() { + return smallFont; + } + + @Override public void addCustomEntriesToTable(UIDefaults table) { - super.addCustomEntriesToTable(table); + super.addCustomEntriesToTable(table); - final int internalFrameIconSize = 22; - table.put("InternalFrame.closeIcon", MetalIconFactory.getInternalFrameCloseIcon(internalFrameIconSize)); - table.put("InternalFrame.maximizeIcon", MetalIconFactory.getInternalFrameMaximizeIcon(internalFrameIconSize)); - table.put("InternalFrame.iconifyIcon", MetalIconFactory.getInternalFrameMinimizeIcon(internalFrameIconSize)); - table.put("InternalFrame.minimizeIcon", MetalIconFactory.getInternalFrameAltMaximizeIcon(internalFrameIconSize)); + final int internalFrameIconSize = 22; + table.put("InternalFrame.closeIcon", MetalIconFactory. + getInternalFrameCloseIcon(internalFrameIconSize)); + table.put("InternalFrame.maximizeIcon", MetalIconFactory. + getInternalFrameMaximizeIcon(internalFrameIconSize)); + table.put("InternalFrame.iconifyIcon", MetalIconFactory. + getInternalFrameMinimizeIcon(internalFrameIconSize)); + table.put("InternalFrame.minimizeIcon", MetalIconFactory. + getInternalFrameAltMaximizeIcon(internalFrameIconSize)); - table.put( "ScrollBar.width", new Integer(21) ); + table.put("ScrollBar.width", 21); } - } diff --git a/src/share/demo/jfc/Metalworks/GreenMetalTheme.java b/src/share/demo/jfc/Metalworks/GreenMetalTheme.java index 77348ef94e1e1f97860830a3891ade73f28179a3..ceb299de9e2286340383fa26cc5ca3a29293ad9a 100644 --- a/src/share/demo/jfc/Metalworks/GreenMetalTheme.java +++ b/src/share/demo/jfc/Metalworks/GreenMetalTheme.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,32 +29,40 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ +import javax.swing.plaf.ColorUIResource; +import javax.swing.plaf.metal.DefaultMetalTheme; -import javax.swing.plaf.*; -import javax.swing.plaf.metal.*; -import javax.swing.*; -import javax.swing.border.*; -import java.awt.*; /** * This class describes a theme using "green" colors. * * @author Steve Wilson + * @author Alexander Kouznetsov */ public class GreenMetalTheme extends DefaultMetalTheme { - public String getName() { return "Emerald"; } - - // greenish colors + @Override + public String getName() { + return "Emerald"; + } + // greenish colors private final ColorUIResource primary1 = new ColorUIResource(51, 102, 51); private final ColorUIResource primary2 = new ColorUIResource(102, 153, 102); private final ColorUIResource primary3 = new ColorUIResource(153, 204, 153); - protected ColorUIResource getPrimary1() { return primary1; } - protected ColorUIResource getPrimary2() { return primary2; } - protected ColorUIResource getPrimary3() { return primary3; } + @Override + protected ColorUIResource getPrimary1() { + return primary1; + } + + @Override + protected ColorUIResource getPrimary2() { + return primary2; + } + @Override + protected ColorUIResource getPrimary3() { + return primary3; + } } diff --git a/src/share/demo/jfc/Metalworks/KhakiMetalTheme.java b/src/share/demo/jfc/Metalworks/KhakiMetalTheme.java index db8733e545c7ca287cc7fbf4a7ddd4c86e4b568b..90e125922203fe7dba2ccff468bec8e33084769a 100644 --- a/src/share/demo/jfc/Metalworks/KhakiMetalTheme.java +++ b/src/share/demo/jfc/Metalworks/KhakiMetalTheme.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,39 +29,60 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ +import javax.swing.plaf.ColorUIResource; +import javax.swing.plaf.metal.DefaultMetalTheme; -import javax.swing.plaf.*; -import javax.swing.plaf.metal.*; -import javax.swing.*; -import javax.swing.border.*; -import java.awt.*; /** * This class describes a theme using "khaki" colors. * * @author Steve Wilson + * @author Alexander Kouznetsov */ public class KhakiMetalTheme extends DefaultMetalTheme { - public String getName() { return "Sandstone"; } - - private final ColorUIResource primary1 = new ColorUIResource( 87, 87, 47); + @Override + public String getName() { + return "Sandstone"; + } + private final ColorUIResource primary1 = new ColorUIResource(87, 87, 47); private final ColorUIResource primary2 = new ColorUIResource(159, 151, 111); private final ColorUIResource primary3 = new ColorUIResource(199, 183, 143); + private final ColorUIResource secondary1 = + new ColorUIResource(111, 111, 111); + private final ColorUIResource secondary2 = + new ColorUIResource(159, 159, 159); + private final ColorUIResource secondary3 = + new ColorUIResource(231, 215, 183); + + @Override + protected ColorUIResource getPrimary1() { + return primary1; + } + + @Override + protected ColorUIResource getPrimary2() { + return primary2; + } - private final ColorUIResource secondary1 = new ColorUIResource( 111, 111, 111); - private final ColorUIResource secondary2 = new ColorUIResource(159, 159, 159); - private final ColorUIResource secondary3 = new ColorUIResource(231, 215, 183); + @Override + protected ColorUIResource getPrimary3() { + return primary3; + } - protected ColorUIResource getPrimary1() { return primary1; } - protected ColorUIResource getPrimary2() { return primary2; } - protected ColorUIResource getPrimary3() { return primary3; } + @Override + protected ColorUIResource getSecondary1() { + return secondary1; + } - protected ColorUIResource getSecondary1() { return secondary1; } - protected ColorUIResource getSecondary2() { return secondary2; } - protected ColorUIResource getSecondary3() { return secondary3; } + @Override + protected ColorUIResource getSecondary2() { + return secondary2; + } + @Override + protected ColorUIResource getSecondary3() { + return secondary3; + } } diff --git a/src/share/demo/jfc/Metalworks/MetalThemeMenu.java b/src/share/demo/jfc/Metalworks/MetalThemeMenu.java index 35e186500582a0e7bda45a67c0e6dd25d2309f0a..a837228743f29a00e58515ed086476d9f9640a34 100644 --- a/src/share/demo/jfc/Metalworks/MetalThemeMenu.java +++ b/src/share/demo/jfc/Metalworks/MetalThemeMenu.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,51 +29,57 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.ButtonGroup; +import javax.swing.JMenu; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.UIManager; +import javax.swing.plaf.metal.MetalLookAndFeel; +import javax.swing.plaf.metal.MetalTheme; -import javax.swing.plaf.metal.*; -import javax.swing.*; -import javax.swing.border.*; -import java.awt.*; -import java.awt.event.*; /** * This class describes a theme using "green" colors. * * @author Steve Wilson + * @author Alexander Kouznetsov */ -public class MetalThemeMenu extends JMenu implements ActionListener{ +@SuppressWarnings("serial") +public class MetalThemeMenu extends JMenu implements ActionListener { - MetalTheme[] themes; - public MetalThemeMenu(String name, MetalTheme[] themeArray) { - super(name); - themes = themeArray; - ButtonGroup group = new ButtonGroup(); - for (int i = 0; i < themes.length; i++) { - JRadioButtonMenuItem item = new JRadioButtonMenuItem( themes[i].getName() ); - group.add(item); - add( item ); - item.setActionCommand(i+""); - item.addActionListener(this); - if ( i == 0) - item.setSelected(true); - } + MetalTheme[] themes; - } + @SuppressWarnings("LeakingThisInConstructor") + public MetalThemeMenu(String name, MetalTheme[] themeArray) { + super(name); + themes = themeArray; + ButtonGroup group = new ButtonGroup(); + for (int i = 0; i < themes.length; i++) { + JRadioButtonMenuItem item = new JRadioButtonMenuItem(themes[i]. + getName()); + group.add(item); + add(item); + item.setActionCommand(i + ""); + item.addActionListener(this); + if (i == 0) { + item.setSelected(true); + } + } - public void actionPerformed(ActionEvent e) { - String numStr = e.getActionCommand(); - MetalTheme selectedTheme = themes[ Integer.parseInt(numStr) ]; - MetalLookAndFeel.setCurrentTheme(selectedTheme); - try { - UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); - } catch (Exception ex) { - System.out.println("Failed loading Metal"); - System.out.println(ex); } - } + public void actionPerformed(ActionEvent e) { + String numStr = e.getActionCommand(); + MetalTheme selectedTheme = themes[Integer.parseInt(numStr)]; + MetalLookAndFeel.setCurrentTheme(selectedTheme); + try { + UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); + } catch (Exception ex) { + System.out.println("Failed loading Metal"); + System.out.println(ex); + } + } } diff --git a/src/share/demo/jfc/Metalworks/Metalworks.java b/src/share/demo/jfc/Metalworks/Metalworks.java index 072076d0ccf983fc70fc5be615c064670f2435ab..22322c26d9f599ae2b3977086a546aa867253626 100644 --- a/src/share/demo/jfc/Metalworks/Metalworks.java +++ b/src/share/demo/jfc/Metalworks/Metalworks.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,34 +29,35 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ - -import java.awt.*; -import javax.swing.*; -import javax.swing.border.*; +import java.awt.Toolkit; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; import javax.swing.plaf.metal.MetalLookAndFeel; + /** - * This application is a demo of the Metal Look & Feel - * - * @author Steve Wilson - */ + * This application is a demo of the Metal Look & Feel + * + * @author Steve Wilson + * @author Alexander Kouznetsov + */ public class Metalworks { - public static void main( String[] args ) { + public static void main(String[] args) { UIManager.put("swing.boldMetal", Boolean.FALSE); JDialog.setDefaultLookAndFeelDecorated(true); JFrame.setDefaultLookAndFeelDecorated(true); Toolkit.getDefaultToolkit().setDynamicLayout(true); - System.setProperty("sun.awt.noerasebackground","true"); - + System.setProperty("sun.awt.noerasebackground", "true"); try { UIManager.setLookAndFeel(new MetalLookAndFeel()); - } - catch ( UnsupportedLookAndFeelException e ) { - System.out.println ("Metal Look & Feel not supported on this platform. \nProgram Terminated"); + } catch (UnsupportedLookAndFeelException e) { + System.out.println( + "Metal Look & Feel not supported on this platform. \n" + + "Program Terminated"); System.exit(0); } JFrame frame = new MetalworksFrame(); diff --git a/src/share/demo/jfc/Metalworks/MetalworksDocumentFrame.java b/src/share/demo/jfc/Metalworks/MetalworksDocumentFrame.java index eb65119217a9134359b93becb7c5d2c35dfea173..5802e77c69458dfb13ba35a242662edba763adbe 100644 --- a/src/share/demo/jfc/Metalworks/MetalworksDocumentFrame.java +++ b/src/share/demo/jfc/Metalworks/MetalworksDocumentFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,21 +29,32 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.*; -import java.awt.event.*; -import java.util.*; -import javax.swing.*; -import javax.swing.border.*; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Insets; +import java.awt.LayoutManager; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import javax.swing.JComponent; +import javax.swing.JInternalFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.border.EmptyBorder; /** - * This is a subclass of JInternalFrame which displays documents. - * - * @author Steve Wilson - */ + * This is a subclass of JInternalFrame which displays documents. + * + * @author Steve Wilson + */ +@SuppressWarnings("serial") public class MetalworksDocumentFrame extends JInternalFrame { static int openFrameCount = 0; @@ -59,27 +70,27 @@ public class MetalworksDocumentFrame extends JInternalFrame { top.setLayout(new BorderLayout()); top.add(buildAddressPanel(), BorderLayout.NORTH); - JTextArea content = new JTextArea( 15, 30 ); - content.setBorder( new EmptyBorder(0,5 ,0, 5) ); + JTextArea content = new JTextArea(15, 30); + content.setBorder(new EmptyBorder(0, 5, 0, 5)); content.setLineWrap(true); JScrollPane textScroller = new JScrollPane(content, - JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); - top.add( textScroller, BorderLayout.CENTER); + JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + top.add(textScroller, BorderLayout.CENTER); setContentPane(top); pack(); - setLocation( offset * openFrameCount, offset *openFrameCount); + setLocation(offset * openFrameCount, offset * openFrameCount); } private JPanel buildAddressPanel() { JPanel p = new JPanel(); - p.setLayout( new LabeledPairLayout() ); + p.setLayout(new LabeledPairLayout()); JLabel toLabel = new JLabel("To: ", JLabel.RIGHT); @@ -103,83 +114,79 @@ public class MetalworksDocumentFrame extends JInternalFrame { } - class LabeledPairLayout implements LayoutManager { - - Vector labels = new Vector(); - Vector fields = new Vector(); - - int yGap = 2; - int xGap = 2; - - public void addLayoutComponent(String s, Component c) { - if (s.equals("label")) { - labels.addElement(c); - } else { - fields.addElement(c); - } - } - - public void layoutContainer(Container c) { - Insets insets = c.getInsets(); - - int labelWidth = 0; - Enumeration labelIter = labels.elements(); - while(labelIter.hasMoreElements()) { - JComponent comp = (JComponent)labelIter.nextElement(); - labelWidth = Math.max( labelWidth, comp.getPreferredSize().width ); - } - - int yPos = insets.top; - - Enumeration fieldIter = fields.elements(); - labelIter = labels.elements(); - while(labelIter.hasMoreElements() && fieldIter.hasMoreElements()) { - JComponent label = (JComponent)labelIter.nextElement(); - JComponent field = (JComponent)fieldIter.nextElement(); - int height = Math.max(label.getPreferredSize().height, field.getPreferredSize().height); - label.setBounds( insets.left, yPos, labelWidth, height ); - field.setBounds( insets.left + labelWidth + xGap, - yPos, - c.getSize().width - (labelWidth +xGap + insets.left + insets.right), - height ); - yPos += (height + yGap); - } - - } - - - public Dimension minimumLayoutSize(Container c) { - Insets insets = c.getInsets(); - - int labelWidth = 0; - Enumeration labelIter = labels.elements(); - while(labelIter.hasMoreElements()) { - JComponent comp = (JComponent)labelIter.nextElement(); - labelWidth = Math.max( labelWidth, comp.getPreferredSize().width ); - } - - int yPos = insets.top; - - labelIter = labels.elements(); - Enumeration fieldIter = fields.elements(); - while(labelIter.hasMoreElements() && fieldIter.hasMoreElements()) { - JComponent label = (JComponent)labelIter.nextElement(); - JComponent field = (JComponent)fieldIter.nextElement(); - int height = Math.max(label.getPreferredSize().height, field.getPreferredSize().height); - yPos += (height + yGap); - } - return new Dimension( labelWidth * 3 , yPos ); - } - - public Dimension preferredLayoutSize(Container c) { - Dimension d = minimumLayoutSize(c); - d.width *= 2; - return d; - } - - public void removeLayoutComponent(Component c) {} - -} + class LabeledPairLayout implements LayoutManager { + List labels = new ArrayList(); + List fields = new ArrayList(); + int yGap = 2; + int xGap = 2; + + public void addLayoutComponent(String s, Component c) { + if (s.equals("label")) { + labels.add(c); + } else { + fields.add(c); + } + } + + public void layoutContainer(Container c) { + Insets insets = c.getInsets(); + + int labelWidth = 0; + for (Component comp : labels) { + labelWidth = Math.max(labelWidth, comp.getPreferredSize().width); + } + + int yPos = insets.top; + + Iterator fieldIter = fields.listIterator(); + Iterator labelIter = labels.listIterator(); + while (labelIter.hasNext() && fieldIter.hasNext()) { + JComponent label = (JComponent) labelIter.next(); + JComponent field = (JComponent) fieldIter.next(); + int height = Math.max(label.getPreferredSize().height, field. + getPreferredSize().height); + label.setBounds(insets.left, yPos, labelWidth, height); + field.setBounds(insets.left + labelWidth + xGap, + yPos, + c.getSize().width - (labelWidth + xGap + insets.left + + insets.right), + height); + yPos += (height + yGap); + } + + } + + public Dimension minimumLayoutSize(Container c) { + Insets insets = c.getInsets(); + + int labelWidth = 0; + for (Component comp : labels) { + labelWidth = Math.max(labelWidth, comp.getPreferredSize().width); + } + + int yPos = insets.top; + + Iterator labelIter = labels.listIterator(); + Iterator fieldIter = fields.listIterator(); + while (labelIter.hasNext() && fieldIter.hasNext()) { + Component label = labelIter.next(); + Component field = fieldIter.next(); + int height = Math.max(label.getPreferredSize().height, field. + getPreferredSize().height); + yPos += (height + yGap); + } + return new Dimension(labelWidth * 3, yPos); + } + + public Dimension preferredLayoutSize(Container c) { + Dimension d = minimumLayoutSize(c); + d.width *= 2; + return d; + } + + public void removeLayoutComponent(Component c) { + } + } } diff --git a/src/share/demo/jfc/Metalworks/MetalworksFrame.java b/src/share/demo/jfc/Metalworks/MetalworksFrame.java index b3dac9397fe5604ba21204a28a522ab95ed9df47..77fa685a38c322f8204b5f8481f9a92141b96f23 100644 --- a/src/share/demo/jfc/Metalworks/MetalworksFrame.java +++ b/src/share/demo/jfc/Metalworks/MetalworksFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,50 +29,70 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.*; -import java.io.*; -import java.awt.event.*; -import java.beans.*; -import javax.swing.*; -import javax.swing.border.*; - -import javax.swing.plaf.metal.*; +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.InputStream; +import javax.swing.ButtonGroup; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JDesktopPane; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.UIManager; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalTheme; +import javax.swing.plaf.metal.OceanTheme; /** - * This is the main container frame for the Metalworks demo app - * - * @author Steve Wilson - */ -public class MetalworksFrame extends JFrame { + * This is the main container frame for the Metalworks demo app + * + * @author Steve Wilson + * @author Alexander Kouznetsov + */ +@SuppressWarnings("serial") +public final class MetalworksFrame extends JFrame { JMenuBar menuBar; JDesktopPane desktop; JInternalFrame toolPalette; JCheckBoxMenuItem showToolPaletteMenuItem; - - static final Integer DOCLAYER = new Integer(5); - static final Integer TOOLLAYER = new Integer(6); - static final Integer HELPLAYER = new Integer(7); - - static final String ABOUTMSG = "Metalworks \n \nAn application written to show off the Java Look & Feel. \n \nWritten by the JavaSoft Look & Feel Team \n Michael Albers\n Tom Santos\n Jeff Shapiro\n Steve Wilson"; - + static final Integer DOCLAYER = 5; + static final Integer TOOLLAYER = 6; + static final Integer HELPLAYER = 7; + static final String ABOUTMSG = "Metalworks \n \nAn application written to " + + "show off the Java Look & Feel. \n \nWritten by the JavaSoft " + + "Look & Feel Team \n Michael Albers\n Tom Santos\n " + + "Jeff Shapiro\n Steve Wilson"; public MetalworksFrame() { super("Metalworks"); final int inset = 50; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); - setBounds ( inset, inset, screenSize.width - inset*2, screenSize.height - inset*2 ); + setBounds(inset, inset, screenSize.width - inset * 2, screenSize.height - inset + * 2); buildContent(); buildMenus(); this.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - quit(); - }}); - UIManager.addPropertyChangeListener(new UISwitchListener((JComponent)getRootPane())); + + @Override + public void windowClosing(WindowEvent e) { + quit(); + } + }); + UIManager.addPropertyChangeListener(new UISwitchListener( + (JComponent) getRootPane())); } protected void buildMenus() { @@ -87,20 +107,23 @@ public class MetalworksFrame extends JFrame { // load a theme from a text file MetalTheme myTheme = null; try { - InputStream istream = getClass().getResourceAsStream("/resources/MyTheme.theme"); - myTheme = new PropertiesMetalTheme(istream); - } catch (NullPointerException e) {System.out.println(e);} + InputStream istream = getClass().getResourceAsStream( + "/resources/MyTheme.theme"); + myTheme = new PropertiesMetalTheme(istream); + } catch (NullPointerException e) { + System.out.println(e); + } // build an array of themes MetalTheme[] themes = { new OceanTheme(), - new DefaultMetalTheme(), - new GreenMetalTheme(), - new AquaMetalTheme(), - new KhakiMetalTheme(), - new DemoMetalTheme(), - new ContrastMetalTheme(), - new BigContrastMetalTheme(), - myTheme }; + new DefaultMetalTheme(), + new GreenMetalTheme(), + new AquaMetalTheme(), + new KhakiMetalTheme(), + new DemoMetalTheme(), + new ContrastMetalTheme(), + new BigContrastMetalTheme(), + myTheme }; // put the themes in a menu JMenu themeMenu = new MetalThemeMenu("Theme", themes); @@ -121,19 +144,25 @@ public class MetalworksFrame extends JFrame { JMenuItem quit = new JMenuItem("Quit"); newWin.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - newDocument(); - }}); + + public void actionPerformed(ActionEvent e) { + newDocument(); + } + }); open.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - openDocument(); - }}); + + public void actionPerformed(ActionEvent e) { + openDocument(); + } + }); quit.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - quit(); - }}); + + public void actionPerformed(ActionEvent e) { + quit(); + } + }); file.add(newWin); file.add(open); @@ -156,9 +185,11 @@ public class MetalworksFrame extends JFrame { paste.setEnabled(false); prefs.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - openPrefsWindow(); - }}); + + public void actionPerformed(ActionEvent e) { + openPrefsWindow(); + } + }); edit.add(undo); edit.addSeparator(); @@ -178,16 +209,18 @@ public class MetalworksFrame extends JFrame { outBox.setEnabled(false); inBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - openInBox(); - }}); + + public void actionPerformed(ActionEvent e) { + openInBox(); + } + }); views.add(inBox); views.add(outBox); return views; } - protected JMenu buildSpeedMenu() { + protected JMenu buildSpeedMenu() { JMenu speed = new JMenu("Drag"); JRadioButtonMenuItem live = new JRadioButtonMenuItem("Live"); @@ -203,28 +236,37 @@ public class MetalworksFrame extends JFrame { live.setSelected(true); - slow.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e){ - // for right now I'm saying if you set the mode - // to something other than a specified mode - // it will revert to the old way - // This is mostly for comparison's sake - desktop.setDragMode(-1);}}); + slow.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + // for right now I'm saying if you set the mode + // to something other than a specified mode + // it will revert to the old way + // This is mostly for comparison's sake + desktop.setDragMode(-1); + } + }); + + live.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + desktop.setDragMode(JDesktopPane.LIVE_DRAG_MODE); + } + }); - live.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e){ - desktop.setDragMode(JDesktopPane.LIVE_DRAG_MODE);}}); + outline.addActionListener(new ActionListener() { - outline.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e){ - desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);}}); + public void actionPerformed(ActionEvent e) { + desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); + } + }); speed.add(live); speed.add(outline); speed.add(slow); return speed; - } + } protected JMenu buildHelpMenu() { JMenu help = new JMenu("Help"); @@ -232,15 +274,18 @@ public class MetalworksFrame extends JFrame { JMenuItem openHelp = new JMenuItem("Open Help Window"); about.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { showAboutBox(); } }); openHelp.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - openHelpWindow(); - }}); + + public void actionPerformed(ActionEvent e) { + openHelpWindow(); + } + }); help.add(about); help.add(openHelp); @@ -263,7 +308,8 @@ public class MetalworksFrame extends JFrame { try { doc.setVisible(true); doc.setSelected(true); - } catch (java.beans.PropertyVetoException e2) {} + } catch (java.beans.PropertyVetoException e2) { + } } public void openDocument() { @@ -277,7 +323,8 @@ public class MetalworksFrame extends JFrame { try { help.setVisible(true); help.setSelected(true); - } catch (java.beans.PropertyVetoException e2) {} + } catch (java.beans.PropertyVetoException e2) { + } } public void showAboutBox() { @@ -286,7 +333,7 @@ public class MetalworksFrame extends JFrame { public void openPrefsWindow() { MetalworksPrefs dialog = new MetalworksPrefs(this); - dialog.show(); + dialog.setVisible(true); } @@ -296,6 +343,7 @@ public class MetalworksFrame extends JFrame { try { doc.setVisible(true); doc.setSelected(true); - } catch (java.beans.PropertyVetoException e2) {} + } catch (java.beans.PropertyVetoException e2) { + } } } diff --git a/src/share/demo/jfc/Metalworks/MetalworksHelp.java b/src/share/demo/jfc/Metalworks/MetalworksHelp.java index c913acdaec971413c68f55c32f2a9b36faaf547f..f9dd1429f0e27e50185e18aefc9e3811be5a81ad 100644 --- a/src/share/demo/jfc/Metalworks/MetalworksHelp.java +++ b/src/share/demo/jfc/Metalworks/MetalworksHelp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import javax.swing.*; import java.awt.*; @@ -40,26 +38,31 @@ import java.io.*; import javax.swing.text.*; import javax.swing.event.*; -/* + +/** * @author Steve Wilson + * @author Alexander Kouznetsov */ +@SuppressWarnings("serial") public class MetalworksHelp extends JInternalFrame { public MetalworksHelp() { super("Help", true, true, true, true); - setFrameIcon( (Icon)UIManager.get("Tree.openIcon")); // PENDING(steve) need more general palce to get this icon - setBounds( 200, 25, 400, 400); + setFrameIcon((Icon) UIManager.get("Tree.openIcon")); // PENDING(steve) need more general place to get this icon + setBounds(200, 25, 400, 400); HtmlPane html = new HtmlPane(); setContentPane(html); } - } +@SuppressWarnings("serial") class HtmlPane extends JScrollPane implements HyperlinkListener { + JEditorPane html; + @SuppressWarnings("LeakingThisInConstructor") public HtmlPane() { try { URL url = getClass().getResource("/resources/HelpFiles/toc.html"); @@ -67,7 +70,7 @@ class HtmlPane extends JScrollPane implements HyperlinkListener { html.setEditable(false); html.addHyperlinkListener(this); html.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, - Boolean.TRUE); + Boolean.TRUE); JViewport vp = getViewport(); vp.add(html); } catch (MalformedURLException e) { @@ -106,6 +109,7 @@ class HtmlPane extends JScrollPane implements HyperlinkListener { SwingUtilities.invokeLater(new PageLoader(u, c)); } + /** * temporary class that loads synchronously (although * later than the request so that a cursor change @@ -142,9 +146,7 @@ class HtmlPane extends JScrollPane implements HyperlinkListener { } } } - URL url; Cursor cursor; } - } diff --git a/src/share/demo/jfc/Metalworks/MetalworksInBox.java b/src/share/demo/jfc/Metalworks/MetalworksInBox.java index 39c904ea8fae8d0f057f8497eaf4bf754e33c799..48e71ca5239a5d4916bad90ea30795c7a1ae6585 100644 --- a/src/share/demo/jfc/Metalworks/MetalworksInBox.java +++ b/src/share/demo/jfc/Metalworks/MetalworksInBox.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,22 +29,20 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.*; -import java.awt.event.*; -import java.util.*; -import javax.swing.*; -import javax.swing.border.*; -import javax.swing.tree.*; +import javax.swing.JInternalFrame; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.tree.DefaultMutableTreeNode; /** - * This is a subclass of JInternalFrame which displays a tree. - * - * @author Steve Wilson - */ + * This is a subclass of JInternalFrame which displays a tree. + * + * @author Steve Wilson + * @author Alexander Kouznetsov + */ +@SuppressWarnings("serial") public class MetalworksInBox extends JInternalFrame { public MetalworksInBox() { @@ -57,49 +55,47 @@ public class MetalworksInBox extends JInternalFrame { DefaultMutableTreeNode top = new DefaultMutableTreeNode("Mail Boxes"); - top.add( unread = new DefaultMutableTreeNode("Unread Mail") ); - top.add( personal = new DefaultMutableTreeNode("Personal") ); - top.add( business = new DefaultMutableTreeNode("Business") ); - top.add( spam = new DefaultMutableTreeNode("Spam") ); - - unread.add( new DefaultMutableTreeNode("Buy Stuff Now") ); - unread.add( new DefaultMutableTreeNode("Read Me Now") ); - unread.add( new DefaultMutableTreeNode("Hot Offer") ); - unread.add( new DefaultMutableTreeNode("Re: Re: Thank You") ); - unread.add( new DefaultMutableTreeNode("Fwd: Good Joke") ); - - personal.add( new DefaultMutableTreeNode("Hi") ); - personal.add( new DefaultMutableTreeNode("Good to hear from you") ); - personal.add( new DefaultMutableTreeNode("Re: Thank You") ); - - business.add( new DefaultMutableTreeNode("Thanks for your order") ); - business.add( new DefaultMutableTreeNode("Price Quote") ); - business.add( new DefaultMutableTreeNode("Here is the invoice") ); - business.add( new DefaultMutableTreeNode("Project Metal: delivered on time") ); - business.add( new DefaultMutableTreeNode("Your salary raise approved") ); - - spam.add( new DefaultMutableTreeNode("Buy Now") ); - spam.add( new DefaultMutableTreeNode("Make $$$ Now") ); - spam.add( new DefaultMutableTreeNode("HOT HOT HOT") ); - spam.add( new DefaultMutableTreeNode("Buy Now") ); - spam.add( new DefaultMutableTreeNode("Don't Miss This") ); - spam.add( new DefaultMutableTreeNode("Opportunity in Precious Metals") ); - spam.add( new DefaultMutableTreeNode("Buy Now") ); - spam.add( new DefaultMutableTreeNode("Last Chance") ); - spam.add( new DefaultMutableTreeNode("Buy Now") ); - spam.add( new DefaultMutableTreeNode("Make $$$ Now") ); - spam.add( new DefaultMutableTreeNode("To Hot To Handle") ); - spam.add( new DefaultMutableTreeNode("I'm waiting for your call") ); + top.add(unread = new DefaultMutableTreeNode("Unread Mail")); + top.add(personal = new DefaultMutableTreeNode("Personal")); + top.add(business = new DefaultMutableTreeNode("Business")); + top.add(spam = new DefaultMutableTreeNode("Spam")); + + unread.add(new DefaultMutableTreeNode("Buy Stuff Now")); + unread.add(new DefaultMutableTreeNode("Read Me Now")); + unread.add(new DefaultMutableTreeNode("Hot Offer")); + unread.add(new DefaultMutableTreeNode("Re: Re: Thank You")); + unread.add(new DefaultMutableTreeNode("Fwd: Good Joke")); + + personal.add(new DefaultMutableTreeNode("Hi")); + personal.add(new DefaultMutableTreeNode("Good to hear from you")); + personal.add(new DefaultMutableTreeNode("Re: Thank You")); + + business.add(new DefaultMutableTreeNode("Thanks for your order")); + business.add(new DefaultMutableTreeNode("Price Quote")); + business.add(new DefaultMutableTreeNode("Here is the invoice")); + business.add(new DefaultMutableTreeNode( + "Project Metal: delivered on time")); + business.add(new DefaultMutableTreeNode("Your salary raise approved")); + + spam.add(new DefaultMutableTreeNode("Buy Now")); + spam.add(new DefaultMutableTreeNode("Make $$$ Now")); + spam.add(new DefaultMutableTreeNode("HOT HOT HOT")); + spam.add(new DefaultMutableTreeNode("Buy Now")); + spam.add(new DefaultMutableTreeNode("Don't Miss This")); + spam.add(new DefaultMutableTreeNode("Opportunity in Precious Metals")); + spam.add(new DefaultMutableTreeNode("Buy Now")); + spam.add(new DefaultMutableTreeNode("Last Chance")); + spam.add(new DefaultMutableTreeNode("Buy Now")); + spam.add(new DefaultMutableTreeNode("Make $$$ Now")); + spam.add(new DefaultMutableTreeNode("To Hot To Handle")); + spam.add(new DefaultMutableTreeNode("I'm waiting for your call")); JTree tree = new JTree(top); JScrollPane treeScroller = new JScrollPane(tree); treeScroller.setBackground(tree.getBackground()); setContentPane(treeScroller); - setSize( 325, 200); - setLocation( 75, 75); + setSize(325, 200); + setLocation(75, 75); } - - - } diff --git a/src/share/demo/jfc/Metalworks/MetalworksPrefs.java b/src/share/demo/jfc/Metalworks/MetalworksPrefs.java index 3282cb10fd423fd8de00f59b7158b2eeae4301d4..fa88a88f5700d88349df2c60affa09f31a9e1ce2 100644 --- a/src/share/demo/jfc/Metalworks/MetalworksPrefs.java +++ b/src/share/demo/jfc/Metalworks/MetalworksPrefs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,50 +29,70 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.*; -import java.awt.event.*; -import java.beans.*; -import javax.swing.*; -import javax.swing.border.*; -import javax.swing.plaf.metal.*; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.Insets; +import java.awt.LayoutManager; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTabbedPane; +import javax.swing.UIManager; +import javax.swing.border.TitledBorder; /** - * This is dialog which allows users to choose preferences - * - * @author Steve Wilson - */ -public class MetalworksPrefs extends JDialog { + * This is dialog which allows users to choose preferences + * + * @author Steve Wilson + * @author Alexander Kouznetsov + */ +@SuppressWarnings("serial") +public final class MetalworksPrefs extends JDialog { public MetalworksPrefs(JFrame f) { super(f, "Preferences", true); JPanel container = new JPanel(); - container.setLayout( new BorderLayout() ); + container.setLayout(new BorderLayout()); JTabbedPane tabs = new JTabbedPane(); JPanel filters = buildFilterPanel(); JPanel conn = buildConnectingPanel(); - tabs.addTab( "Filters", null, filters ); - tabs.addTab( "Connecting", null, conn ); + tabs.addTab("Filters", null, filters); + tabs.addTab("Connecting", null, conn); JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout ( new FlowLayout(FlowLayout.RIGHT) ); + buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - CancelPressed(); - }}); - buttonPanel.add( cancel ); + + public void actionPerformed(ActionEvent e) { + CancelPressed(); + } + }); + buttonPanel.add(cancel); JButton ok = new JButton("OK"); ok.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - OKPressed(); - }}); - buttonPanel.add( ok ); + + public void actionPerformed(ActionEvent e) { + OKPressed(); + } + }); + buttonPanel.add(ok); getRootPane().setDefaultButton(ok); container.add(tabs, BorderLayout.CENTER); @@ -85,12 +105,12 @@ public class MetalworksPrefs extends JDialog { public JPanel buildFilterPanel() { JPanel filters = new JPanel(); - filters.setLayout( new GridLayout(1, 0) ); + filters.setLayout(new GridLayout(1, 0)); JPanel spamPanel = new JPanel(); spamPanel.setLayout(new ColumnLayout()); - spamPanel.setBorder( new TitledBorder("Spam") ); + spamPanel.setBorder(new TitledBorder("Spam")); ButtonGroup spamGroup = new ButtonGroup(); JRadioButton file = new JRadioButton("File in Spam Folder"); JRadioButton delete = new JRadioButton("Auto Delete"); @@ -106,7 +126,7 @@ public class MetalworksPrefs extends JDialog { JPanel autoRespond = new JPanel(); autoRespond.setLayout(new ColumnLayout()); - autoRespond.setBorder( new TitledBorder("Auto Response") ); + autoRespond.setBorder(new TitledBorder("Auto Response")); ButtonGroup respondGroup = new ButtonGroup(); JRadioButton none = new JRadioButton("None"); @@ -129,10 +149,10 @@ public class MetalworksPrefs extends JDialog { public JPanel buildConnectingPanel() { JPanel connectPanel = new JPanel(); - connectPanel.setLayout( new ColumnLayout() ); + connectPanel.setLayout(new ColumnLayout()); JPanel protoPanel = new JPanel(); - JLabel protoLabel = new JLabel ("Protocol"); + JLabel protoLabel = new JLabel("Protocol"); JComboBox protocol = new JComboBox(); protocol.addItem("SMTP"); protocol.addItem("IMAP"); @@ -141,7 +161,7 @@ public class MetalworksPrefs extends JDialog { protoPanel.add(protocol); JPanel attachmentPanel = new JPanel(); - JLabel attachmentLabel = new JLabel ("Attachments"); + JLabel attachmentLabel = new JLabel("Attachments"); JComboBox attach = new JComboBox(); attach.addItem("Download Always"); attach.addItem("Ask size > 1 Meg"); @@ -152,7 +172,7 @@ public class MetalworksPrefs extends JDialog { JCheckBox autoConn = new JCheckBox("Auto Connect"); JCheckBox compress = new JCheckBox("Use Compression"); - autoConn.setSelected( true ); + autoConn.setSelected(true); connectPanel.add(protoPanel); connectPanel.add(attachmentPanel); @@ -161,18 +181,16 @@ public class MetalworksPrefs extends JDialog { return connectPanel; } - - protected void centerDialog() { Dimension screenSize = this.getToolkit().getScreenSize(); Dimension size = this.getSize(); - screenSize.height = screenSize.height/2; - screenSize.width = screenSize.width/2; - size.height = size.height/2; - size.width = size.width/2; + screenSize.height = screenSize.height / 2; + screenSize.width = screenSize.width / 2; + size.height = size.height / 2; + size.width = size.width / 2; int y = screenSize.height - size.height; int x = screenSize.width - size.width; - this.setLocation(x,y); + this.setLocation(x, y); } public void CancelPressed() { @@ -182,52 +200,54 @@ public class MetalworksPrefs extends JDialog { public void OKPressed() { this.setVisible(false); } - } + class ColumnLayout implements LayoutManager { - int xInset = 5; - int yInset = 5; - int yGap = 2; - - public void addLayoutComponent(String s, Component c) {} - - public void layoutContainer(Container c) { - Insets insets = c.getInsets(); - int height = yInset + insets.top; - - Component[] children = c.getComponents(); - Dimension compSize = null; - for (int i = 0; i < children.length; i++) { - compSize = children[i].getPreferredSize(); - children[i].setSize(compSize.width, compSize.height); - children[i].setLocation( xInset + insets.left, height); - height += compSize.height + yGap; - } - - } - - public Dimension minimumLayoutSize(Container c) { - Insets insets = c.getInsets(); - int height = yInset + insets.top; - int width = 0 + insets.left + insets.right; - - Component[] children = c.getComponents(); - Dimension compSize = null; - for (int i = 0; i < children.length; i++) { - compSize = children[i].getPreferredSize(); - height += compSize.height + yGap; - width = Math.max(width, compSize.width + insets.left + insets.right + xInset*2); - } - height += insets.bottom; - return new Dimension( width, height); - } - - public Dimension preferredLayoutSize(Container c) { - return minimumLayoutSize(c); - } - - public void removeLayoutComponent(Component c) {} + int xInset = 5; + int yInset = 5; + int yGap = 2; + public void addLayoutComponent(String s, Component c) { + } + + public void layoutContainer(Container c) { + Insets insets = c.getInsets(); + int height = yInset + insets.top; + + Component[] children = c.getComponents(); + Dimension compSize = null; + for (Component child : children) { + compSize = child.getPreferredSize(); + child.setSize(compSize.width, compSize.height); + child.setLocation(xInset + insets.left, height); + height += compSize.height + yGap; + } + + } + + public Dimension minimumLayoutSize(Container c) { + Insets insets = c.getInsets(); + int height = yInset + insets.top; + int width = 0 + insets.left + insets.right; + + Component[] children = c.getComponents(); + Dimension compSize = null; + for (Component child : children) { + compSize = child.getPreferredSize(); + height += compSize.height + yGap; + width = Math.max(width, compSize.width + insets.left + insets.right + xInset + * 2); + } + height += insets.bottom; + return new Dimension(width, height); + } + + public Dimension preferredLayoutSize(Container c) { + return minimumLayoutSize(c); + } + + public void removeLayoutComponent(Component c) { + } } diff --git a/src/share/demo/jfc/Metalworks/PropertiesMetalTheme.java b/src/share/demo/jfc/Metalworks/PropertiesMetalTheme.java index 9f944a3460ff0c26be2cb66b6bdae9dd8d2ab5e2..ec729f16aba4d2610371906456fe8b31637b4031 100644 --- a/src/share/demo/jfc/Metalworks/PropertiesMetalTheme.java +++ b/src/share/demo/jfc/Metalworks/PropertiesMetalTheme.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,17 +29,15 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import java.util.StringTokenizer; + +import javax.swing.plaf.ColorUIResource; +import javax.swing.plaf.metal.DefaultMetalTheme; -import javax.swing.plaf.*; -import javax.swing.plaf.metal.*; -import javax.swing.*; -import javax.swing.border.*; -import java.awt.*; -import java.io.*; -import java.util.*; /** * This class allows you to load a theme from a file. @@ -57,36 +55,33 @@ import java.util.*; * but it could easily be extended to load fonts - or even icons. * * @author Steve Wilson + * @author Alexander Kouznetsov */ public class PropertiesMetalTheme extends DefaultMetalTheme { private String name = "Custom Theme"; - private ColorUIResource primary1; private ColorUIResource primary2; private ColorUIResource primary3; - private ColorUIResource secondary1; private ColorUIResource secondary2; private ColorUIResource secondary3; - private ColorUIResource black; private ColorUIResource white; - /** - * pass an inputstream pointing to a properties file. - * Colors will be initialized to be the same as the DefaultMetalTheme, - * and then any colors provided in the properties file will override that. - */ - public PropertiesMetalTheme( InputStream stream ) { + * pass an inputstream pointing to a properties file. + * Colors will be initialized to be the same as the DefaultMetalTheme, + * and then any colors provided in the properties file will override that. + */ + public PropertiesMetalTheme(InputStream stream) { initColors(); loadProperties(stream); } /** - * Initialize all colors to be the same as the DefaultMetalTheme. - */ + * Initialize all colors to be the same as the DefaultMetalTheme. + */ private void initColors() { primary1 = super.getPrimary1(); primary2 = super.getPrimary2(); @@ -101,9 +96,9 @@ public class PropertiesMetalTheme extends DefaultMetalTheme { } /** - * Load the theme name and colors from the properties file - * Items not defined in the properties file are ignored - */ + * Load the theme name and colors from the properties file + * Items not defined in the properties file are ignored + */ private void loadProperties(InputStream stream) { Properties prop = new Properties(); try { @@ -120,7 +115,7 @@ public class PropertiesMetalTheme extends DefaultMetalTheme { Object colorString = null; colorString = prop.get("primary1"); - if (colorString != null){ + if (colorString != null) { primary1 = parseColor(colorString.toString()); } @@ -161,22 +156,54 @@ public class PropertiesMetalTheme extends DefaultMetalTheme { } - public String getName() { return name; } + @Override + public String getName() { + return name; + } + + @Override + protected ColorUIResource getPrimary1() { + return primary1; + } + + @Override + protected ColorUIResource getPrimary2() { + return primary2; + } + + @Override + protected ColorUIResource getPrimary3() { + return primary3; + } - protected ColorUIResource getPrimary1() { return primary1; } - protected ColorUIResource getPrimary2() { return primary2; } - protected ColorUIResource getPrimary3() { return primary3; } + @Override + protected ColorUIResource getSecondary1() { + return secondary1; + } - protected ColorUIResource getSecondary1() { return secondary1; } - protected ColorUIResource getSecondary2() { return secondary2; } - protected ColorUIResource getSecondary3() { return secondary3; } + @Override + protected ColorUIResource getSecondary2() { + return secondary2; + } - protected ColorUIResource getBlack() { return black; } - protected ColorUIResource getWhite() { return white; } + @Override + protected ColorUIResource getSecondary3() { + return secondary3; + } + + @Override + protected ColorUIResource getBlack() { + return black; + } + + @Override + protected ColorUIResource getWhite() { + return white; + } /** - * parse a comma delimited list of 3 strings into a Color - */ + * parse a comma delimited list of 3 strings into a Color + */ private ColorUIResource parseColor(String s) { int red = 0; int green = 0; diff --git a/src/share/demo/jfc/Metalworks/UISwitchListener.java b/src/share/demo/jfc/Metalworks/UISwitchListener.java index a9023df9d90949e7eab0706ceab740021d402eec..d75fb3f4b6a36ec72072ae757eb908067d0fff53 100644 --- a/src/share/demo/jfc/Metalworks/UISwitchListener.java +++ b/src/share/demo/jfc/Metalworks/UISwitchListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,22 +29,21 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.*; -import java.beans.*; -import java.awt.event.*; -import javax.swing.*; -import javax.swing.event.*; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import javax.swing.JComponent; +import javax.swing.SwingUtilities; /** - * This class listens for UISwitches, and updates a given component. - * - * @author Steve Wilson - */ + * This class listens for UISwitches, and updates a given component. + * + * @author Steve Wilson + * @author Alexander Kouznetsov + */ public class UISwitchListener implements PropertyChangeListener { + JComponent componentToSwitch; public UISwitchListener(JComponent c) { diff --git a/src/share/demo/jfc/Metalworks/resources/HelpFiles/credits.html b/src/share/demo/jfc/Metalworks/resources/HelpFiles/credits.html index 9965ac1bbe9590ae5fbdb6eec3b39da3ad668009..3625742baf96097d89f2edd3ed3c4da36d1200ee 100644 --- a/src/share/demo/jfc/Metalworks/resources/HelpFiles/credits.html +++ b/src/share/demo/jfc/Metalworks/resources/HelpFiles/credits.html @@ -5,9 +5,9 @@ -

Java L&F Credits

+

Java L&F Credits

-

The Java L&F Engineering team:

+

The Java L&F Engineering team:

  • Mike Albers @@ -22,12 +22,12 @@
  • Harry Vertelney
-

The Java L&F Designer:

+

The Java L&F Designer:

  • Chris Ryan
-

Back +

BackBack diff --git a/src/share/demo/jfc/Metalworks/resources/HelpFiles/metal.html b/src/share/demo/jfc/Metalworks/resources/HelpFiles/metal.html index 65fb5b3004a48837d1d1ccb0a0ff02a2302a8b38..6a42b1539efc8d3256b7fb4eec67753e77cc828e 100644 --- a/src/share/demo/jfc/Metalworks/resources/HelpFiles/metal.html +++ b/src/share/demo/jfc/Metalworks/resources/HelpFiles/metal.html @@ -7,11 +7,11 @@

-About the Java L&F

-The Java Look and Feel is a cross-platform look & feel being provided by Javasoft. -Here is some information about the Java L&F you might find useful. +About the Java L&F +The Java Look and Feel is a cross-platform look & feel being provided by Javasoft. +Here is some information about the Java L&F you might find useful. -

The Java L&F implements all of the basic Swing functionality, +

The Java L&F implements all of the basic Swing functionality, but also extends it in several areas including:

  • @@ -27,27 +27,27 @@ Toolbars
  • Trees
-

+

Themes

-

One of the first things we learned while implementing the Java L&F +

One of the first things we learned while implementing the Java L&F was than many developers feel very strongly about how colors are used in their software. To help accommodate this we created a Theme mechanism which allows a developer to easily specify the default colors, fonts and -icons used by the L&F.

+icons used by the L&F.

The theme mechanism is designed to allow developers to create their own themes. For an example of this, see the themes -which are included with Metalworks. Note, like all of the L&F packages, +which are included with Metalworks. Note, like all of the L&F packages, the metal package is not yet frozen and the theme mechanism may change as we get developer feedback on how to improve it.

Sliders

-

There are several areas where the Java L&F introduces some optional +

There are several areas where the Java L&F introduces some optional "value-added" features above the base line capabilities of swing.  One is the option of Filled Sliders. These are ideal for things like -volume controls. To access the Java L&F "value-added" features you +volume controls. To access the Java L&F "value-added" features you pass in a token to the component's putClientProperty method. Here is an example:

@@ -60,12 +60,12 @@ slider.putClientProperty("JSlider.isFilled",

Note that if a UI such as Windows or Motif encounters a property such as JSlider.fill which is does not understand that property will be ignored.  Thus you don't have to worry about problems which could arise if you switch -to a different L&F.

+to a different L&F.

ToolBars

Many popular applications support "roll-over" effects on buttons in toolbars. -The Java L&F provides an easy way to do this. Here is a code snippit:

+The Java L&F provides an easy way to do this. Here is a code snippit:

 JToolBar toolbar = new JToolBar();
@@ -82,7 +82,7 @@ is a nice effect for many applications.

Trees

-

Java L&F allows you to control the line style used in the JTree component. Here are some code snippits:

+

Java L&F allows you to control the line style used in the JTree component. Here are some code snippits:

 JTree myTree = new JTree();
@@ -101,6 +101,6 @@ myTree.putClientProperty("JTree.lineStyle",
                          "Horizontal"); 
 
-

Back +

BackBack diff --git a/src/share/demo/jfc/Metalworks/resources/HelpFiles/metalworks.html b/src/share/demo/jfc/Metalworks/resources/HelpFiles/metalworks.html index 8ad5f25d5afb92d3cde63656ba85032a13d19e46..df9a440b27392367e2520976ce227cb99d4b41bf 100644 --- a/src/share/demo/jfc/Metalworks/resources/HelpFiles/metalworks.html +++ b/src/share/demo/jfc/Metalworks/resources/HelpFiles/metalworks.html @@ -8,7 +8,7 @@

About Metalworks

-Metalworks is a simple Swing-based simulated email application. It shows off several features of Swing including: JInternalFrame, JTabbedPane, JFileChooser, JEditorPane and JRadioButtonMenuItem. It is optimized to work with the Java Look & Feel and shows use of several Java L&F specific features including themes. +Metalworks is a simple Swing-based simulated email application. It shows off several features of Swing including: JInternalFrame, JTabbedPane, JFileChooser, JEditorPane and JRadioButtonMenuItem. It is optimized to work with the Java Look & Feel and shows use of several Java L&F specific features including themes.

Metalworks Features

The functionality of the Metalworks demo is minimal, and many controls are non-functional. They are only intended to show how to construct the UI for such interfaces. Things that do work in the Metalworks demo include: @@ -28,6 +28,6 @@ The functionality of the Metalworks demo is minimal, and many controls are non-f   -

Back +

BackBack diff --git a/src/share/demo/jfc/Metalworks/resources/HelpFiles/swing.html b/src/share/demo/jfc/Metalworks/resources/HelpFiles/swing.html index 14bf84c84c56234128143675de264f934963e732..22e60bdc9d1c1e96731a45412a9af1edd00bd7fe 100644 --- a/src/share/demo/jfc/Metalworks/resources/HelpFiles/swing.html +++ b/src/share/demo/jfc/Metalworks/resources/HelpFiles/swing.html @@ -5,7 +5,7 @@ -

About Swing

+

About SwingAbout Swing

 

@@ -17,6 +17,6 @@ will give users the ability to switch the look and feel of an application without restarting it and without the developer having to subclass the entire component set.

-

Back +

BackBack diff --git a/src/share/demo/jfc/Metalworks/resources/HelpFiles/toc.html b/src/share/demo/jfc/Metalworks/resources/HelpFiles/toc.html index 6a9c4a72a58cc25c0bc5190ca74d893681d6f75e..ab36b48592523a4f1e108d3b4d903aa44330d218 100644 --- a/src/share/demo/jfc/Metalworks/resources/HelpFiles/toc.html +++ b/src/share/demo/jfc/Metalworks/resources/HelpFiles/toc.html @@ -5,7 +5,7 @@ -

Metalworks Help

+

HelpMetalworks Help

Welcome to the Metalworks Help files. These are actually HTML files which you are viewing with the Swing JEditorPane component. Pretty cool, eh? Were @@ -18,7 +18,7 @@ possible. Click on the links below for more information.

diff --git a/src/share/demo/jfc/Notepad/ElementTreePanel.java b/src/share/demo/jfc/Notepad/ElementTreePanel.java index 34915782258bdd41c42bb84040f21358da21ce75..0a208c926936d6fe0872da90364c0d02bbe44372 100644 --- a/src/share/demo/jfc/Notepad/ElementTreePanel.java +++ b/src/share/demo/jfc/Notepad/ElementTreePanel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2000, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,17 +29,36 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.text.*; -import javax.swing.tree.*; -import javax.swing.undo.*; -import java.awt.*; -import java.beans.*; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Font; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; import java.util.*; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.SwingConstants; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.text.AttributeSet; +import javax.swing.text.Document; +import javax.swing.text.Element; +import javax.swing.text.JTextComponent; +import javax.swing.text.StyleConstants; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreeNode; +import javax.swing.tree.TreePath; + /** * Displays a tree showing all the elements in a text Document. Selecting @@ -49,16 +68,20 @@ import java.util.*; * * @author Scott Violet */ -public class ElementTreePanel extends JPanel implements CaretListener, DocumentListener, PropertyChangeListener, TreeSelectionListener { +@SuppressWarnings("serial") +public class ElementTreePanel extends JPanel implements CaretListener, + DocumentListener, PropertyChangeListener, TreeSelectionListener { + /** Tree showing the documents element structure. */ - protected JTree tree; + protected JTree tree; /** Text component showing elemenst for. */ - protected JTextComponent editor; + protected JTextComponent editor; /** Model for the tree. */ - protected ElementTreeModel treeModel; + protected ElementTreeModel treeModel; /** Set to true when updatin the selection. */ - protected boolean updatingSelection; + protected boolean updatingSelection; + @SuppressWarnings("LeakingThisInConstructor") public ElementTreePanel(JTextComponent editor) { this.editor = editor; @@ -67,25 +90,28 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL // Create the tree. treeModel = new ElementTreeModel(document); tree = new JTree(treeModel) { + + @Override public String convertValueToText(Object value, boolean selected, - boolean expanded, boolean leaf, - int row, boolean hasFocus) { + boolean expanded, boolean leaf, + int row, boolean hasFocus) { // Should only happen for the root - if(!(value instanceof Element)) + if (!(value instanceof Element)) { return value.toString(); + } - Element e = (Element)value; - AttributeSet as = e.getAttributes().copyAttributes(); - String asString; + Element e = (Element) value; + AttributeSet as = e.getAttributes().copyAttributes(); + String asString; - if(as != null) { - StringBuffer retBuffer = new StringBuffer("["); - Enumeration names = as.getAttributeNames(); + if (as != null) { + StringBuilder retBuffer = new StringBuilder("["); + Enumeration names = as.getAttributeNames(); - while(names.hasMoreElements()) { - Object nextName = names.nextElement(); + while (names.hasMoreElements()) { + Object nextName = names.nextElement(); - if(nextName != StyleConstants.ResolveAttribute) { + if (nextName != StyleConstants.ResolveAttribute) { retBuffer.append(" "); retBuffer.append(nextName); retBuffer.append("="); @@ -94,16 +120,16 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL } retBuffer.append(" ]"); asString = retBuffer.toString(); - } - else + } else { asString = "[ ]"; + } - if(e.isLeaf()) - return e.getName() + " [" + e.getStartOffset() + - ", " + e.getEndOffset() +"] Attributes: " + asString; - return e.getName() + " [" + e.getStartOffset() + - ", " + e.getEndOffset() + "] Attributes: " + - asString; + if (e.isLeaf()) { + return e.getName() + " [" + e.getStartOffset() + ", " + e. + getEndOffset() + "] Attributes: " + asString; + } + return e.getName() + " [" + e.getStartOffset() + ", " + e. + getEndOffset() + "] Attributes: " + asString; } }; tree.addTreeSelectionListener(this); @@ -117,10 +143,13 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL // This is a temporary workaround, increase the needed size by 15, // hoping that will be enough. tree.setCellRenderer(new DefaultTreeCellRenderer() { + + @Override public Dimension getPreferredSize() { Dimension retValue = super.getPreferredSize(); - if(retValue != null) + if (retValue != null) { retValue.width += 15; + } return retValue; } }); @@ -139,7 +168,8 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL add(new JScrollPane(tree), BorderLayout.CENTER); // Add a label above tree to describe what is being shown - JLabel label = new JLabel("Elements that make up the current document", SwingConstants.CENTER); + JLabel label = new JLabel("Elements that make up the current document", + SwingConstants.CENTER); label.setFont(new Font("Dialog", Font.BOLD, 14)); add(label, BorderLayout.NORTH); @@ -157,7 +187,7 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL } if (this.editor != null) { - Document oldDoc = this.editor.getDocument(); + Document oldDoc = this.editor.getDocument(); oldDoc.removeDocumentListener(this); this.editor.removePropertyChangeListener(this); @@ -167,9 +197,8 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL if (editor == null) { treeModel = null; tree.setModel(null); - } - else { - Document newDoc = editor.getDocument(); + } else { + Document newDoc = editor.getDocument(); newDoc.addDocumentListener(this); editor.addPropertyChangeListener(this); @@ -180,17 +209,15 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL } // PropertyChangeListener - /** * Invoked when a property changes. We are only interested in when the * Document changes to reset the DocumentListener. */ public void propertyChange(PropertyChangeEvent e) { - if (e.getSource() == getEditor() && - e.getPropertyName().equals("document")) { - JTextComponent editor = getEditor(); - Document oldDoc = (Document)e.getOldValue(); - Document newDoc = (Document)e.getNewValue(); + if (e.getSource() == getEditor() && e.getPropertyName().equals( + "document")) { + Document oldDoc = (Document) e.getOldValue(); + Document newDoc = (Document) e.getNewValue(); // Reset the DocumentListener oldDoc.removeDocumentListener(this); @@ -202,9 +229,7 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL } } - // DocumentListener - /** * Gives notification that there was an insert into the document. The * given range bounds the freshly inserted region. @@ -236,53 +261,50 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL } // CaretListener - /** * Messaged when the selection in the editor has changed. Will update * the selection in the tree. */ public void caretUpdate(CaretEvent e) { - if(!updatingSelection) { - JTextComponent editor = getEditor(); - int selBegin = Math.min(e.getDot(), e.getMark()); - int end = Math.max(e.getDot(), e.getMark()); - Vector paths = new Vector(); - TreeModel model = getTreeModel(); - Object root = model.getRoot(); - int rootCount = model.getChildCount(root); + if (!updatingSelection) { + int selBegin = Math.min(e.getDot(), e.getMark()); + int end = Math.max(e.getDot(), e.getMark()); + List paths = new ArrayList(); + TreeModel model = getTreeModel(); + Object root = model.getRoot(); + int rootCount = model.getChildCount(root); // Build an array of all the paths to all the character elements // in the selection. - for(int counter = 0; counter < rootCount; counter++) { - int start = selBegin; + for (int counter = 0; counter < rootCount; counter++) { + int start = selBegin; - while(start <= end) { - TreePath path = getPathForIndex(start, root, - (Element)model.getChild(root, counter)); - Element charElement = (Element)path. - getLastPathComponent(); + while (start <= end) { + TreePath path = getPathForIndex(start, root, + (Element) model.getChild(root, counter)); + Element charElement = (Element) path.getLastPathComponent(); - paths.addElement(path); - if(start >= charElement.getEndOffset()) + paths.add(path); + if (start >= charElement.getEndOffset()) { start++; - else + } else { start = charElement.getEndOffset(); + } } } // If a path was found, select it (them). - int numPaths = paths.size(); + int numPaths = paths.size(); - if(numPaths > 0) { - TreePath[] pathArray = new TreePath[numPaths]; + if (numPaths > 0) { + TreePath[] pathArray = new TreePath[numPaths]; - paths.copyInto(pathArray); + paths.toArray(pathArray); updatingSelection = true; try { getTree().setSelectionPaths(pathArray); getTree().scrollPathToVisible(pathArray[0]); - } - finally { + } finally { updatingSelection = false; } } @@ -290,27 +312,24 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL } // TreeSelectionListener - /** - * Called whenever the value of the selection changes. - * @param e the event that characterizes the change. - */ + * Called whenever the value of the selection changes. + * @param e the event that characterizes the change. + */ public void valueChanged(TreeSelectionEvent e) { - JTree tree = getTree(); - if(!updatingSelection && tree.getSelectionCount() == 1) { - TreePath selPath = tree.getSelectionPath(); - Object lastPathComponent = selPath.getLastPathComponent(); + if (!updatingSelection && tree.getSelectionCount() == 1) { + TreePath selPath = tree.getSelectionPath(); + Object lastPathComponent = selPath.getLastPathComponent(); - if(!(lastPathComponent instanceof DefaultMutableTreeNode)) { - Element selElement = (Element)lastPathComponent; + if (!(lastPathComponent instanceof DefaultMutableTreeNode)) { + Element selElement = (Element) lastPathComponent; updatingSelection = true; try { getEditor().select(selElement.getStartOffset(), - selElement.getEndOffset()); - } - finally { + selElement.getEndOffset()); + } finally { updatingSelection = false; } } @@ -318,7 +337,6 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL } // Local methods - /** * @return tree showing elements. */ @@ -347,15 +365,14 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL protected void updateTree(DocumentEvent event) { updatingSelection = true; try { - TreeModel model = getTreeModel(); - Object root = model.getRoot(); + TreeModel model = getTreeModel(); + Object root = model.getRoot(); - for(int counter = model.getChildCount(root) - 1; counter >= 0; - counter--) { - updateTree(event, (Element)model.getChild(root, counter)); + for (int counter = model.getChildCount(root) - 1; counter >= 0; + counter--) { + updateTree(event, (Element) model.getChild(root, counter)); } - } - finally { + } finally { updatingSelection = false; } } @@ -372,53 +389,50 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL DocumentEvent.ElementChange ec = event.getChange(element); if (ec != null) { - Element[] removed = ec.getChildrenRemoved(); - Element[] added = ec.getChildrenAdded(); - int startIndex = ec.getIndex(); + Element[] removed = ec.getChildrenRemoved(); + Element[] added = ec.getChildrenAdded(); + int startIndex = ec.getIndex(); // Check for removed. - if(removed != null && removed.length > 0) { - int[] indices = new int[removed.length]; + if (removed != null && removed.length > 0) { + int[] indices = new int[removed.length]; - for(int counter = 0; counter < removed.length; counter++) { + for (int counter = 0; counter < removed.length; counter++) { indices[counter] = startIndex + counter; } - getTreeModel().nodesWereRemoved((TreeNode)element, indices, - removed); + getTreeModel().nodesWereRemoved((TreeNode) element, indices, + removed); } // check for added - if(added != null && added.length > 0) { - int[] indices = new int[added.length]; + if (added != null && added.length > 0) { + int[] indices = new int[added.length]; - for(int counter = 0; counter < added.length; counter++) { + for (int counter = 0; counter < added.length; counter++) { indices[counter] = startIndex + counter; } - getTreeModel().nodesWereInserted((TreeNode)element, indices); + getTreeModel().nodesWereInserted((TreeNode) element, indices); } } - if(!element.isLeaf()) { - int startIndex = element.getElementIndex - (event.getOffset()); - int elementCount = element.getElementCount(); - int endIndex = Math.min(elementCount - 1, - element.getElementIndex - (event.getOffset() + event.getLength())); - - if(startIndex > 0 && startIndex < elementCount && - element.getElement(startIndex).getStartOffset() == - event.getOffset()) { + if (!element.isLeaf()) { + int startIndex = element.getElementIndex(event.getOffset()); + int elementCount = element.getElementCount(); + int endIndex = Math.min(elementCount - 1, + element.getElementIndex(event.getOffset() + + event.getLength())); + + if (startIndex > 0 && startIndex < elementCount && element. + getElement(startIndex).getStartOffset() == event.getOffset()) { // Force checking the previous element. startIndex--; } - if(startIndex != -1 && endIndex != -1) { - for(int counter = startIndex; counter <= endIndex; counter++) { + if (startIndex != -1 && endIndex != -1) { + for (int counter = startIndex; counter <= endIndex; counter++) { updateTree(event, element.getElement(counter)); } } - } - else { + } else { // Element is a leaf, assume it changed - getTreeModel().nodeChanged((TreeNode)element); + getTreeModel().nodeChanged((TreeNode) element); } } @@ -426,14 +440,14 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL * Returns a TreePath to the element at position. */ protected TreePath getPathForIndex(int position, Object root, - Element rootElement) { - TreePath path = new TreePath(root); - Element child = rootElement.getElement - (rootElement.getElementIndex(position)); + Element rootElement) { + TreePath path = new TreePath(root); + Element child = rootElement.getElement(rootElement.getElementIndex( + position)); path = path.pathByAddingChild(rootElement); path = path.pathByAddingChild(child); - while(!child.isLeaf()) { + while (!child.isLeaf()) { child = child.getElement(child.getElementIndex(position)); path = path.pathByAddingChild(child); } @@ -456,7 +470,8 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL * methods have been subclassed, primarily to special case the root. */ public static class ElementTreeModel extends DefaultTreeModel { - protected Element[] rootElements; + + protected Element[] rootElements; public ElementTreeModel(Document document) { super(new DefaultMutableTreeNode("root"), false); @@ -474,13 +489,14 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL * @param parent a node in the tree, obtained from this data source * @return the child of parent at index index */ + @Override public Object getChild(Object parent, int index) { - if(parent == root) + if (parent == root) { return rootElements[index]; + } return super.getChild(parent, index); } - /** * Returns the number of children of parent. Returns 0 * if the node is a leaf or if it has no children. @@ -490,13 +506,14 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL * @param parent a node in the tree, obtained from this data source * @return the number of children of the node parent */ + @Override public int getChildCount(Object parent) { - if(parent == root) + if (parent == root) { return rootElements.length; + } return super.getChildCount(parent); } - /** * Returns true if node is a leaf. It is possible for * this method to return false even if node has no @@ -507,21 +524,25 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL * @param node a node in the tree, obtained from this data source * @return true if node is a leaf */ + @Override public boolean isLeaf(Object node) { - if(node == root) + if (node == root) { return false; + } return super.isLeaf(node); } /** * Returns the index of child in parent. */ + @Override public int getIndexOfChild(Object parent, Object child) { - if(parent == root) { - for(int counter = rootElements.length - 1; counter >= 0; - counter--) { - if(rootElements[counter] == child) + if (parent == root) { + for (int counter = rootElements.length - 1; counter >= 0; + counter--) { + if (rootElements[counter] == child) { return counter; + } } return -1; } @@ -532,18 +553,19 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL * Invoke this method after you've changed how node is to be * represented in the tree. */ + @Override public void nodeChanged(TreeNode node) { - if(listenerList != null && node != null) { - TreeNode parent = node.getParent(); + if (listenerList != null && node != null) { + TreeNode parent = node.getParent(); - if(parent == null && node != root) { + if (parent == null && node != root) { parent = root; } - if(parent != null) { - int anIndex = getIndexOfChild(parent, node); + if (parent != null) { + int anIndex = getIndexOfChild(parent, node); - if(anIndex != -1) { - int[] cIndexs = new int[1]; + if (anIndex != -1) { + int[] cIndexs = new int[1]; cIndexs[0] = anIndex; nodesChanged(parent, cIndexs); @@ -555,26 +577,28 @@ public class ElementTreePanel extends JPanel implements CaretListener, DocumentL /** * Returns the path to a particluar node. This is recursive. */ + @Override protected TreeNode[] getPathToRoot(TreeNode aNode, int depth) { - TreeNode[] retNodes; + TreeNode[] retNodes; /* Check for null, in case someone passed in a null node, or - they passed in an element that isn't rooted at root. */ - if(aNode == null) { - if(depth == 0) + they passed in an element that isn't rooted at root. */ + if (aNode == null) { + if (depth == 0) { return null; - else + } else { retNodes = new TreeNode[depth]; - } - else { + } + } else { depth++; - if(aNode == root) + if (aNode == root) { retNodes = new TreeNode[depth]; - else { + } else { TreeNode parent = aNode.getParent(); - if(parent == null) + if (parent == null) { parent = root; + } retNodes = getPathToRoot(parent, depth); } retNodes[retNodes.length - depth] = aNode; diff --git a/src/share/demo/jfc/Notepad/Notepad.java b/src/share/demo/jfc/Notepad/Notepad.java index 1c742798c6198641fbf8517b253a662c6ba9daba..a6d7e03a94664c7a18eaf836b9929078aafb773b 100644 --- a/src/share/demo/jfc/Notepad/Notepad.java +++ b/src/share/demo/jfc/Notepad/Notepad.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,20 +29,73 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.*; -import java.awt.event.*; -import java.beans.*; -import java.io.*; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.FileDialog; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; import java.net.URL; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.StringTokenizer; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JToolBar; +import javax.swing.JViewport; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UIManager.LookAndFeelInfo; +import javax.swing.event.UndoableEditEvent; +import javax.swing.event.UndoableEditListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.JTextComponent; +import javax.swing.text.PlainDocument; +import javax.swing.text.Segment; +import javax.swing.text.TextAction; +import javax.swing.undo.CannotRedoException; +import javax.swing.undo.CannotUndoException; +import javax.swing.undo.UndoManager; -import javax.swing.text.*; -import javax.swing.undo.*; -import javax.swing.event.*; -import javax.swing.*; /** * Sample application using the simple text editor component that @@ -50,22 +103,24 @@ import javax.swing.*; * * @author Timothy Prinzing */ +@SuppressWarnings("serial") class Notepad extends JPanel { private static ResourceBundle resources; - private final static String EXIT_AFTER_PAINT = new String("-exit"); + private final static String EXIT_AFTER_PAINT = "-exit"; private static boolean exitAfterFirstPaint; static { try { resources = ResourceBundle.getBundle("resources.Notepad", - Locale.getDefault()); + Locale.getDefault()); } catch (MissingResourceException mre) { System.err.println("resources/Notepad.properties not found"); System.exit(1); } } + @Override public void paintChildren(Graphics g) { super.paintChildren(g); if (exitAfterFirstPaint) { @@ -73,17 +128,19 @@ class Notepad extends JPanel { } } + @SuppressWarnings("OverridableMethodCallInConstructor") Notepad() { super(true); - // Force SwingSet to come up in the Cross Platform L&F + // Trying to set Nimbus look and feel try { - UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); - // If you want the System L&F instead, comment out the above line and - // uncomment the following: - // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch (Exception exc) { - System.err.println("Error loading L&F: " + exc); + for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (Exception ignored) { } setBorder(BorderFactory.createEtchedBorder()); @@ -95,7 +152,7 @@ class Notepad extends JPanel { editor.getDocument().addUndoableEditListener(undoHandler); // install the command table - commands = new Hashtable(); + commands = new HashMap(); Action[] actions = getActions(); for (int i = 0; i < actions.length; i++) { Action a = actions[i]; @@ -109,15 +166,17 @@ class Notepad extends JPanel { try { String vpFlag = resources.getString("ViewportBackingStore"); Boolean bs = Boolean.valueOf(vpFlag); - port.setBackingStoreEnabled(bs.booleanValue()); - } catch (MissingResourceException mre) { + port.setScrollMode(bs.booleanValue() + ? JViewport.BACKINGSTORE_SCROLL_MODE + : JViewport.BLIT_SCROLL_MODE); + } catch (MissingResourceException ignored) { // just use the viewport default } - menuItems = new Hashtable(); + menuItems = new HashMap(); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); - panel.add("North",createToolbar()); + panel.add("North", createToolbar()); panel.add("Center", scroller); add("Center", panel); add("South", createStatusbar()); @@ -125,28 +184,28 @@ class Notepad extends JPanel { public static void main(String[] args) { try { - String vers = System.getProperty("java.version"); - if (vers.compareTo("1.1.2") < 0) { - System.out.println("!!!WARNING: Swing must be run with a " + - "1.1.2 or higher version VM!!!"); - } - if (args.length > 0 && args[0].equals(EXIT_AFTER_PAINT)) { - exitAfterFirstPaint = true; - } - JFrame frame = new JFrame(); - frame.setTitle(resources.getString("Title")); - frame.setBackground(Color.lightGray); - frame.getContentPane().setLayout(new BorderLayout()); - Notepad notepad = new Notepad(); - frame.getContentPane().add("Center", notepad); - frame.setJMenuBar(notepad.createMenubar()); - frame.addWindowListener(new AppCloser()); - frame.pack(); - frame.setSize(500, 600); - frame.show(); + if (args.length > 0 && args[0].equals(EXIT_AFTER_PAINT)) { + exitAfterFirstPaint = true; + } + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + JFrame frame = new JFrame(); + frame.setTitle(resources.getString("Title")); + frame.setBackground(Color.lightGray); + frame.getContentPane().setLayout(new BorderLayout()); + Notepad notepad = new Notepad(); + frame.getContentPane().add("Center", notepad); + frame.setJMenuBar(notepad.createMenubar()); + frame.addWindowListener(new AppCloser()); + frame.pack(); + frame.setSize(500, 600); + frame.setVisible(true); + } + }); } catch (Throwable t) { - System.out.println("uncaught exception: " + t); - t.printStackTrace(); + Logger.getLogger(Notepad.class.getName()).log(Level.SEVERE, + "uncaught exception", t); } } @@ -177,6 +236,7 @@ class Notepad extends JPanel { return editor; } + /** * To shutdown when run as an application. This is a * fairly lame implementation. A more self-respecting @@ -184,6 +244,8 @@ class Notepad extends JPanel { * was needed. */ protected static final class AppCloser extends WindowAdapter { + + @Override public void windowClosing(WindowEvent e) { System.exit(0); } @@ -239,11 +301,11 @@ class Notepad extends JPanel { * if one wasn't created. */ protected JMenuItem getMenuItem(String cmd) { - return (JMenuItem) menuItems.get(cmd); + return menuItems.get(cmd); } protected Action getAction(String cmd) { - return (Action) commands.get(cmd); + return commands.get(cmd); } protected String getResourceString(String nm) { @@ -328,10 +390,14 @@ class Notepad extends JPanel { protected JButton createToolbarButton(String key) { URL url = getResource(key + imageSuffix); JButton b = new JButton(new ImageIcon(url)) { - public float getAlignmentY() { return 0.5f; } + + @Override + public float getAlignmentY() { + return 0.5f; + } }; b.setRequestFocusEnabled(false); - b.setMargin(new Insets(1,1,1,1)); + b.setMargin(new Insets(1, 1, 1, 1)); String astr = getResourceString(key + actionSuffix); if (astr == null) { @@ -360,15 +426,17 @@ class Notepad extends JPanel { * resource file. */ protected String[] tokenize(String input) { - Vector v = new Vector(); + List v = new ArrayList(); StringTokenizer t = new StringTokenizer(input); String cmd[]; - while (t.hasMoreTokens()) - v.addElement(t.nextToken()); + while (t.hasMoreTokens()) { + v.add(t.nextToken()); + } cmd = new String[v.size()]; - for (int i = 0; i < cmd.length; i++) - cmd[i] = (String) v.elementAt(i); + for (int i = 0; i < cmd.length; i++) { + cmd[i] = v.get(i); + } return cmd; } @@ -416,13 +484,16 @@ class Notepad extends JPanel { } // Yarked from JMenu, ideally this would be public. + private class ActionChangedListener implements PropertyChangeListener { + JMenuItem menuItem; ActionChangedListener(JMenuItem mi) { super(); this.menuItem = mi; } + public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if (e.getPropertyName().equals(Action.NAME)) { @@ -434,56 +505,48 @@ class Notepad extends JPanel { } } } - private JTextComponent editor; - private Hashtable commands; - private Hashtable menuItems; + private Map commands; + private Map menuItems; private JMenuBar menubar; private JToolBar toolbar; private JComponent status; private JFrame elementTreeFrame; protected ElementTreePanel elementTreePanel; - protected FileDialog fileDialog; - /** * Listener for the edits on the current document. */ protected UndoableEditListener undoHandler = new UndoHandler(); - /** UndoManager that we add edits to. */ protected UndoManager undo = new UndoManager(); - /** * Suffix applied to the key used in resource file * lookups for an image. */ public static final String imageSuffix = "Image"; - /** * Suffix applied to the key used in resource file * lookups for a label. */ public static final String labelSuffix = "Label"; - /** * Suffix applied to the key used in resource file * lookups for an action. */ public static final String actionSuffix = "Action"; - /** * Suffix applied to the key used in resource file * lookups for tooltip text. */ public static final String tipSuffix = "Tooltip"; - public static final String openAction = "open"; - public static final String newAction = "new"; + public static final String newAction = "new"; public static final String saveAction = "save"; public static final String exitAction = "exit"; public static final String showElementTreeAction = "showElementTree"; + class UndoHandler implements UndoableEditListener { /** @@ -497,6 +560,7 @@ class Notepad extends JPanel { } } + /** * FIXME - I'm not very useful yet */ @@ -507,17 +571,14 @@ class Notepad extends JPanel { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); } + @Override public void paint(Graphics g) { super.paint(g); } - } - // --- action implementations ----------------------------------- - private UndoAction undoAction = new UndoAction(); private RedoAction redoAction = new RedoAction(); - /** * Actions defined by the Notepad class */ @@ -531,7 +592,9 @@ class Notepad extends JPanel { redoAction }; + class UndoAction extends AbstractAction { + public UndoAction() { super("Undo"); setEnabled(false); @@ -541,26 +604,27 @@ class Notepad extends JPanel { try { undo.undo(); } catch (CannotUndoException ex) { - System.out.println("Unable to undo: " + ex); - ex.printStackTrace(); + Logger.getLogger(UndoAction.class.getName()).log(Level.SEVERE, + "Unable to undo", ex); } update(); redoAction.update(); } protected void update() { - if(undo.canUndo()) { + if (undo.canUndo()) { setEnabled(true); putValue(Action.NAME, undo.getUndoPresentationName()); - } - else { + } else { setEnabled(false); putValue(Action.NAME, "Undo"); } } } + class RedoAction extends AbstractAction { + public RedoAction() { super("Redo"); setEnabled(false); @@ -570,31 +634,32 @@ class Notepad extends JPanel { try { undo.redo(); } catch (CannotRedoException ex) { - System.out.println("Unable to redo: " + ex); - ex.printStackTrace(); + Logger.getLogger(RedoAction.class.getName()).log(Level.SEVERE, + "Unable to redo", ex); } update(); undoAction.update(); } protected void update() { - if(undo.canRedo()) { + if (undo.canRedo()) { setEnabled(true); putValue(Action.NAME, undo.getRedoPresentationName()); - } - else { + } else { setEnabled(false); putValue(Action.NAME, "Redo"); } } } + class OpenAction extends NewAction { OpenAction() { super(openAction); } + @Override public void actionPerformed(ActionEvent e) { Frame frame = getFrame(); JFileChooser chooser = new JFileChooser(); @@ -607,8 +672,9 @@ class Notepad extends JPanel { File f = chooser.getSelectedFile(); if (f.isFile() && f.canRead()) { Document oldDoc = getEditor().getDocument(); - if(oldDoc != null) + if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); + } if (elementTreePanel != null) { elementTreePanel.setEditor(null); } @@ -625,6 +691,7 @@ class Notepad extends JPanel { } } + class SaveAction extends AbstractAction { SaveAction() { @@ -647,6 +714,7 @@ class Notepad extends JPanel { } } + class NewAction extends AbstractAction { NewAction() { @@ -659,8 +727,9 @@ class Notepad extends JPanel { public void actionPerformed(ActionEvent e) { Document oldDoc = getEditor().getDocument(); - if(oldDoc != null) + if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); + } getEditor().setDocument(new PlainDocument()); getEditor().getDocument().addUndoableEditListener(undoHandler); resetUndoManager(); @@ -669,6 +738,7 @@ class Notepad extends JPanel { } } + /** * Really lame implementation of an exit command */ @@ -683,6 +753,7 @@ class Notepad extends JPanel { } } + /** * Action that brings up a JFrame with a JTree showing the structure * of the document. @@ -698,18 +769,19 @@ class Notepad extends JPanel { } public void actionPerformed(ActionEvent e) { - if(elementTreeFrame == null) { + if (elementTreeFrame == null) { // Create a frame containing an instance of // ElementTreePanel. try { - String title = resources.getString - ("ElementTreeFrameTitle"); + String title = resources.getString("ElementTreeFrameTitle"); elementTreeFrame = new JFrame(title); } catch (MissingResourceException mre) { elementTreeFrame = new JFrame(); } elementTreeFrame.addWindowListener(new WindowAdapter() { + + @Override public void windowClosing(WindowEvent weeee) { elementTreeFrame.setVisible(false); } @@ -721,10 +793,11 @@ class Notepad extends JPanel { fContentPane.add(elementTreePanel); elementTreeFrame.pack(); } - elementTreeFrame.show(); + elementTreeFrame.setVisible(true); } } + /** * Thread to load a file into the text storage model */ @@ -736,6 +809,7 @@ class Notepad extends JPanel { this.doc = doc; } + @Override public void run() { try { // initialize the statusbar @@ -751,22 +825,22 @@ class Notepad extends JPanel { char[] buff = new char[4096]; int nch; while ((nch = in.read(buff, 0, buff.length)) != -1) { - doc.insertString(doc.getLength(), new String(buff, 0, nch), null); + doc.insertString(doc.getLength(), new String(buff, 0, nch), + null); progress.setValue(progress.getValue() + nch); } - } - catch (IOException e) { + } catch (IOException e) { final String msg = e.getMessage(); SwingUtilities.invokeLater(new Runnable() { + public void run() { JOptionPane.showMessageDialog(getFrame(), "Could not open file: " + msg, "Error opening file", JOptionPane.ERROR_MESSAGE); - } + } }); - } - catch (BadLocationException e) { + } catch (BadLocationException e) { System.err.println(e.getMessage()); } doc.addUndoableEditListener(undoHandler); @@ -778,21 +852,23 @@ class Notepad extends JPanel { if (elementTreePanel != null) { SwingUtilities.invokeLater(new Runnable() { + public void run() { elementTreePanel.setEditor(getEditor()); } }); } } - Document doc; File f; } + /** * Thread to save a document to file */ class FileSaver extends Thread { + Document doc; File f; @@ -802,13 +878,15 @@ class Notepad extends JPanel { this.doc = doc; } + @Override + @SuppressWarnings("SleepWhileHoldingLock") public void run() { try { // initialize the statusbar status.removeAll(); JProgressBar progress = new JProgressBar(); progress.setMinimum(0); - progress.setMaximum((int) doc.getLength()); + progress.setMaximum(doc.getLength()); status.add(progress); status.revalidate(); @@ -827,24 +905,25 @@ class Notepad extends JPanel { try { Thread.sleep(10); } catch (InterruptedException e) { - e.printStackTrace(); + Logger.getLogger(FileSaver.class.getName()).log( + Level.SEVERE, + null, e); } } out.flush(); out.close(); - } - catch (IOException e) { + } catch (IOException e) { final String msg = e.getMessage(); SwingUtilities.invokeLater(new Runnable() { + public void run() { JOptionPane.showMessageDialog(getFrame(), "Could not save file: " + msg, "Error saving file", JOptionPane.ERROR_MESSAGE); - } + } }); - } - catch (BadLocationException e) { + } catch (BadLocationException e) { System.err.println(e.getMessage()); } // we are done... get rid of progressbar diff --git a/src/share/demo/jfc/SampleTree/DynamicTreeNode.java b/src/share/demo/jfc/SampleTree/DynamicTreeNode.java index 02c5ddfae6877e6ebc81a842e6f2e77f64ac0a5b..fa6db4dfd139031320d884bccf30bf6e2927b4e3 100644 --- a/src/share/demo/jfc/SampleTree/DynamicTreeNode.java +++ b/src/share/demo/jfc/SampleTree/DynamicTreeNode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,154 +29,154 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import javax.swing.tree.DefaultMutableTreeNode; import java.awt.Color; import java.awt.Font; -import java.awt.Toolkit; +import java.awt.GraphicsEnvironment; import java.util.Random; +import javax.swing.tree.DefaultMutableTreeNode; -/** - * DynamicTreeNode illustrates one of the possible ways in which dynamic - * loading can be used in tree. The basic premise behind this is that - * getChildCount() will be messaged from JTreeModel before any children - * are asked for. So, the first time getChildCount() is issued the - * children are loaded.

- * It should be noted that isLeaf will also be messaged from the model. - * The default behavior of TreeNode is to message getChildCount to - * determine this. As such, isLeaf is subclassed to always return false.

- * There are others ways this could be accomplished as well. Instead of - * subclassing TreeNode you could subclass JTreeModel and do the same - * thing in getChildCount(). Or, if you aren't using TreeNode you could - * write your own TreeModel implementation. - * Another solution would be to listen for TreeNodeExpansion events and - * the first time a node has been expanded post the appropriate insertion - * events. I would not recommend this approach though, the other two - * are much simpler and cleaner (and are faster from the perspective of - * how tree deals with it). - * - * NOTE: getAllowsChildren() can be messaged before getChildCount(). - * For this example the nodes always allow children, so it isn't - * a problem, but if you do support true leaf nodes you may want - * to check for loading in getAllowsChildren too. - * - * @author Scott Violet - */ -public class DynamicTreeNode extends DefaultMutableTreeNode -{ +/** + * DynamicTreeNode illustrates one of the possible ways in which dynamic + * loading can be used in tree. The basic premise behind this is that + * getChildCount() will be messaged from JTreeModel before any children + * are asked for. So, the first time getChildCount() is issued the + * children are loaded.

+ * It should be noted that isLeaf will also be messaged from the model. + * The default behavior of TreeNode is to message getChildCount to + * determine this. As such, isLeaf is subclassed to always return false.

+ * There are others ways this could be accomplished as well. Instead of + * subclassing TreeNode you could subclass JTreeModel and do the same + * thing in getChildCount(). Or, if you aren't using TreeNode you could + * write your own TreeModel implementation. + * Another solution would be to listen for TreeNodeExpansion events and + * the first time a node has been expanded post the appropriate insertion + * events. I would not recommend this approach though, the other two + * are much simpler and cleaner (and are faster from the perspective of + * how tree deals with it). + * + * NOTE: getAllowsChildren() can be messaged before getChildCount(). + * For this example the nodes always allow children, so it isn't + * a problem, but if you do support true leaf nodes you may want + * to check for loading in getAllowsChildren too. + * + * @author Scott Violet + */ +@SuppressWarnings("serial") +public class DynamicTreeNode extends DefaultMutableTreeNode { // Class stuff. - /** Number of names. */ - static protected float nameCount; + /** Number of names. */ + protected static float nameCount; /** Names to use for children. */ - static protected String[] names; - + protected static final String[] NAMES; /** Potential fonts used to draw with. */ - static protected Font[] fonts; - + protected static Font[] fonts; /** Used to generate the names. */ - static protected Random nameGen; - + protected static Random nameGen; /** Number of children to create for each node. */ - static protected final int DefaultChildrenCount = 7; + protected static final int DEFAULT_CHILDREN_COUNT = 7; static { - String[] fontNames; + String[] fontNames; try { - fontNames = Toolkit.getDefaultToolkit().getFontList(); + fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment(). + getAvailableFontFamilyNames(); + } catch (Exception e) { fontNames = null; } - if(fontNames == null || fontNames.length == 0) { - names = new String[] {"Mark Andrews", "Tom Ball", "Alan Chung", - "Rob Davis", "Jeff Dinkins", - "Amy Fowler", "James Gosling", - "David Karlton", "Dave Kloba", - "Dave Moore", "Hans Muller", - "Rick Levenson", "Tim Prinzing", - "Chester Rose", "Ray Ryan", - "Georges Saab", "Scott Violet", - "Kathy Walrath", "Arnaud Weber" }; - } - else { + if (fontNames == null || fontNames.length == 0) { + NAMES = new String[] { "Mark Andrews", "Tom Ball", "Alan Chung", + "Rob Davis", "Jeff Dinkins", + "Amy Fowler", "James Gosling", + "David Karlton", "Dave Kloba", + "Dave Moore", "Hans Muller", + "Rick Levenson", "Tim Prinzing", + "Chester Rose", "Ray Ryan", + "Georges Saab", "Scott Violet", + "Kathy Walrath", "Arnaud Weber" }; + } else { /* Create the Fonts, creating fonts is slow, much better to - do it once. */ - int fontSize = 12; + do it once. */ + int fontSize = 12; - names = fontNames; - fonts = new Font[names.length]; - for(int counter = 0, maxCounter = names.length; - counter < maxCounter; counter++) { + NAMES = fontNames; + fonts = new Font[NAMES.length]; + for (int counter = 0, maxCounter = NAMES.length; + counter < maxCounter; counter++) { try { fonts[counter] = new Font(fontNames[counter], 0, fontSize); - } - catch (Exception e) { + } catch (Exception e) { fonts[counter] = null; } fontSize = ((fontSize + 2 - 12) % 12) + 12; } } - nameCount = (float)names.length; + nameCount = (float) NAMES.length; nameGen = new Random(System.currentTimeMillis()); } - - /** Have the children of this node been loaded yet? */ - protected boolean hasLoaded; + protected boolean hasLoaded; /** - * Constructs a new DynamicTreeNode instance with o as the user - * object. - */ + * Constructs a new DynamicTreeNode instance with o as the user + * object. + */ public DynamicTreeNode(Object o) { super(o); } + @Override public boolean isLeaf() { return false; } /** - * If hasLoaded is false, meaning the children have not yet been - * loaded, loadChildren is messaged and super is messaged for - * the return value. - */ + * If hasLoaded is false, meaning the children have not yet been + * loaded, loadChildren is messaged and super is messaged for + * the return value. + */ + @Override public int getChildCount() { - if(!hasLoaded) { + if (!hasLoaded) { loadChildren(); } return super.getChildCount(); } /** - * Messaged the first time getChildCount is messaged. Creates - * children with random names from names. - */ + * Messaged the first time getChildCount is messaged. Creates + * children with random names from names. + */ protected void loadChildren() { - DynamicTreeNode newNode; - Font font; - int randomIndex; - SampleData data; - - for(int counter = 0; counter < DynamicTreeNode.DefaultChildrenCount; - counter++) { - randomIndex = (int)(nameGen.nextFloat() * nameCount); - if(fonts != null) - font = fonts[randomIndex]; - else + DynamicTreeNode newNode; + Font font; + int randomIndex; + SampleData data; + + for (int counter = 0; counter < DynamicTreeNode.DEFAULT_CHILDREN_COUNT; + counter++) { + randomIndex = (int) (nameGen.nextFloat() * nameCount); + String displayString = NAMES[randomIndex]; + if (fonts == null || fonts[randomIndex].canDisplayUpTo(displayString) + != -1) { font = null; - if(counter % 2 == 0) - data = new SampleData(font, Color.red, names[randomIndex]); - else - data = new SampleData(font, Color.blue, names[randomIndex]); + } else { + font = fonts[randomIndex]; + } + + if (counter % 2 == 0) { + data = new SampleData(font, Color.red, displayString); + } else { + data = new SampleData(font, Color.blue, displayString); + } newNode = new DynamicTreeNode(data); /* Don't use add() here, add calls insert(newNode, getChildCount()) - so if you want to use add, just be sure to set hasLoaded = true - first. */ + so if you want to use add, just be sure to set hasLoaded = true + first. */ insert(newNode, counter); } /* This node has now been loaded, mark it so. */ diff --git a/src/share/demo/jfc/SampleTree/SampleData.java b/src/share/demo/jfc/SampleTree/SampleData.java index 375f36b4073191da82f9ed4e310d09db929ef558..48a92dd8d0dfef59968c1593be52d3eea266052b 100644 --- a/src/share/demo/jfc/SampleTree/SampleData.java +++ b/src/share/demo/jfc/SampleTree/SampleData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,32 +29,27 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import java.awt.Color; import java.awt.Font; + /** - * @author Scott Violet - */ + * @author Scott Violet + */ +public class SampleData extends Object { -public class SampleData extends Object -{ /** Font used for drawing. */ - protected Font font; - + protected Font font; /** Color used for text. */ - protected Color color; - + protected Color color; /** Value to display. */ - protected String string; - + protected String string; /** - * Constructs a new instance of SampleData with the passed in - * arguments. - */ + * Constructs a new instance of SampleData with the passed in + * arguments. + */ public SampleData(Font newFont, Color newColor, String newString) { font = newFont; color = newColor; @@ -62,47 +57,48 @@ public class SampleData extends Object } /** - * Sets the font that is used to represent this object. - */ + * Sets the font that is used to represent this object. + */ public void setFont(Font newFont) { font = newFont; } /** - * Returns the Font used to represent this object. - */ + * Returns the Font used to represent this object. + */ public Font getFont() { return font; } /** - * Sets the color used to draw the text. - */ + * Sets the color used to draw the text. + */ public void setColor(Color newColor) { color = newColor; } /** - * Returns the color used to draw the text. - */ + * Returns the color used to draw the text. + */ public Color getColor() { return color; } /** - * Sets the string to display for this object. - */ + * Sets the string to display for this object. + */ public void setString(String newString) { string = newString; } /** - * Returnes the string to display for this object. - */ + * Returnes the string to display for this object. + */ public String string() { return string; } + @Override public String toString() { return string; } diff --git a/src/share/demo/jfc/SampleTree/SampleTree.java b/src/share/demo/jfc/SampleTree/SampleTree.java index 760180d391b410a85097fb4df4e7269b5ce67b3e..831d70cbdf9d6cb51f62bb94e164cf1aaa875202 100644 --- a/src/share/demo/jfc/SampleTree/SampleTree.java +++ b/src/share/demo/jfc/SampleTree/SampleTree.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,9 +29,10 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ +import java.lang.reflect.InvocationTargetException; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.swing.*; import javax.swing.event.*; import java.awt.BorderLayout; @@ -40,58 +41,57 @@ import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; import java.util.*; +import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.border.*; import javax.swing.tree.*; + /** - * A demo for illustrating how to do different things with JTree. - * The data that this displays is rather boring, that is each node will - * have 7 children that have random names based on the fonts. Each node - * is then drawn with that font and in a different color. - * While the data isn't interesting the example illustrates a number - * of things: - * - * For an example of dynamicaly loading children refer to DynamicTreeNode. - * For an example of adding/removing/inserting/reloading refer to the inner - * classes of this class, AddAction, RemovAction, InsertAction and - * ReloadAction. - * For an example of creating your own cell renderer refer to - * SampleTreeCellRenderer. - * For an example of subclassing JTreeModel for editing refer to - * SampleTreeModel. - * - * @author Scott Violet - */ - -public class SampleTree -{ + * A demo for illustrating how to do different things with JTree. + * The data that this displays is rather boring, that is each node will + * have 7 children that have random names based on the fonts. Each node + * is then drawn with that font and in a different color. + * While the data isn't interesting the example illustrates a number + * of things: + * + * For an example of dynamicaly loading children refer to DynamicTreeNode. + * For an example of adding/removing/inserting/reloading refer to the inner + * classes of this class, AddAction, RemovAction, InsertAction and + * ReloadAction. + * For an example of creating your own cell renderer refer to + * SampleTreeCellRenderer. + * For an example of subclassing JTreeModel for editing refer to + * SampleTreeModel. + * + * @author Scott Violet + */ +public final class SampleTree { + /** Window for showing Tree. */ - protected JFrame frame; + protected JFrame frame; /** Tree used for the example. */ - protected JTree tree; + protected JTree tree; /** Tree model. */ - protected DefaultTreeModel treeModel; + protected DefaultTreeModel treeModel; /** - * Constructs a new instance of SampleTree. - */ + * Constructs a new instance of SampleTree. + */ public SampleTree() { - // Force SampleTree to come up in the Cross Platform L&F + // Trying to set Nimbus look and feel try { - UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); - // If you want the System L&F instead, comment out the above line and - // uncomment the following: - // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch (Exception exc) { - System.err.println("Error loading L&F: " + exc); + for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (Exception ignored) { } - - JMenuBar menuBar = constructMenuBar(); - JPanel panel = new JPanel(true); + JMenuBar menuBar = constructMenuBar(); + JPanel panel = new JPanel(true); frame = new JFrame("SampleTree"); frame.getContentPane().add("Center", panel); @@ -106,18 +106,18 @@ public class SampleTree tree = new JTree(treeModel); /* Enable tool tips for the tree, without this tool tips will not - be picked up. */ + be picked up. */ ToolTipManager.sharedInstance().registerComponent(tree); /* Make the tree use an instance of SampleTreeCellRenderer for - drawing. */ + drawing. */ tree.setCellRenderer(new SampleTreeCellRenderer()); /* Make tree ask for the height of each row. */ tree.setRowHeight(-1); /* Put the Tree in a scroller. */ - JScrollPane sp = new JScrollPane(); + JScrollPane sp = new JScrollPane(); sp.setPreferredSize(new Dimension(300, 300)); sp.getViewport().add(tree); @@ -126,19 +126,18 @@ public class SampleTree panel.add("Center", sp); panel.add("South", constructOptionsPanel()); - frame.addWindowListener( new WindowAdapter() { - public void windowClosing(WindowEvent e) {System.exit(0);}}); - + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); - frame.show(); + frame.setVisible(true); } /** Constructs a JPanel containing check boxes for the different - * options that tree supports. */ + * options that tree supports. */ + @SuppressWarnings("serial") private JPanel constructOptionsPanel() { - JCheckBox aCheckbox; - JPanel retPanel = new JPanel(false); - JPanel borderPane = new JPanel(false); + JCheckBox aCheckbox; + JPanel retPanel = new JPanel(false); + JPanel borderPane = new JPanel(false); borderPane.setLayout(new BorderLayout()); retPanel.setLayout(new FlowLayout()); @@ -162,39 +161,54 @@ public class SampleTree borderPane.add(retPanel, BorderLayout.CENTER); /* Create a set of radio buttons that dictate what selection should - be allowed in the tree. */ - ButtonGroup group = new ButtonGroup(); - JPanel buttonPane = new JPanel(false); - JRadioButton button; + be allowed in the tree. */ + ButtonGroup group = new ButtonGroup(); + JPanel buttonPane = new JPanel(false); + JRadioButton button; buttonPane.setLayout(new FlowLayout()); buttonPane.setBorder(new TitledBorder("Selection Mode")); button = new JRadioButton("Single"); button.addActionListener(new AbstractAction() { - public boolean isEnabled() { return true; } + + @Override + public boolean isEnabled() { + return true; + } + public void actionPerformed(ActionEvent e) { - tree.getSelectionModel().setSelectionMode - (TreeSelectionModel.SINGLE_TREE_SELECTION); + tree.getSelectionModel().setSelectionMode( + TreeSelectionModel.SINGLE_TREE_SELECTION); } }); group.add(button); buttonPane.add(button); button = new JRadioButton("Contiguous"); button.addActionListener(new AbstractAction() { - public boolean isEnabled() { return true; } + + @Override + public boolean isEnabled() { + return true; + } + public void actionPerformed(ActionEvent e) { - tree.getSelectionModel().setSelectionMode - (TreeSelectionModel.CONTIGUOUS_TREE_SELECTION); + tree.getSelectionModel().setSelectionMode( + TreeSelectionModel.CONTIGUOUS_TREE_SELECTION); } }); group.add(button); buttonPane.add(button); button = new JRadioButton("Discontiguous"); button.addActionListener(new AbstractAction() { - public boolean isEnabled() { return true; } + + @Override + public boolean isEnabled() { + return true; + } + public void actionPerformed(ActionEvent e) { - tree.getSelectionModel().setSelectionMode - (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + tree.getSelectionModel().setSelectionMode( + TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); } }); button.setSelected(true); @@ -209,33 +223,33 @@ public class SampleTree /* JPanel clickPanel = new JPanel(); Object[] values = { "Never", new Integer(1), - new Integer(2), new Integer(3) }; + new Integer(2), new Integer(3) }; final JComboBox clickCBox = new JComboBox(values); clickPanel.setLayout(new FlowLayout()); clickPanel.add(new JLabel("Click count to expand:")); clickCBox.setSelectedIndex(2); clickCBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - Object selItem = clickCBox.getSelectedItem(); + public void actionPerformed(ActionEvent ae) { + Object selItem = clickCBox.getSelectedItem(); - if(selItem instanceof Integer) - tree.setToggleClickCount(((Integer)selItem).intValue()); - else // Don't toggle - tree.setToggleClickCount(0); - } + if(selItem instanceof Integer) + tree.setToggleClickCount(((Integer)selItem).intValue()); + else // Don't toggle + tree.setToggleClickCount(0); + } }); clickPanel.add(clickCBox); borderPane.add(clickPanel, BorderLayout.NORTH); -*/ + */ return borderPane; } /** Construct a menu. */ private JMenuBar constructMenuBar() { - JMenu menu; - JMenuBar menuBar = new JMenuBar(); - JMenuItem menuItem; + JMenu menu; + JMenuBar menuBar = new JMenuBar(); + JMenuItem menuItem; /* Good ol exit. */ menu = new JMenu("File"); @@ -243,9 +257,11 @@ public class SampleTree menuItem = menu.add(new JMenuItem("Exit")); menuItem.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { System.exit(0); - }}); + } + }); /* Tree related stuff. */ menu = new JMenu("Tree"); @@ -267,14 +283,15 @@ public class SampleTree } /** - * Returns the TreeNode instance that is selected in the tree. - * If nothing is selected, null is returned. - */ + * Returns the TreeNode instance that is selected in the tree. + * If nothing is selected, null is returned. + */ protected DefaultMutableTreeNode getSelectedNode() { - TreePath selPath = tree.getSelectionPath(); + TreePath selPath = tree.getSelectionPath(); - if(selPath != null) - return (DefaultMutableTreeNode)selPath.getLastPathComponent(); + if (selPath != null) { + return (DefaultMutableTreeNode) selPath.getLastPathComponent(); + } return null; } @@ -290,133 +307,136 @@ public class SampleTree return new DynamicTreeNode(new SampleData(null, Color.black, name)); } + /** - * AddAction is used to add a new item after the selected item. - */ - class AddAction extends Object implements ActionListener - { + * AddAction is used to add a new item after the selected item. + */ + class AddAction extends Object implements ActionListener { + /** Number of nodes that have been added. */ - public int addCount; + public int addCount; /** - * Messaged when the user clicks on the Add menu item. - * Determines the selection from the Tree and adds an item - * after that. If nothing is selected, an item is added to - * the root. - */ + * Messaged when the user clicks on the Add menu item. + * Determines the selection from the Tree and adds an item + * after that. If nothing is selected, an item is added to + * the root. + */ public void actionPerformed(ActionEvent e) { - DefaultMutableTreeNode lastItem = getSelectedNode(); - DefaultMutableTreeNode parent; + DefaultMutableTreeNode lastItem = getSelectedNode(); + DefaultMutableTreeNode parent; /* Determine where to create the new node. */ - if(lastItem != null) { - parent = (DefaultMutableTreeNode)lastItem.getParent(); - if(parent == null) { - parent = (DefaultMutableTreeNode)treeModel.getRoot(); + if (lastItem != null) { + parent = (DefaultMutableTreeNode) lastItem.getParent(); + if (parent == null) { + parent = (DefaultMutableTreeNode) treeModel.getRoot(); lastItem = null; } + } else { + parent = (DefaultMutableTreeNode) treeModel.getRoot(); } - else - parent = (DefaultMutableTreeNode)treeModel.getRoot(); if (parent == null) { // new root - treeModel.setRoot(createNewNode("Added " + - Integer.toString(addCount++))); - } - else { - int newIndex; - if(lastItem == null) + treeModel.setRoot(createNewNode("Added " + Integer.toString( + addCount++))); + } else { + int newIndex; + if (lastItem == null) { newIndex = treeModel.getChildCount(parent); - else + } else { newIndex = parent.getIndex(lastItem) + 1; + } /* Let the treemodel know. */ - treeModel.insertNodeInto(createNewNode("Added " + - Integer.toString(addCount++)), - parent, newIndex); + treeModel.insertNodeInto(createNewNode("Added " + Integer. + toString(addCount++)), + parent, newIndex); } } } // End of SampleTree.AddAction /** - * InsertAction is used to insert a new item before the selected item. - */ - class InsertAction extends Object implements ActionListener - { + * InsertAction is used to insert a new item before the selected item. + */ + class InsertAction extends Object implements ActionListener { + /** Number of nodes that have been added. */ - public int insertCount; + public int insertCount; /** - * Messaged when the user clicks on the Insert menu item. - * Determines the selection from the Tree and inserts an item - * after that. If nothing is selected, an item is added to - * the root. - */ + * Messaged when the user clicks on the Insert menu item. + * Determines the selection from the Tree and inserts an item + * after that. If nothing is selected, an item is added to + * the root. + */ public void actionPerformed(ActionEvent e) { - DefaultMutableTreeNode lastItem = getSelectedNode(); - DefaultMutableTreeNode parent; + DefaultMutableTreeNode lastItem = getSelectedNode(); + DefaultMutableTreeNode parent; /* Determine where to create the new node. */ - if(lastItem != null) { - parent = (DefaultMutableTreeNode)lastItem.getParent(); - if(parent == null) { - parent = (DefaultMutableTreeNode)treeModel.getRoot(); + if (lastItem != null) { + parent = (DefaultMutableTreeNode) lastItem.getParent(); + if (parent == null) { + parent = (DefaultMutableTreeNode) treeModel.getRoot(); lastItem = null; } + } else { + parent = (DefaultMutableTreeNode) treeModel.getRoot(); } - else - parent = (DefaultMutableTreeNode)treeModel.getRoot(); if (parent == null) { // new root - treeModel.setRoot(createNewNode("Inserted " + - Integer.toString(insertCount++))); - } - else { - int newIndex; + treeModel.setRoot(createNewNode("Inserted " + Integer.toString( + insertCount++))); + } else { + int newIndex; - if(lastItem == null) + if (lastItem == null) { newIndex = treeModel.getChildCount(parent); - else + } else { newIndex = parent.getIndex(lastItem); + } /* Let the treemodel know. */ - treeModel.insertNodeInto(createNewNode("Inserted " + - Integer.toString(insertCount++)), - parent, newIndex); + treeModel.insertNodeInto(createNewNode("Inserted " + Integer. + toString(insertCount++)), + parent, newIndex); } } } // End of SampleTree.InsertAction /** - * ReloadAction is used to reload from the selected node. If nothing - * is selected, reload is not issued. - */ - class ReloadAction extends Object implements ActionListener - { + * ReloadAction is used to reload from the selected node. If nothing + * is selected, reload is not issued. + */ + class ReloadAction extends Object implements ActionListener { + /** - * Messaged when the user clicks on the Reload menu item. - * Determines the selection from the Tree and asks the treemodel - * to reload from that node. - */ + * Messaged when the user clicks on the Reload menu item. + * Determines the selection from the Tree and asks the treemodel + * to reload from that node. + */ public void actionPerformed(ActionEvent e) { - DefaultMutableTreeNode lastItem = getSelectedNode(); + DefaultMutableTreeNode lastItem = getSelectedNode(); - if(lastItem != null) + if (lastItem != null) { treeModel.reload(lastItem); + } } } // End of SampleTree.ReloadAction + /** - * RemoveAction removes the selected node from the tree. If - * The root or nothing is selected nothing is removed. - */ - class RemoveAction extends Object implements ActionListener - { + * RemoveAction removes the selected node from the tree. If + * The root or nothing is selected nothing is removed. + */ + class RemoveAction extends Object implements ActionListener { + /** - * Removes the selected item as long as it isn't root. - */ + * Removes the selected item as long as it isn't root. + */ public void actionPerformed(ActionEvent e) { TreePath[] selected = getSelectedPaths(); @@ -451,19 +471,17 @@ public class SampleTree paths[counter] = null; } treeModel.setRoot(null); - } - else { + } else { // Find the siblings of path. TreePath parent = path.getParentPath(); - MutableTreeNode parentNode = (MutableTreeNode)parent. - getLastPathComponent(); - ArrayList toRemove = new ArrayList(); - int depth = parent.getPathCount(); + MutableTreeNode parentNode = (MutableTreeNode) parent. + getLastPathComponent(); + ArrayList toRemove = new ArrayList(); // First pass, find paths with a parent TreePath of parent for (int counter = paths.length - 1; counter >= 0; counter--) { - if (paths[counter] != null && paths[counter]. - getParentPath().equals(parent)) { + if (paths[counter] != null && paths[counter].getParentPath(). + equals(parent)) { toRemove.add(paths[counter]); paths[counter] = null; } @@ -477,9 +495,9 @@ public class SampleTree for (int counter = paths.length - 1; counter >= 0; counter--) { if (paths[counter] != null) { for (int rCounter = rCount - 1; rCounter >= 0; - rCounter--) { - if (((TreePath)toRemove.get(rCounter)). - isDescendant(paths[counter])) { + rCounter--) { + if ((toRemove.get(rCounter)).isDescendant( + paths[counter])) { paths[counter] = null; } } @@ -493,10 +511,10 @@ public class SampleTree int[] indices = new int[rCount]; Object[] removedNodes = new Object[rCount]; for (int counter = rCount - 1; counter >= 0; counter--) { - removedNodes[counter] = ((TreePath)toRemove.get(counter)). - getLastPathComponent(); - indices[counter] = treeModel.getIndexOfChild - (parentNode, removedNodes[counter]); + removedNodes[counter] = (toRemove.get(counter)). + getLastPathComponent(); + indices[counter] = treeModel.getIndexOfChild(parentNode, + removedNodes[counter]); parentNode.remove(indices[counter]); } treeModel.nodesWereRemoved(parentNode, indices, removedNodes); @@ -522,8 +540,7 @@ public class SampleTree return shallowestPath; } } - } - else { + } else { shallowestPath = paths[counter]; shallowest = paths[counter].getPathCount(); } @@ -540,67 +557,70 @@ public class SampleTree * This is actually rather expensive, it would be more efficient * to extract the indices and then do the comparision. */ - private class PositionComparator implements Comparator { - public int compare(Object o1, Object o2) { - TreePath p1 = (TreePath)o1; - int o1Index = treeModel.getIndexOfChild(p1.getParentPath(). - getLastPathComponent(), p1.getLastPathComponent()); - TreePath p2 = (TreePath)o2; - int o2Index = treeModel.getIndexOfChild(p2.getParentPath(). - getLastPathComponent(), p2.getLastPathComponent()); - return o1Index - o2Index; - } - - public boolean equals(Object obj) { - return super.equals(obj); + private class PositionComparator implements Comparator { + + public int compare(TreePath p1, TreePath p2) { + int p1Index = treeModel.getIndexOfChild(p1.getParentPath(). + getLastPathComponent(), p1.getLastPathComponent()); + int p2Index = treeModel.getIndexOfChild(p2.getParentPath(). + getLastPathComponent(), p2.getLastPathComponent()); + return p1Index - p2Index; } } - } // End of SampleTree.RemoveAction /** - * ShowHandlesChangeListener implements the ChangeListener interface - * to toggle the state of showing the handles in the tree. - */ - class ShowHandlesChangeListener extends Object implements ChangeListener - { + * ShowHandlesChangeListener implements the ChangeListener interface + * to toggle the state of showing the handles in the tree. + */ + class ShowHandlesChangeListener extends Object implements ChangeListener { + public void stateChanged(ChangeEvent e) { - tree.setShowsRootHandles(((JCheckBox)e.getSource()).isSelected()); + tree.setShowsRootHandles(((JCheckBox) e.getSource()).isSelected()); } - } // End of class SampleTree.ShowHandlesChangeListener /** - * ShowRootChangeListener implements the ChangeListener interface - * to toggle the state of showing the root node in the tree. - */ - class ShowRootChangeListener extends Object implements ChangeListener - { + * ShowRootChangeListener implements the ChangeListener interface + * to toggle the state of showing the root node in the tree. + */ + class ShowRootChangeListener extends Object implements ChangeListener { + public void stateChanged(ChangeEvent e) { - tree.setRootVisible(((JCheckBox)e.getSource()).isSelected()); + tree.setRootVisible(((JCheckBox) e.getSource()).isSelected()); } - } // End of class SampleTree.ShowRootChangeListener /** - * TreeEditableChangeListener implements the ChangeListener interface - * to toggle between allowing editing and now allowing editing in - * the tree. - */ - class TreeEditableChangeListener extends Object implements ChangeListener - { + * TreeEditableChangeListener implements the ChangeListener interface + * to toggle between allowing editing and now allowing editing in + * the tree. + */ + class TreeEditableChangeListener extends Object implements ChangeListener { + public void stateChanged(ChangeEvent e) { - tree.setEditable(((JCheckBox)e.getSource()).isSelected()); + tree.setEditable(((JCheckBox) e.getSource()).isSelected()); } - } // End of class SampleTree.TreeEditableChangeListener + public static void main(String args[]) { + try { + SwingUtilities.invokeAndWait(new Runnable() { - static public void main(String args[]) { - new SampleTree(); + @SuppressWarnings(value = "ResultOfObjectAllocationIgnored") + public void run() { + new SampleTree(); + } + }); + } catch (InterruptedException ex) { + Logger.getLogger(SampleTree.class.getName()).log(Level.SEVERE, null, + ex); + } catch (InvocationTargetException ex) { + Logger.getLogger(SampleTree.class.getName()).log(Level.SEVERE, null, + ex); + } } - } diff --git a/src/share/demo/jfc/SampleTree/SampleTreeCellRenderer.java b/src/share/demo/jfc/SampleTree/SampleTreeCellRenderer.java index 51c1a371c5cfc9a072b489c93636a674284ed32c..d45bf4e27b6f4fc06b9a936d5c68bef60fecf5f5 100644 --- a/src/share/demo/jfc/SampleTree/SampleTreeCellRenderer.java +++ b/src/share/demo/jfc/SampleTree/SampleTreeCellRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import javax.swing.Icon; import javax.swing.ImageIcon; @@ -42,48 +40,56 @@ import java.awt.Component; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; +import javax.swing.UIManager; + + +@SuppressWarnings("serial") +public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer { -public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer -{ /** Font used if the string to be displayed isn't a font. */ - static protected Font defaultFont; + protected static Font defaultFont; /** Icon to use when the item is collapsed. */ - static protected ImageIcon collapsedIcon; + protected static ImageIcon collapsedIcon; /** Icon to use when the item is expanded. */ - static protected ImageIcon expandedIcon; - + protected static ImageIcon expandedIcon; /** Color to use for the background when selected. */ - static protected final Color SelectedBackgroundColor = Color.yellow;//new Color(0, 0, 128); + protected static final Color SELECTED_BACKGROUND_COLOR; - static - { + static { + if ("Nimbus".equals(UIManager.getLookAndFeel().getName())) { + SELECTED_BACKGROUND_COLOR = new Color(0, 0, + 0, 0); + } else { + SELECTED_BACKGROUND_COLOR = Color.YELLOW; + } try { defaultFont = new Font("SansSerif", 0, 12); - } catch (Exception e) {} + } catch (Exception e) { + } try { - collapsedIcon = new ImageIcon(SampleTreeCellRenderer.class.getResource("/resources/images/collapsed.gif")); - expandedIcon = new ImageIcon(SampleTreeCellRenderer.class.getResource("/resources/images/expanded.gif")); + collapsedIcon = new ImageIcon(SampleTreeCellRenderer.class. + getResource("/resources/images/collapsed.gif")); + expandedIcon = new ImageIcon(SampleTreeCellRenderer.class. + getResource("/resources/images/expanded.gif")); } catch (Exception e) { System.out.println("Couldn't load images: " + e); } } - /** Whether or not the item that was last configured is selected. */ - protected boolean selected; + protected boolean selected; /** - * This is messaged from JTree whenever it needs to get the size - * of the component or it wants to draw it. - * This attempts to set the font based on value, which will be - * a TreeNode. - */ + * This is messaged from JTree whenever it needs to get the size + * of the component or it wants to draw it. + * This attempts to set the font based on value, which will be + * a TreeNode. + */ public Component getTreeCellRendererComponent(JTree tree, Object value, - boolean selected, boolean expanded, - boolean leaf, int row, - boolean hasFocus) { - Font font; - String stringValue = tree.convertValueToText(value, selected, - expanded, leaf, row, hasFocus); + boolean selected, boolean expanded, + boolean leaf, int row, + boolean hasFocus) { + String stringValue = tree.convertValueToText(value, selected, + expanded, leaf, row, hasFocus); /* Set the text. */ setText(stringValue); @@ -91,24 +97,27 @@ public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer setToolTipText(stringValue); /* Set the image. */ - if(expanded) + if (expanded) { setIcon(expandedIcon); - else if(!leaf) + } else if (!leaf) { setIcon(collapsedIcon); - else + } else { setIcon(null); + } /* Set the color and the font based on the SampleData userObject. */ - SampleData userObject = (SampleData)((DefaultMutableTreeNode)value) - .getUserObject(); - if(hasFocus) - setForeground(Color.cyan); - else + SampleData userObject = (SampleData) ((DefaultMutableTreeNode) value). + getUserObject(); + if (hasFocus) { + setForeground(UIManager.getColor("Tree.selectionForeground")); + } else { setForeground(userObject.getColor()); - if(userObject.getFont() == null) + } + if (userObject.getFont() == null) { setFont(defaultFont); - else + } else { setFont(userObject.getFont()); + } /* Update the selected flag for the next paint. */ this.selected = selected; @@ -117,36 +126,36 @@ public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer } /** - * paint is subclassed to draw the background correctly. JLabel - * currently does not allow backgrounds other than white, and it - * will also fill behind the icon. Something that isn't desirable. - */ + * paint is subclassed to draw the background correctly. JLabel + * currently does not allow backgrounds other than white, and it + * will also fill behind the icon. Something that isn't desirable. + */ + @Override public void paint(Graphics g) { - Color bColor; - Icon currentI = getIcon(); + Color bColor; + Icon currentI = getIcon(); - if(selected) - bColor = SelectedBackgroundColor; - else if(getParent() != null) - /* Pick background color up from parent (which will come from - the JTree we're contained in). */ + if (selected) { + bColor = SELECTED_BACKGROUND_COLOR; + } else if (getParent() != null) /* Pick background color up from parent (which will come from + the JTree we're contained in). */ { bColor = getParent().getBackground(); - else + } else { bColor = getBackground(); + } g.setColor(bColor); - if(currentI != null && getText() != null) { - int offset = (currentI.getIconWidth() + getIconTextGap()); + if (currentI != null && getText() != null) { + int offset = (currentI.getIconWidth() + getIconTextGap()); if (getComponentOrientation().isLeftToRight()) { g.fillRect(offset, 0, getWidth() - 1 - offset, - getHeight() - 1); - } - else { + getHeight() - 1); + } else { g.fillRect(0, 0, getWidth() - 1 - offset, getHeight() - 1); } + } else { + g.fillRect(0, 0, getWidth() - 1, getHeight() - 1); } - else - g.fillRect(0, 0, getWidth()-1, getHeight()-1); super.paint(g); } } diff --git a/src/share/demo/jfc/SampleTree/SampleTreeModel.java b/src/share/demo/jfc/SampleTree/SampleTreeModel.java index 4facf196d09cfd3b180860a84fd3addef91d3e46..51ee2daec91c9851168077e88f71b7b9ca5e983c 100644 --- a/src/share/demo/jfc/SampleTree/SampleTreeModel.java +++ b/src/share/demo/jfc/SampleTree/SampleTreeModel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; @@ -38,40 +36,43 @@ import javax.swing.tree.TreePath; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.Color; + /** - * SampleTreeModel extends JTreeModel to extends valueForPathChanged. - * This method is called as a result of the user editing a value in - * the tree. If you allow editing in your tree, are using TreeNodes - * and the user object of the TreeNodes is not a String, then you're going - * to have to subclass JTreeModel as this example does. - * - * @author Scott Violet - */ + * SampleTreeModel extends JTreeModel to extends valueForPathChanged. + * This method is called as a result of the user editing a value in + * the tree. If you allow editing in your tree, are using TreeNodes + * and the user object of the TreeNodes is not a String, then you're going + * to have to subclass JTreeModel as this example does. + * + * @author Scott Violet + */ +@SuppressWarnings("serial") +public class SampleTreeModel extends DefaultTreeModel { -public class SampleTreeModel extends DefaultTreeModel -{ /** - * Creates a new instance of SampleTreeModel with newRoot set - * to the root of this model. - */ + * Creates a new instance of SampleTreeModel with newRoot set + * to the root of this model. + */ public SampleTreeModel(TreeNode newRoot) { super(newRoot); } /** - * Subclassed to message setString() to the changed path item. - */ + * Subclassed to message setString() to the changed path item. + */ + @Override public void valueForPathChanged(TreePath path, Object newValue) { /* Update the user object. */ - DefaultMutableTreeNode aNode = (DefaultMutableTreeNode)path.getLastPathComponent(); - SampleData sampleData = (SampleData)aNode.getUserObject(); + DefaultMutableTreeNode aNode = (DefaultMutableTreeNode) path. + getLastPathComponent(); + SampleData sampleData = (SampleData) aNode.getUserObject(); - sampleData.setString((String)newValue); + sampleData.setString((String) newValue); /* UUUhhhhh, pretty colors. */ sampleData.setColor(Color.green); /* Since we've changed how the data is to be displayed, message - nodeChanged. */ + nodeChanged. */ nodeChanged(aNode); } } diff --git a/src/share/demo/jfc/SwingApplet/SwingApplet.java b/src/share/demo/jfc/SwingApplet/SwingApplet.java index bc801a0b3686c686148c30c1a62ed9340ac7c464..281ca709849a1c48221f0a577af6b33f676a8d11 100644 --- a/src/share/demo/jfc/SwingApplet/SwingApplet.java +++ b/src/share/demo/jfc/SwingApplet/SwingApplet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,42 +29,59 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.awt.*; -import java.awt.event.*; -import java.net.*; -import java.applet.*; -import javax.swing.*; +import java.awt.FlowLayout; +import java.lang.reflect.InvocationTargetException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JApplet; +import javax.swing.JButton; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + /** * A very simple applet. */ +@SuppressWarnings("serial") public class SwingApplet extends JApplet { JButton button; - public void init() { - - // Force SwingApplet to come up in the System L&F - String laf = UIManager.getSystemLookAndFeelClassName(); + private void initUI() { + // Trying to set Nimbus look and feel try { - UIManager.setLookAndFeel(laf); - // If you want the Cross Platform L&F instead, comment out the above line and - // uncomment the following: - // UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); - } catch (UnsupportedLookAndFeelException exc) { - System.err.println("Warning: UnsupportedLookAndFeel: " + laf); - } catch (Exception exc) { - System.err.println("Error loading " + laf + ": " + exc); + UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); + } catch (Exception ex) { + Logger.getLogger(SwingApplet.class.getName()). + log(Level.SEVERE, "Failed to apply Nimbus look and feel", ex); } - getContentPane().setLayout(new FlowLayout()); button = new JButton("Hello, I'm a Swing Button!"); getContentPane().add(button); + getContentPane().doLayout(); + } + + @Override + public void init() { + try { + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + initUI(); + } + }); + } catch (InterruptedException ex) { + Logger.getLogger(SwingApplet.class.getName()). + log(Level.SEVERE, null, ex); + } catch (InvocationTargetException ex) { + Logger.getLogger(SwingApplet.class.getName()). + log(Level.SEVERE, null, ex); + } } + @Override public void stop() { if (button != null) { getContentPane().remove(button); diff --git a/src/share/demo/jfc/TableExample/JDBCAdapter.java b/src/share/demo/jfc/TableExample/JDBCAdapter.java index 9093e7cb59db8fe2ae400964a3b437c42c6f4448..4dbfe4201159f0fcb59d4e77e613381a61ccbdeb 100644 --- a/src/share/demo/jfc/TableExample/JDBCAdapter.java +++ b/src/share/demo/jfc/TableExample/JDBCAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,46 +29,50 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; +import javax.swing.table.AbstractTableModel; + /** * An adaptor, transforming the JDBC interface to the TableModel interface. * * @author Philip Milne */ - -import java.util.Vector; -import java.sql.*; -import javax.swing.table.AbstractTableModel; -import javax.swing.event.TableModelEvent; - +@SuppressWarnings("serial") public class JDBCAdapter extends AbstractTableModel { - Connection connection; - Statement statement; - ResultSet resultSet; - String[] columnNames = {}; - Vector rows = new Vector(); - ResultSetMetaData metaData; + + Connection connection; + Statement statement; + ResultSet resultSet; + String[] columnNames = {}; + List> rows = new ArrayList>(); + ResultSetMetaData metaData; public JDBCAdapter(String url, String driverName, - String user, String passwd) { + String user, String passwd) { try { Class.forName(driverName); System.out.println("Opening db connection"); connection = DriverManager.getConnection(url, user, passwd); statement = connection.createStatement(); - } - catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ex) { System.err.println("Cannot find the database driver classes."); System.err.println(ex); - } - catch (SQLException ex) { + } catch (SQLException ex) { System.err.println("Cannot connect to this database."); System.err.println(ex); } - } + } public void executeQuery(String query) { if (connection == null || statement == null) { @@ -79,27 +83,28 @@ public class JDBCAdapter extends AbstractTableModel { resultSet = statement.executeQuery(query); metaData = resultSet.getMetaData(); - int numberOfColumns = metaData.getColumnCount(); + int numberOfColumns = metaData.getColumnCount(); columnNames = new String[numberOfColumns]; // Get the column names and cache them. // Then we can close the connection. - for(int column = 0; column < numberOfColumns; column++) { - columnNames[column] = metaData.getColumnLabel(column+1); + for (int column = 0; column < numberOfColumns; column++) { + columnNames[column] = metaData.getColumnLabel(column + 1); } // Get all rows. - rows = new Vector(); + rows = new ArrayList>(); while (resultSet.next()) { - Vector newRow = new Vector(); + List newRow = new ArrayList(); for (int i = 1; i <= getColumnCount(); i++) { - newRow.addElement(resultSet.getObject(i)); + newRow.add(resultSet.getObject(i)); } - rows.addElement(newRow); + rows.add(newRow); } // close(); Need to copy the metaData, bug in jdbc:odbc driver. - fireTableChanged(null); // Tell the listeners a new table has arrived. - } - catch (SQLException ex) { + + // Tell the listeners a new table has arrived. + fireTableChanged(null); + } catch (SQLException ex) { System.err.println(ex); } } @@ -111,6 +116,7 @@ public class JDBCAdapter extends AbstractTableModel { connection.close(); } + @Override protected void finalize() throws Throwable { close(); super.finalize(); @@ -121,9 +127,8 @@ public class JDBCAdapter extends AbstractTableModel { // Implementation of the TableModel Interface // ////////////////////////////////////////////////////////////////////////// - // MetaData - + @Override public String getColumnName(int column) { if (columnNames[column] != null) { return columnNames[column]; @@ -132,49 +137,49 @@ public class JDBCAdapter extends AbstractTableModel { } } - public Class getColumnClass(int column) { + @Override + public Class getColumnClass(int column) { int type; try { - type = metaData.getColumnType(column+1); - } - catch (SQLException e) { + type = metaData.getColumnType(column + 1); + } catch (SQLException e) { return super.getColumnClass(column); } - switch(type) { - case Types.CHAR: - case Types.VARCHAR: - case Types.LONGVARCHAR: - return String.class; + switch (type) { + case Types.CHAR: + case Types.VARCHAR: + case Types.LONGVARCHAR: + return String.class; - case Types.BIT: - return Boolean.class; + case Types.BIT: + return Boolean.class; - case Types.TINYINT: - case Types.SMALLINT: - case Types.INTEGER: - return Integer.class; + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + return Integer.class; - case Types.BIGINT: - return Long.class; + case Types.BIGINT: + return Long.class; - case Types.FLOAT: - case Types.DOUBLE: - return Double.class; + case Types.FLOAT: + case Types.DOUBLE: + return Double.class; - case Types.DATE: - return java.sql.Date.class; + case Types.DATE: + return java.sql.Date.class; - default: - return Object.class; + default: + return Object.class; } } + @Override public boolean isCellEditable(int row, int column) { try { - return metaData.isWritable(column+1); - } - catch (SQLException e) { + return metaData.isWritable(column + 1); + } catch (SQLException e) { return false; } } @@ -184,14 +189,13 @@ public class JDBCAdapter extends AbstractTableModel { } // Data methods - public int getRowCount() { return rows.size(); } public Object getValueAt(int aRow, int aColumn) { - Vector row = (Vector)rows.elementAt(aRow); - return row.elementAt(aColumn); + List row = rows.get(aRow); + return row.get(aColumn); } public String dbRepresentation(int column, Object value) { @@ -202,43 +206,42 @@ public class JDBCAdapter extends AbstractTableModel { } try { - type = metaData.getColumnType(column+1); - } - catch (SQLException e) { + type = metaData.getColumnType(column + 1); + } catch (SQLException e) { return value.toString(); } - switch(type) { - case Types.INTEGER: - case Types.DOUBLE: - case Types.FLOAT: - return value.toString(); - case Types.BIT: - return ((Boolean)value).booleanValue() ? "1" : "0"; - case Types.DATE: - return value.toString(); // This will need some conversion. - default: - return "\""+value.toString()+"\""; + switch (type) { + case Types.INTEGER: + case Types.DOUBLE: + case Types.FLOAT: + return value.toString(); + case Types.BIT: + return ((Boolean) value).booleanValue() ? "1" : "0"; + case Types.DATE: + return value.toString(); // This will need some conversion. + default: + return "\"" + value.toString() + "\""; } } + @Override public void setValueAt(Object value, int row, int column) { try { - String tableName = metaData.getTableName(column+1); + String tableName = metaData.getTableName(column + 1); // Some of the drivers seem buggy, tableName should not be null. if (tableName == null) { System.out.println("Table name returned null."); } String columnName = getColumnName(column); String query = - "update "+tableName+ - " set "+columnName+" = "+dbRepresentation(column, value)+ - " where "; + "update " + tableName + " set " + columnName + " = " + + dbRepresentation(column, value) + " where "; // We don't have a model of the schema so we don't know the // primary keys or which columns to lock on. To demonstrate // that editing is possible, we'll just lock on everything. - for(int col = 0; col dataRow = rows.get(row); + dataRow.set(column, value); } } diff --git a/src/share/demo/jfc/TableExample/OldJTable.java b/src/share/demo/jfc/TableExample/OldJTable.java index 2ee6267eac5f1898626f47557e1a4c0eb5ad30a2..28a3f212816341230f806a9962e9da444a799d26 100644 --- a/src/share/demo/jfc/TableExample/OldJTable.java +++ b/src/share/demo/jfc/TableExample/OldJTable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,28 +29,26 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ -import java.lang.Thread; -import java.util.*; -import java.awt.*; -import java.awt.event.*; -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.plaf.*; -import javax.swing.table.*; +import java.util.EventObject; +import java.util.List; +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; /** * The OldJTable is an unsupported class containing some methods that were * deleted from the JTable between releases 0.6 and 0.7 */ +@SuppressWarnings("serial") public class OldJTable extends JTable { /* - * A new convenience method returning the index of the column in the co-ordinate - * space of the view. + * A new convenience method returning the index of the column in the + * co-ordinate space of the view. */ public int getColumnIndex(Object identifier) { return getColumnModel().getColumnIndex(identifier); @@ -65,7 +63,7 @@ public class OldJTable extends JTable return addColumn(columnIdentifier, width, null, null, null); } - public TableColumn addColumn(Object columnIdentifier, Vector columnData) { + public TableColumn addColumn(Object columnIdentifier, List columnData) { return addColumn(columnIdentifier, -1, null, null, columnData); } @@ -79,16 +77,17 @@ public class OldJTable extends JTable public TableColumn addColumn(Object columnIdentifier, int width, TableCellRenderer renderer, - TableCellEditor editor, Vector columnData) { + TableCellEditor editor, List columnData) { checkDefaultTableModel(); // Set up the model side first DefaultTableModel m = (DefaultTableModel)getModel(); - m.addColumn(columnIdentifier, columnData); + m.addColumn(columnIdentifier, columnData.toArray()); // The column will have been added to the end, so the index of the // column in the model is the last element. - TableColumn newColumn = new TableColumn(m.getColumnCount()-1, width, renderer, editor); + TableColumn newColumn = new TableColumn( + m.getColumnCount()-1, width, renderer, editor); super.addColumn(newColumn); return newColumn; } @@ -104,9 +103,9 @@ public class OldJTable extends JTable ((DefaultTableModel)getModel()).addRow(rowData); } - public void addRow(Vector rowData) { + public void addRow(List rowData) { checkDefaultTableModel(); - ((DefaultTableModel)getModel()).addRow(rowData); + ((DefaultTableModel)getModel()).addRow(rowData.toArray()); } public void removeRow(int rowIndex) { @@ -124,9 +123,9 @@ public class OldJTable extends JTable ((DefaultTableModel)getModel()).insertRow(rowIndex, rowData); } - public void insertRow(int rowIndex, Vector rowData) { + public void insertRow(int rowIndex, List rowData) { checkDefaultTableModel(); - ((DefaultTableModel)getModel()).insertRow(rowIndex, rowData); + ((DefaultTableModel)getModel()).insertRow(rowIndex, rowData.toArray()); } public void setNumRows(int newSize) { @@ -134,9 +133,10 @@ public class OldJTable extends JTable ((DefaultTableModel)getModel()).setNumRows(newSize); } - public void setDataVector(Vector newData, Vector columnIds) { + public void setDataVector(Object[][] newData, List columnIds) { checkDefaultTableModel(); - ((DefaultTableModel)getModel()).setDataVector(newData, columnIds); + ((DefaultTableModel)getModel()).setDataVector( + newData, columnIds.toArray()); } public void setDataVector(Object[][] newData, Object[] columnIds) { @@ -154,11 +154,11 @@ public class OldJTable extends JTable // public Object getValueAt(Object columnIdentifier, int rowIndex) { - return super.getValueAt(rowIndex, getColumnIndex(columnIdentifier)); + return super.getValueAt(rowIndex, getColumnIndex(columnIdentifier)); } public boolean isCellEditable(Object columnIdentifier, int rowIndex) { - return super.isCellEditable(rowIndex, getColumnIndex(columnIdentifier)); + return super.isCellEditable(rowIndex, getColumnIndex(columnIdentifier)); } public void setValueAt(Object aValue, Object columnIdentifier, int rowIndex) { @@ -217,7 +217,8 @@ public class OldJTable extends JTable public TableColumn addColumn(int modelColumn, int width, TableCellRenderer renderer, TableCellEditor editor) { - TableColumn newColumn = new TableColumn(modelColumn, width, renderer, editor); + TableColumn newColumn = new TableColumn( + modelColumn, width, renderer, editor); addColumn(newColumn); return newColumn; } diff --git a/src/share/demo/jfc/TableExample/TableExample.java b/src/share/demo/jfc/TableExample/TableExample.java index b0ac36dac0436fda16981b18187fcf5a61bfdf74..03d798f3f1226f034b1fa93563c6f7cb2f2c9d92 100644 --- a/src/share/demo/jfc/TableExample/TableExample.java +++ b/src/share/demo/jfc/TableExample/TableExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ /** * A a UI around the JDBCAdaptor, allowing database data to be interactively @@ -41,41 +39,56 @@ * * @author Philip Milne */ +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.LayoutManager; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.UIManager; +import javax.swing.UIManager.LookAndFeelInfo; +import javax.swing.border.BevelBorder; + + +public final class TableExample implements LayoutManager { -import java.applet.Applet; -import java.awt.*; -import java.awt.event.*; -import javax.swing.*; -import javax.swing.table.*; -import javax.swing.event.*; -import javax.swing.border.*; - -public class TableExample implements LayoutManager { static String[] ConnectOptionNames = { "Connect" }; - static String ConnectTitle = "Connection Information"; - - Dimension origin = new Dimension(0, 0); - - JButton fetchButton; - JButton showConnectionInfoButton; - - JPanel connectionPanel; - JFrame frame; // The query/results window. - - JLabel userNameLabel; - JTextField userNameField; - JLabel passwordLabel; - JTextField passwordField; + static String ConnectTitle = "Connection Information"; + Dimension origin = new Dimension(0, 0); + JButton fetchButton; + JButton showConnectionInfoButton; + JPanel connectionPanel; + JFrame frame; // The query/results window. + JLabel userNameLabel; + JTextField userNameField; + JLabel passwordLabel; + JTextField passwordField; // JLabel queryLabel; - JTextArea queryTextArea; - JComponent queryAggregate; - JLabel serverLabel; - JTextField serverField; - JLabel driverLabel; - JTextField driverField; - - JPanel mainPanel; - + JTextArea queryTextArea; + JComponent queryAggregate; + JLabel serverLabel; + JTextField serverField; + JLabel driverLabel; + JTextField driverField; + JPanel mainPanel; TableSorter sorter; JDBCAdapter dataBase; JScrollPane tableAggregate; @@ -85,14 +98,15 @@ public class TableExample implements LayoutManager { * If the user clicks on the 'Connect' button the connection is reset. */ void activateConnectionDialog() { - if(JOptionPane.showOptionDialog(tableAggregate, connectionPanel, ConnectTitle, - JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, - null, ConnectOptionNames, ConnectOptionNames[0]) == 0) { + if (JOptionPane.showOptionDialog(tableAggregate, connectionPanel, + ConnectTitle, + JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, + null, ConnectOptionNames, ConnectOptionNames[0]) == 0) { connect(); frame.setVisible(true); - } - else if(!frame.isVisible()) + } else if (!frame.isVisible()) { System.exit(0); + } } /** @@ -102,21 +116,21 @@ public class TableExample implements LayoutManager { public void createConnectionDialog() { // Create the labels and text fields. userNameLabel = new JLabel("User name: ", JLabel.RIGHT); - userNameField = new JTextField("guest"); + userNameField = new JTextField("app"); passwordLabel = new JLabel("Password: ", JLabel.RIGHT); - passwordField = new JTextField("trustworthy"); + passwordField = new JTextField("app"); serverLabel = new JLabel("Database URL: ", JLabel.RIGHT); - serverField = new JTextField("jdbc:sybase://dbtest:1455/pubs2"); + serverField = new JTextField("jdbc:derby://localhost:1527/sample"); driverLabel = new JLabel("Driver: ", JLabel.RIGHT); - driverField = new JTextField("connect.sybase.SybaseDriver"); + driverField = new JTextField("org.apache.derby.jdbc.ClientDriver"); connectionPanel = new JPanel(false); connectionPanel.setLayout(new BoxLayout(connectionPanel, - BoxLayout.X_AXIS)); + BoxLayout.X_AXIS)); JPanel namePanel = new JPanel(false); namePanel.setLayout(new GridLayout(0, 1)); @@ -145,22 +159,22 @@ public class TableExample implements LayoutManager { // Create the buttons. showConnectionInfoButton = new JButton("Configuration"); showConnectionInfoButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - activateConnectionDialog(); - } + + public void actionPerformed(ActionEvent e) { + activateConnectionDialog(); } - ); + }); fetchButton = new JButton("Fetch"); fetchButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - fetch(); - } + + public void actionPerformed(ActionEvent e) { + fetch(); } - ); + }); // Create the query text area and label. - queryTextArea = new JTextArea("SELECT * FROM titles", 25, 25); + queryTextArea = new JTextArea("SELECT * FROM APP.CUSTOMER", 25, 25); queryAggregate = new JScrollPane(queryTextArea); queryAggregate.setBorder(new BevelBorder(BevelBorder.LOWERED)); @@ -178,7 +192,12 @@ public class TableExample implements LayoutManager { // Create a Frame and put the main panel in it. frame = new JFrame("TableExample"); frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) {System.exit(0);}}); + + @Override + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); frame.setBackground(Color.lightGray); frame.getContentPane().add(mainPanel); frame.pack(); @@ -189,13 +208,13 @@ public class TableExample implements LayoutManager { } public void connect() { - dataBase = new JDBCAdapter( - serverField.getText(), - driverField.getText(), - userNameField.getText(), - passwordField.getText()); - sorter.setModel(dataBase); - } + dataBase = new JDBCAdapter( + serverField.getText(), + driverField.getText(), + userNameField.getText(), + passwordField.getText()); + sorter.setModel(dataBase); + } public void fetch() { dataBase.executeQuery(queryTextArea.getText()); @@ -221,25 +240,48 @@ public class TableExample implements LayoutManager { } public static void main(String s[]) { + // Trying to set Nimbus look and feel + try { + for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (Exception ex) { + Logger.getLogger(TableExample.class.getName()).log(Level.SEVERE, + "Failed to apply Nimbus look and feel", ex); + } + new TableExample(); } - public Dimension preferredLayoutSize(Container c){return origin;} - public Dimension minimumLayoutSize(Container c){return origin;} - public void addLayoutComponent(String s, Component c) {} - public void removeLayoutComponent(Component c) {} + public Dimension preferredLayoutSize(Container c) { + return origin; + } + + public Dimension minimumLayoutSize(Container c) { + return origin; + } + + public void addLayoutComponent(String s, Component c) { + } + + public void removeLayoutComponent(Component c) { + } + public void layoutContainer(Container c) { Rectangle b = c.getBounds(); int topHeight = 90; int inset = 4; - showConnectionInfoButton.setBounds(b.width-2*inset-120, inset, 120, 25); - fetchButton.setBounds(b.width-2*inset-120, 60, 120, 25); + showConnectionInfoButton.setBounds(b.width - 2 * inset - 120, inset, 120, + 25); + fetchButton.setBounds(b.width - 2 * inset - 120, 60, 120, 25); // queryLabel.setBounds(10, 10, 100, 25); - queryAggregate.setBounds(inset, inset, b.width-2*inset - 150, 80); + queryAggregate.setBounds(inset, inset, b.width - 2 * inset - 150, 80); tableAggregate.setBounds(new Rectangle(inset, - inset + topHeight, - b.width-2*inset, - b.height-2*inset - topHeight)); + inset + topHeight, + b.width - 2 * inset, + b.height - 2 * inset - topHeight)); } - } diff --git a/src/share/demo/jfc/TableExample/TableExample2.java b/src/share/demo/jfc/TableExample/TableExample2.java index 145e71046408f3c084cb95f1a7d1b99767bda3ab..9423f17556ea0ebd2dc1a8dea17144f08e35fdb2 100644 --- a/src/share/demo/jfc/TableExample/TableExample2.java +++ b/src/share/demo/jfc/TableExample/TableExample2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,28 +29,36 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ + +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.Dimension; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JFrame; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.UIManager; +import javax.swing.UIManager.LookAndFeelInfo; + /** * A minimal example, using the JTable to view data from a database. * * @author Philip Milne */ - -import javax.swing.*; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.Dimension; - public class TableExample2 { public TableExample2(String URL, String driver, String user, - String passwd, String query) { + String passwd, String query) { JFrame frame = new JFrame("Table"); frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) {System.exit(0);}}); + + @Override + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); JDBCAdapter dt = new JDBCAdapter(URL, driver, user, passwd); dt.executeQuery(query); @@ -68,9 +76,26 @@ public class TableExample2 { public static void main(String[] args) { if (args.length != 5) { System.err.println("Needs database parameters eg. ..."); - System.err.println("java TableExample2 \"jdbc:sybase://dbtest:1455/pubs2\" \"connect.sybase.SybaseDriver\" guest trustworthy \"select * from titles\""); + System.err.println( + "java TableExample2 \"jdbc:derby://localhost:1527/sample\" " + + "org.apache.derby.jdbc.ClientDriver app app " + + "\"select * from app.customer\""); return; } + + // Trying to set Nimbus look and feel + try { + for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (Exception ex) { + Logger.getLogger(TableExample2.class.getName()).log(Level.SEVERE, + "Failed to apply Nimbus look and feel", ex); + } + new TableExample2(args[0], args[1], args[2], args[3], args[4]); } } diff --git a/src/share/demo/jfc/TableExample/TableExample3.java b/src/share/demo/jfc/TableExample/TableExample3.java index b04b40aa6a532e25a1a344b4971b59a32f99b5d7..51646395b0eec09f4c037f4576b09a578a9ae5ed 100644 --- a/src/share/demo/jfc/TableExample/TableExample3.java +++ b/src/share/demo/jfc/TableExample/TableExample3.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,16 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ - -/** - * An example showing the JTable with a dataModel that is not derived - * from a database. We add the optional TableSorter object to give the - * JTable the ability to sort. - * - * @author Philip Milne - */ import javax.swing.*; import javax.swing.table.*; @@ -46,63 +36,104 @@ import javax.swing.table.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.Dimension; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.UIManager.LookAndFeelInfo; + +/** + * An example showing the JTable with a dataModel that is not derived + * from a database. We add the optional TableSorter object to give the + * JTable the ability to sort. + * + * @author Philip Milne + */ public class TableExample3 { public TableExample3() { JFrame frame = new JFrame("Table"); frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) {System.exit(0);}}); + + @Override + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); // Take the dummy data from SwingSet. - final String[] names = {"First Name", "Last Name", "Favorite Color", - "Favorite Number", "Vegetarian"}; + final String[] names = { "First Name", "Last Name", "Favorite Color", + "Favorite Number", "Vegetarian" }; final Object[][] data = { - {"Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE}, - {"Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE}, - {"Alan", "Chung", "Green", new Integer(838), Boolean.FALSE}, - {"Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE}, - {"Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE}, - {"Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE}, - {"James", "Gosling", "Pink", new Integer(21), Boolean.FALSE}, - {"David", "Karlton", "Red", new Integer(1), Boolean.FALSE}, - {"Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE}, - {"Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE}, - {"Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE}, - {"Dave", "Moore", "Green", new Integer(88), Boolean.FALSE}, - {"Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE}, - {"Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE}, - {"Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE}, - {"Chester", "Rose", "Black", new Integer(0), Boolean.FALSE}, - {"Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE}, - {"Georges", "Saab", "Red", new Integer(4), Boolean.FALSE}, - {"Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE}, - {"Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE}, - {"Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE} + { "Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE }, + { "Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE }, + { "Alan", "Chung", "Green", new Integer(838), Boolean.FALSE }, + { "Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE }, + { "Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE }, + { "Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE }, + { "James", "Gosling", "Pink", new Integer(21), Boolean.FALSE }, + { "David", "Karlton", "Red", new Integer(1), Boolean.FALSE }, + { "Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE }, + { "Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE }, + { "Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE }, + { "Dave", "Moore", "Green", new Integer(88), Boolean.FALSE }, + { "Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE }, + { "Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE }, + { "Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE }, + { "Chester", "Rose", "Black", new Integer(0), Boolean.FALSE }, + { "Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE }, + { "Georges", "Saab", "Red", new Integer(4), Boolean.FALSE }, + { "Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE }, + { "Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE }, + { "Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE } }; // Create a model of the data. + @SuppressWarnings("serial") TableModel dataModel = new AbstractTableModel() { // These methods always need to be implemented. - public int getColumnCount() { return names.length; } - public int getRowCount() { return data.length;} - public Object getValueAt(int row, int col) {return data[row][col];} + + public int getColumnCount() { + return names.length; + } + + public int getRowCount() { + return data.length; + } + + public Object getValueAt(int row, int col) { + return data[row][col]; + } // The default implementations of these methods in // AbstractTableModel would work, but we can refine them. - public String getColumnName(int column) {return names[column];} - public Class getColumnClass(int col) {return getValueAt(0,col).getClass();} - public boolean isCellEditable(int row, int col) {return (col==4);} + @Override + public String getColumnName(int column) { + return names[column]; + } + + @Override + public Class getColumnClass(int col) { + return getValueAt(0, col).getClass(); + } + + @Override + public boolean isCellEditable(int row, int col) { + return (col == 4); + } + + @Override public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; } - }; + }; - // Instead of making the table display the data as it would normally with: + // Instead of making the table display the data as it would normally + // with: // JTable tableView = new JTable(dataModel); - // Add a sorter, by using the following three lines instead of the one above. - TableSorter sorter = new TableSorter(dataModel); - JTable tableView = new JTable(sorter); + // Add a sorter, by using the following three lines instead of the one + // above. + TableSorter sorter = new TableSorter(dataModel); + JTable tableView = new JTable(sorter); sorter.addMouseListenerToHeaderInTable(tableView); JScrollPane scrollpane = new JScrollPane(tableView); @@ -114,6 +145,18 @@ public class TableExample3 { } public static void main(String[] args) { + // Trying to set Nimbus look and feel + try { + for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (Exception ex) { + Logger.getLogger(TableExample3.class.getName()).log(Level.SEVERE, + "Failed to apply Nimbus look and feel", ex); + } new TableExample3(); } } diff --git a/src/share/demo/jfc/TableExample/TableExample4.java b/src/share/demo/jfc/TableExample/TableExample4.java index 621d905256ac599410df7bb0c1e80552ec7fa1b9..e75e2db3838ad2e4dae5f3ee4a160d07e85ef197 100644 --- a/src/share/demo/jfc/TableExample/TableExample4.java +++ b/src/share/demo/jfc/TableExample/TableExample4.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,83 +29,112 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ - -/** - * Another JTable example, showing how column attributes can be refined - * even when columns have been created automatically. Here we create some - * specialised renderers and editors as well as changing widths and colors - * for some of the columns in the SwingSet demo table. - * - * @author Philip Milne - */ import javax.swing.*; import javax.swing.table.*; import javax.swing.border.*; - import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.Color; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.UIManager.LookAndFeelInfo; + +/** + * Another JTable example, showing how column attributes can be refined + * even when columns have been created automatically. Here we create some + * specialised renderers and editors as well as changing widths and colors + * for some of the columns in the SwingSet demo table. + * + * @author Philip Milne + */ public class TableExample4 { public TableExample4() { JFrame frame = new JFrame("Table"); frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) {System.exit(0);}}); + + @Override + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); // Take the dummy data from SwingSet. - final String[] names = {"First Name", "Last Name", "Favorite Color", - "Favorite Number", "Vegetarian"}; + final String[] names = { "First Name", "Last Name", "Favorite Color", + "Favorite Number", "Vegetarian" }; final Object[][] data = { - {"Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE}, - {"Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE}, - {"Alan", "Chung", "Green", new Integer(838), Boolean.FALSE}, - {"Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE}, - {"Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE}, - {"Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE}, - {"James", "Gosling", "Pink", new Integer(21), Boolean.FALSE}, - {"David", "Karlton", "Red", new Integer(1), Boolean.FALSE}, - {"Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE}, - {"Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE}, - {"Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE}, - {"Dave", "Moore", "Green", new Integer(88), Boolean.FALSE}, - {"Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE}, - {"Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE}, - {"Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE}, - {"Chester", "Rose", "Black", new Integer(0), Boolean.FALSE}, - {"Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE}, - {"Georges", "Saab", "Red", new Integer(4), Boolean.FALSE}, - {"Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE}, - {"Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE}, - {"Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE} + { "Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE }, + { "Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE }, + { "Alan", "Chung", "Green", new Integer(838), Boolean.FALSE }, + { "Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE }, + { "Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE }, + { "Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE }, + { "James", "Gosling", "Pink", new Integer(21), Boolean.FALSE }, + { "David", "Karlton", "Red", new Integer(1), Boolean.FALSE }, + { "Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE }, + { "Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE }, + { "Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE }, + { "Dave", "Moore", "Green", new Integer(88), Boolean.FALSE }, + { "Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE }, + { "Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE }, + { "Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE }, + { "Chester", "Rose", "Black", new Integer(0), Boolean.FALSE }, + { "Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE }, + { "Georges", "Saab", "Red", new Integer(4), Boolean.FALSE }, + { "Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE }, + { "Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE }, + { "Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE } }; // Create a model of the data. + @SuppressWarnings("serial") TableModel dataModel = new AbstractTableModel() { // These methods always need to be implemented. - public int getColumnCount() { return names.length; } - public int getRowCount() { return data.length;} - public Object getValueAt(int row, int col) {return data[row][col];} + + public int getColumnCount() { + return names.length; + } + + public int getRowCount() { + return data.length; + } + + public Object getValueAt(int row, int col) { + return data[row][col]; + } // The default implementations of these methods in // AbstractTableModel would work, but we can refine them. - public String getColumnName(int column) {return names[column];} - public Class getColumnClass(int c) {return getValueAt(0, c).getClass();} - public boolean isCellEditable(int row, int col) {return true;} + @Override + public String getColumnName(int column) { + return names[column]; + } + + @Override + public Class getColumnClass(int c) { + return getValueAt(0, c).getClass(); + } + + @Override + public boolean isCellEditable(int row, int col) { + return true; + } + + @Override public void setValueAt(Object aValue, int row, int column) { System.out.println("Setting value to: " + aValue); data[row][column] = aValue; } - }; + }; // Create the table JTable tableView = new JTable(dataModel); - // Turn off auto-resizing so that we can set column sizes programmatically. - // In this mode, all columns will get their preferred widths, as set blow. + // Turn off auto-resizing so that we can set column sizes + // programmatically. In this mode, all columns will get their preferred + // widths, as set blow. tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Create a combo box to show that you can use one in a table. @@ -123,15 +152,18 @@ public class TableExample4 { colorColumn.setCellEditor(new DefaultCellEditor(comboBox)); // Set a pink background and tooltip for the Color column renderer. - DefaultTableCellRenderer colorColumnRenderer = new DefaultTableCellRenderer(); + DefaultTableCellRenderer colorColumnRenderer = + new DefaultTableCellRenderer(); colorColumnRenderer.setBackground(Color.pink); colorColumnRenderer.setToolTipText("Click for combo box"); colorColumn.setCellRenderer(colorColumnRenderer); // Set a tooltip for the header of the colors column. TableCellRenderer headerRenderer = colorColumn.getHeaderRenderer(); - if (headerRenderer instanceof DefaultTableCellRenderer) - ((DefaultTableCellRenderer)headerRenderer).setToolTipText("Hi Mom!"); + if (headerRenderer instanceof DefaultTableCellRenderer) { + ((DefaultTableCellRenderer) headerRenderer).setToolTipText( + "Hi Mom!"); + } // Set the width of the "Vegetarian" column. TableColumn vegetarianColumn = tableView.getColumn("Vegetarian"); @@ -139,9 +171,14 @@ public class TableExample4 { // Show the values in the "Favorite Number" column in different colors. TableColumn numbersColumn = tableView.getColumn("Favorite Number"); - DefaultTableCellRenderer numberColumnRenderer = new DefaultTableCellRenderer() { + @SuppressWarnings("serial") + DefaultTableCellRenderer numberColumnRenderer + = new DefaultTableCellRenderer() { + + @Override public void setValue(Object value) { - int cellValue = (value instanceof Number) ? ((Number)value).intValue() : 0; + int cellValue = (value instanceof Number) ? ((Number) value). + intValue() : 0; setForeground((cellValue > 30) ? Color.black : Color.red); setText((value == null) ? "" : value.toString()); } @@ -160,6 +197,19 @@ public class TableExample4 { } public static void main(String[] args) { + // Trying to set Nimbus look and feel + try { + for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (Exception ex) { + Logger.getLogger(TableExample4.class.getName()).log(Level.SEVERE, + "Failed to apply Nimbus look and feel", ex); + } + new TableExample4(); } } diff --git a/src/share/demo/jfc/TableExample/TableMap.java b/src/share/demo/jfc/TableExample/TableMap.java index a6c61df7137c2849f0d8827476920bb77b6a24fb..2511397fec19a67d4d6ea0d3377cd62daa321557 100644 --- a/src/share/demo/jfc/TableExample/TableMap.java +++ b/src/share/demo/jfc/TableExample/TableMap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ /** * In a chain of data manipulators some behaviour is common. TableMap @@ -41,32 +39,34 @@ * a TableMap which has not been subclassed into a chain of table filters * should have no effect. * - * @author Philip Milne */ - + * @author Philip Milne + */ import javax.swing.table.*; import javax.swing.event.TableModelListener; import javax.swing.event.TableModelEvent; -public class TableMap extends AbstractTableModel implements TableModelListener -{ + +@SuppressWarnings("serial") +public class TableMap extends AbstractTableModel implements TableModelListener { + protected TableModel model; - public TableModel getModel() { + public TableModel getModel() { return model; } - public void setModel(TableModel model) { + public void setModel(TableModel model) { this.model = model; model.addTableModelListener(this); } // By default, Implement TableModel by forwarding all messages // to the model. - public Object getValueAt(int aRow, int aColumn) { return model.getValueAt(aRow, aColumn); } + @Override public void setValueAt(Object aValue, int aRow, int aColumn) { model.setValueAt(aValue, aRow, aColumn); } @@ -79,16 +79,19 @@ public class TableMap extends AbstractTableModel implements TableModelListener return (model == null) ? 0 : model.getColumnCount(); } + @Override public String getColumnName(int aColumn) { return model.getColumnName(aColumn); } + @Override public Class getColumnClass(int aColumn) { return model.getColumnClass(aColumn); } + @Override public boolean isCellEditable(int row, int column) { - return model.isCellEditable(row, column); + return model.isCellEditable(row, column); } // // Implementation of the TableModelListener interface, diff --git a/src/share/demo/jfc/TableExample/TableSorter.java b/src/share/demo/jfc/TableExample/TableSorter.java index 8f8b0625dce97ac6064276f59b75766beb6f99fc..625b6f260053b5ed64e429face197ce094464874 100644 --- a/src/share/demo/jfc/TableExample/TableSorter.java +++ b/src/share/demo/jfc/TableExample/TableSorter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,8 +29,19 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - */ + +import javax.swing.table.TableModel; +import javax.swing.event.TableModelEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.InputEvent; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import javax.swing.JTable; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableColumnModel; + /** * A sorter for TableModels. The sorter has a model (conforming to TableModel) @@ -48,46 +59,29 @@ * * @author Philip Milne */ +@SuppressWarnings("serial") +public final class TableSorter extends TableMap { -import java.util.*; - -import javax.swing.table.TableModel; -import javax.swing.event.TableModelEvent; - -// Imports for picking up mouse events from the JTable. - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.InputEvent; -import javax.swing.JTable; -import javax.swing.table.JTableHeader; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; - -public class TableSorter extends TableMap -{ - int indexes[]; - Vector sortingColumns = new Vector(); - boolean ascending = true; + int indexes[]; + List sortingColumns = new ArrayList(); + boolean ascending = true; int compares; - public TableSorter() - { + public TableSorter() { indexes = new int[0]; // For consistency. } - public TableSorter(TableModel model) - { + public TableSorter(TableModel model) { setModel(model); } + @Override public void setModel(TableModel model) { super.setModel(model); reallocateIndexes(); } - public int compareRowsByColumn(int row1, int row2, int column) - { + public int compareRowsByColumn(int row1, int row2, int column) { Class type = model.getColumnClass(column); TableModel data = model; @@ -99,104 +93,100 @@ public class TableSorter extends TableMap // If both values are null return 0 if (o1 == null && o2 == null) { return 0; - } - else if (o1 == null) { // Define null less than everything. + } else if (o1 == null) { // Define null less than everything. return -1; - } - else if (o2 == null) { + } else if (o2 == null) { return 1; } -/* We copy all returned values from the getValue call in case -an optimised model is reusing one object to return many values. -The Number subclasses in the JDK are immutable and so will not be used in -this way but other subclasses of Number might want to do this to save -space and avoid unnecessary heap allocation. -*/ - if (type.getSuperclass() == java.lang.Number.class) - { - Number n1 = (Number)data.getValueAt(row1, column); - double d1 = n1.doubleValue(); - Number n2 = (Number)data.getValueAt(row2, column); - double d2 = n2.doubleValue(); - - if (d1 < d2) - return -1; - else if (d1 > d2) - return 1; - else - return 0; + /* We copy all returned values from the getValue call in case + an optimised model is reusing one object to return many values. + The Number subclasses in the JDK are immutable and so will not be used + in this way but other subclasses of Number might want to do this to save + space and avoid unnecessary heap allocation. + */ + if (type.getSuperclass() == java.lang.Number.class) { + Number n1 = (Number) data.getValueAt(row1, column); + double d1 = n1.doubleValue(); + Number n2 = (Number) data.getValueAt(row2, column); + double d2 = n2.doubleValue(); + + if (d1 < d2) { + return -1; + } else if (d1 > d2) { + return 1; + } else { + return 0; } - else if (type == java.util.Date.class) - { - Date d1 = (Date)data.getValueAt(row1, column); - long n1 = d1.getTime(); - Date d2 = (Date)data.getValueAt(row2, column); - long n2 = d2.getTime(); - - if (n1 < n2) - return -1; - else if (n1 > n2) - return 1; - else return 0; + } else if (type == java.util.Date.class) { + Date d1 = (Date) data.getValueAt(row1, column); + long n1 = d1.getTime(); + Date d2 = (Date) data.getValueAt(row2, column); + long n2 = d2.getTime(); + + if (n1 < n2) { + return -1; + } else if (n1 > n2) { + return 1; + } else { + return 0; } - else if (type == String.class) - { - String s1 = (String)data.getValueAt(row1, column); - String s2 = (String)data.getValueAt(row2, column); - int result = s1.compareTo(s2); - - if (result < 0) - return -1; - else if (result > 0) - return 1; - else return 0; + } else if (type == String.class) { + String s1 = (String) data.getValueAt(row1, column); + String s2 = (String) data.getValueAt(row2, column); + int result = s1.compareTo(s2); + + if (result < 0) { + return -1; + } else if (result > 0) { + return 1; + } else { + return 0; } - else if (type == Boolean.class) + } else if (type == Boolean.class) { + Boolean bool1 = (Boolean) data.getValueAt(row1, column); + boolean b1 = bool1.booleanValue(); + Boolean bool2 = (Boolean) data.getValueAt(row2, column); + boolean b2 = bool2.booleanValue(); + + if (b1 == b2) { + return 0; + } else if (b1) // Define false < true { - Boolean bool1 = (Boolean)data.getValueAt(row1, column); - boolean b1 = bool1.booleanValue(); - Boolean bool2 = (Boolean)data.getValueAt(row2, column); - boolean b2 = bool2.booleanValue(); - - if (b1 == b2) - return 0; - else if (b1) // Define false < true - return 1; - else - return -1; + return 1; + } else { + return -1; } - else - { - Object v1 = data.getValueAt(row1, column); - String s1 = v1.toString(); - Object v2 = data.getValueAt(row2, column); - String s2 = v2.toString(); - int result = s1.compareTo(s2); - - if (result < 0) - return -1; - else if (result > 0) - return 1; - else return 0; + } else { + Object v1 = data.getValueAt(row1, column); + String s1 = v1.toString(); + Object v2 = data.getValueAt(row2, column); + String s2 = v2.toString(); + int result = s1.compareTo(s2); + + if (result < 0) { + return -1; + } else if (result > 0) { + return 1; + } else { + return 0; } + } } - public int compare(int row1, int row2) - { + public int compare(int row1, int row2) { compares++; - for(int level = 0; level < sortingColumns.size(); level++) - { - Integer column = (Integer)sortingColumns.elementAt(level); - int result = compareRowsByColumn(row1, row2, column.intValue()); - if (result != 0) - return ascending ? result : -result; + for (int level = 0; level < sortingColumns.size(); level++) { + Integer column = sortingColumns.get(level); + int result = compareRowsByColumn(row1, row2, column.intValue()); + if (result != 0) { + return ascending ? result : -result; } + } return 0; } - public void reallocateIndexes() - { + public void reallocateIndexes() { int rowCount = model.getRowCount(); // Set up a new array of indexes with the right number of elements @@ -204,39 +194,38 @@ space and avoid unnecessary heap allocation. indexes = new int[rowCount]; // Initialise with the identity mapping. - for(int row = 0; row < rowCount; row++) + for (int row = 0; row < rowCount; row++) { indexes[row] = row; + } } - public void tableChanged(TableModelEvent e) - { + @Override + public void tableChanged(TableModelEvent e) { System.out.println("Sorter: tableChanged"); reallocateIndexes(); super.tableChanged(e); } - public void checkModel() - { + public void checkModel() { if (indexes.length != model.getRowCount()) { System.err.println("Sorter not informed of a change in model."); } } - public void sort(Object sender) - { + public void sort(Object sender) { checkModel(); compares = 0; // n2sort(); // qsort(0, indexes.length-1); - shuttlesort((int[])indexes.clone(), indexes, 0, indexes.length); - System.out.println("Compares: "+compares); + shuttlesort(indexes.clone(), indexes, 0, indexes.length); + System.out.println("Compares: " + compares); } public void n2sort() { - for(int i = 0; i < getRowCount(); i++) { - for(int j = i+1; j < getRowCount(); j++) { + for (int i = 0; i < getRowCount(); i++) { + for (int j = i + 1; j < getRowCount(); j++) { if (compare(indexes[i], indexes[j]) == -1) { swap(i, j); } @@ -255,7 +244,7 @@ space and avoid unnecessary heap allocation. if (high - low < 2) { return; } - int middle = (low + high)/2; + int middle = (low + high) / 2; shuttlesort(to, from, low, middle); shuttlesort(to, from, middle, high); @@ -277,20 +266,17 @@ space and avoid unnecessary heap allocation. find out how the performance drops to Nlog(N) as the initial order diminishes - it may drop very quickly. */ - if (high - low >= 4 && compare(from[middle-1], from[middle]) <= 0) { - for (int i = low; i < high; i++) { - to[i] = from[i]; - } + if (high - low >= 4 && compare(from[middle - 1], from[middle]) <= 0) { + System.arraycopy(from, low, to, low, high - low); return; } // A normal merge. - for(int i = low; i < high; i++) { + for (int i = low; i < high; i++) { if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) { to[i] = from[p++]; - } - else { + } else { to[i] = from[q++]; } } @@ -304,15 +290,14 @@ space and avoid unnecessary heap allocation. // The mapping only affects the contents of the data rows. // Pass all requests to these rows through the mapping array: "indexes". - - public Object getValueAt(int aRow, int aColumn) - { + @Override + public Object getValueAt(int aRow, int aColumn) { checkModel(); return model.getValueAt(indexes[aRow], aColumn); } - public void setValueAt(Object aValue, int aRow, int aColumn) - { + @Override + public void setValueAt(Object aValue, int aRow, int aColumn) { checkModel(); model.setValueAt(aValue, indexes[aRow], aColumn); } @@ -323,8 +308,8 @@ space and avoid unnecessary heap allocation. public void sortByColumn(int column, boolean ascending) { this.ascending = ascending; - sortingColumns.removeAllElements(); - sortingColumns.addElement(new Integer(column)); + sortingColumns.clear(); + sortingColumns.add(column); sort(this); super.tableChanged(new TableModelEvent(this)); } @@ -337,22 +322,21 @@ space and avoid unnecessary heap allocation. final JTable tableView = table; tableView.setColumnSelectionAllowed(false); MouseAdapter listMouseListener = new MouseAdapter() { + + @Override public void mouseClicked(MouseEvent e) { TableColumnModel columnModel = tableView.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = tableView.convertColumnIndexToModel(viewColumn); - if(e.getClickCount() == 1 && column != -1) { + if (e.getClickCount() == 1 && column != -1) { System.out.println("Sorting ..."); - int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK; + int shiftPressed = e.getModifiers() & InputEvent.SHIFT_MASK; boolean ascending = (shiftPressed == 0); sorter.sortByColumn(column, ascending); } - } - }; + } + }; JTableHeader th = tableView.getTableHeader(); th.addMouseListener(listMouseListener); } - - - } diff --git a/src/share/demo/jfc/TransparentRuler/README.txt b/src/share/demo/jfc/TransparentRuler/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..ddcf9de1d5e0e7837a71e6789694fa04452e7ab9 --- /dev/null +++ b/src/share/demo/jfc/TransparentRuler/README.txt @@ -0,0 +1,14 @@ + +To run the Ruler demo: + + java -jar Ruler.jar + +These instructions assume that this installation's version of the java +command is in your path. If it isn't, then you should either +specify the complete path to the java command or update your +PATH environment variable as described in the installation +instructions for the Java(TM) SE Development Kit. + +KNOWN ISSUES: +Context menu is clipped with the window shape. The issues are: +CR 7027486 JPopupMenu doesn't take window shape into account diff --git a/src/share/demo/jfc/TransparentRuler/transparentruler/Ruler.java b/src/share/demo/jfc/TransparentRuler/transparentruler/Ruler.java new file mode 100644 index 0000000000000000000000000000000000000000..707151f971987eeedac8a8a3be4dcad41ef5cdcb --- /dev/null +++ b/src/share/demo/jfc/TransparentRuler/transparentruler/Ruler.java @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package transparentruler; + + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsDevice; +import java.awt.GraphicsDevice.WindowTranslucency; +import java.awt.GraphicsEnvironment; +import java.awt.event.ActionEvent; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.geom.Path2D.Float; +import java.lang.reflect.InvocationTargetException; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JFrame; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; + + +/** + * This sample demonstrates shaped and translucent window feature. + * @author Alexander Kouznetsov + */ +@SuppressWarnings("serial") +public class Ruler extends JFrame { + + private static final Color BACKGROUND = Color.RED; + private static final Color FOREGROUND = Color.WHITE; + private static final int OPACITY = 180; + private static final int W = 70; + private static final int F_HEIGHT = 400; + private static final int F_WIDTH = (int) (F_HEIGHT * 1.618 + 0.5); + + private static void checkTranslucencyMode(WindowTranslucency arg) { + GraphicsEnvironment ge = + GraphicsEnvironment.getLocalGraphicsEnvironment(); + GraphicsDevice gd = ge.getDefaultScreenDevice(); + if (!gd.isWindowTranslucencySupported(arg)) { + System.err.println("'" + arg + + "' translucency mode isn't supported."); + System.exit(-1); + } + } + private final ComponentAdapter componentListener = new ComponentAdapter() { + + /** + * Applies the shape to window. It is recommended to apply shape in + * componentResized() method + */ + @Override + public void componentResized(ComponentEvent e) { + int h = getHeight(); + int w = getWidth(); + float a = (float) Math.hypot(h, w); + Float path = new java.awt.geom.Path2D.Float(); + path.moveTo(0, 0); + path.lineTo(w, 0); + path.lineTo(0, h); + path.closePath(); + path.moveTo(W, W); + path.lineTo(W, h - W * (a + h) / w); + path.lineTo(w - W * (a + w) / h, W); + path.closePath(); + setShape(path); + } + }; + private final Action exitAction = new AbstractAction("Exit") { + + { + putValue(Action.MNEMONIC_KEY, KeyEvent.VK_X); + } + + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + }; + private final JPopupMenu jPopupMenu = new JPopupMenu(); + + { + jPopupMenu.add(new JMenuItem(exitAction)); + } + /** + * Implements mouse-related behavior: window dragging and popup menu + * invocation + */ + private final MouseAdapter mouseListener = new MouseAdapter() { + + int x, y; + + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + x = e.getX(); + y = e.getY(); + } + } + + @Override + public void mouseDragged(MouseEvent e) { + if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { + setLocation(e.getXOnScreen() - x, e.getYOnScreen() - y); + } + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.isPopupTrigger()) { + jPopupMenu.show(getContentPane(), e.getX(), e.getY()); + } + } + }; + /** + * Implements keyboard navigation. Arrows move by 5 pixels, Ctrl + arrows + * move by 50 pixels, Alt + arrows move by 1 pixel. + * Esc exits the application. + */ + private final KeyAdapter keyboardListener = new KeyAdapter() { + + @Override + public void keyPressed(KeyEvent e) { + int step = e.isControlDown() ? 50 : e.isAltDown() ? 1 : 5; + switch (e.getKeyCode()) { + case KeyEvent.VK_LEFT: + setLocation(getX() - step, getY()); + break; + case KeyEvent.VK_RIGHT: + setLocation(getX() + step, getY()); + break; + case KeyEvent.VK_UP: + setLocation(getX(), getY() - step); + break; + case KeyEvent.VK_DOWN: + setLocation(getX(), getY() + step); + break; + case KeyEvent.VK_ESCAPE: + exitAction.actionPerformed(null); + } + } + }; + + public Ruler() { + setUndecorated(true); + + // Enables perpixel translucency + setBackground(new Color(BACKGROUND.getRed(), BACKGROUND.getGreen(), + BACKGROUND.getBlue(), OPACITY)); + + addMouseListener(mouseListener); + addMouseMotionListener(mouseListener); + addComponentListener(componentListener); + addKeyListener(keyboardListener); + setContentPane(new JPanel() { + + @Override + protected void paintComponent(Graphics g) { + Graphics gg = g.create(); + int w = getWidth(); + int h = getHeight(); + int hh = gg.getFontMetrics().getAscent(); + gg.setColor(FOREGROUND); + for (int x = 0; x < w * (h - 8) / h - 5; x += 5) { + boolean hi = x % 50 == 0; + gg.drawLine(x + 5, 0, x + 5, + hi ? 20 : (x % 25 == 0 ? 13 : 8)); + if (hi) { + String number = Integer.toString(x); + int ww = gg.getFontMetrics().stringWidth(number); + gg.drawString(number, x + 5 - ww / 2, 20 + hh); + } + } + gg.dispose(); + } + }); + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + setSize(F_WIDTH, F_HEIGHT); + setLocationByPlatform(true); + } + + /** + * @param args the command line arguments are ignored + */ + public static void main(String[] args) throws InterruptedException, InvocationTargetException { + + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + checkTranslucencyMode(WindowTranslucency.PERPIXEL_TRANSLUCENT); + checkTranslucencyMode(WindowTranslucency.PERPIXEL_TRANSPARENT); + + Ruler ruler = new Ruler(); + ruler.setVisible(true); + } + }); + } +} diff --git a/src/share/demo/nbproject/jfc/TransparentRuler/build.properties b/src/share/demo/nbproject/jfc/TransparentRuler/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..b1b2ef89b820b67eab5422b10ec0c9f495c34d9b --- /dev/null +++ b/src/share/demo/nbproject/jfc/TransparentRuler/build.properties @@ -0,0 +1,22 @@ +main.dir=${basedir}/../../../jfc/TransparentRuler + +src.dir=${main.dir}/src + +build.dir=build +classes.dir=${build.dir}/classes +jar=${main.dir}/TransparentRuler.jar +javadoc.dir=${build.dir}/javadoc + +build.sysclasspath=ignore +# E.g.: cp=lib/x.jar:lib/y.jar +cp= +extra.run.cp= + +main.class=transparentruler.Ruler + +run.cp=${cp}:${classes.dir}:${extra.run.cp} + +debug=true +deprecation=false + +nbjdk.home=${basedir}/../../../.. diff --git a/src/share/demo/nbproject/jfc/TransparentRuler/build.xml b/src/share/demo/nbproject/jfc/TransparentRuler/build.xml new file mode 100644 index 0000000000000000000000000000000000000000..8db759a30c0c6d03dabe1803935611155cfe82bc --- /dev/null +++ b/src/share/demo/nbproject/jfc/TransparentRuler/build.xml @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set property 'main.class' (e.g. in build.properties) + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/file-targets.xml b/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/file-targets.xml new file mode 100644 index 0000000000000000000000000000000000000000..9d750841e3b5fdc3b80755263baa4f1a67ce4160 --- /dev/null +++ b/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/file-targets.xml @@ -0,0 +1,46 @@ + + + + + + + + + + Must set property 'includes' + + + + + + + diff --git a/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/jdk.xml b/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/jdk.xml new file mode 100644 index 0000000000000000000000000000000000000000..3690ef0e8f8674020f02765a6c1c1797dd0a76c1 --- /dev/null +++ b/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/jdk.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/netbeans-targets.xml b/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/netbeans-targets.xml new file mode 100644 index 0000000000000000000000000000000000000000..84a0e9b3c5e0fc7ded178a17f5da786399bc5e4c --- /dev/null +++ b/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/netbeans-targets.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/project.xml b/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..ecc07bc52b91d2c540438192922f72ab751466f8 --- /dev/null +++ b/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/project.xml @@ -0,0 +1,173 @@ + + + + + + org.netbeans.modules.ant.freeform + + + TransparentRuler + + user.build.properties + build.properties + ${nbjdk.home}/jre/lib/rt.jar + + + + + ${main.dir} + + + + java + ${src.dir} + + + ${build.dir} + + + + + jar + + + clean + + + clean + jar + + + run + + + + show-javadoc + + + + debug + + + + compile-selected + + includes + ${src.dir} + \.java$ + relative-path + + , + + + + + run + + main.class + ${src.dir} + \.java$ + java-name + + + + + + + + debug + + main.class + ${src.dir} + \.java$ + java-name + + + + + + + + debug-fix + + class + ${src.dir} + \.java$ + relative-path-noext + + + + + + + + jar + ${jar} + jar + clean + + + + + + ${src.dir} + + + ${main.dir}/README.txt + + + + + + + + + + + + + + + + + ${src.dir} + ${cp} + ${run.cp} + ${nbjdk.bootclasspath} + ${classes.dir} + ${jar} + ${javadoc.dir} + 1.5 + + + + diff --git a/src/share/demo/nbproject/project.xml b/src/share/demo/nbproject/project.xml index 585faf33b000bf3e5eb2b19e039c67f1ccbab32d..43667547ddf2d2ccf8307ce6b0d6e6ddb38c878d 100644 --- a/src/share/demo/nbproject/project.xml +++ b/src/share/demo/nbproject/project.xml @@ -50,6 +50,7 @@ nbproject/jfc/Stylepad nbproject/jfc/SwingApplet nbproject/jfc/TableExample + nbproject/jfc/TransparentRuler nbproject/scripting/jconsole-plugin nbproject/management/FullThreadDump nbproject/management/JTop diff --git a/src/windows/classes/sun/awt/windows/fontconfig.properties b/src/windows/classes/sun/awt/windows/fontconfig.properties index a7f59e52b8d43b8e068aaf7458bbd852c1225231..2a43e6e90d0e388cd4967abd5194aa250792cf15 100644 --- a/src/windows/classes/sun/awt/windows/fontconfig.properties +++ b/src/windows/classes/sun/awt/windows/fontconfig.properties @@ -102,28 +102,28 @@ sansserif.bolditalic.korean=Gulim monospaced.plain.alphabetic=Courier New monospaced.plain.chinese-ms950=MingLiU monospaced.plain.chinese-ms950-extb=MingLiU-ExtB -monospaced.plain.hebrew=David +monospaced.plain.hebrew=Courier New monospaced.plain.japanese=MS Gothic monospaced.plain.korean=GulimChe monospaced.bold.alphabetic=Courier New Bold monospaced.bold.chinese-ms950=PMingLiU monospaced.bold.chinese-ms950-extb=PMingLiU-ExtB -monospaced.bold.hebrew=David Bold +monospaced.bold.hebrew=Courier New Bold monospaced.bold.japanese=MS Gothic monospaced.bold.korean=GulimChe monospaced.italic.alphabetic=Courier New Italic monospaced.italic.chinese-ms950=PMingLiU monospaced.italic.chinese-ms950-extb=PMingLiU-ExtB -monospaced.italic.hebrew=David +monospaced.italic.hebrew=Courier New monospaced.italic.japanese=MS Gothic monospaced.italic.korean=GulimChe monospaced.bolditalic.alphabetic=Courier New Bold Italic monospaced.bolditalic.chinese-ms950=PMingLiU monospaced.bolditalic.chinese-ms950-extb=PMingLiU-ExtB -monospaced.bolditalic.hebrew=David Bold +monospaced.bolditalic.hebrew=Courier New Bold monospaced.bolditalic.japanese=MS Gothic monospaced.bolditalic.korean=GulimChe diff --git a/test/java/lang/reflect/Method/InheritedMethods.java b/test/java/lang/reflect/Method/InheritedMethods.java index 9da23d69832fd845749a4037564c912e849ed306..ebfdc0823cda9a1089bc834e6d2c5f127e576bba 100644 --- a/test/java/lang/reflect/Method/InheritedMethods.java +++ b/test/java/lang/reflect/Method/InheritedMethods.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2011, Oracle and/or its affiliates. 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,17 +23,14 @@ /* @test @bug 4471738 - @ignore until 6825739 fixed @summary Failure to properly traverse class hierarchy in Class.getMethod() */ import java.lang.reflect.Method; import java.util.Collection; import java.util.List; -import javax.swing.JPanel; -import javax.swing.JLabel; -public class InheritedMethods extends JPanel { +public class InheritedMethods { public static void main(String[] args) throws Exception { new InheritedMethods(); } InheritedMethods() throws Exception { Class c = Foo.class; @@ -41,7 +38,6 @@ public class InheritedMethods extends JPanel { if (m.getDeclaringClass() != java.util.List.class) { throw new RuntimeException("TEST FAILED"); } - add(new JLabel("Test")); } interface Foo extends List { } } diff --git a/test/javax/sound/sampled/Clip/ClipSetPos.java b/test/javax/sound/sampled/Clip/ClipSetPos.java index 2968c9b735f6c13e4873b189a464aaf2645dcfd8..715274fe65fcfabfebe527c5c9bb254347125d39 100644 --- a/test/javax/sound/sampled/Clip/ClipSetPos.java +++ b/test/javax/sound/sampled/Clip/ClipSetPos.java @@ -33,6 +33,7 @@ import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; +import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; public class ClipSetPos { @@ -48,12 +49,16 @@ public class ClipSetPos { boolean testPassed = true; Clip clip = null; try { - clip = AudioSystem.getClip(); + clip = (Clip)AudioSystem.getLine(new DataLine.Info(Clip.class, audioFormat)); clip.open(audioFormat, dataBuffer, 0, dataBuffer.length); } catch (LineUnavailableException ex) { log(ex); log("Cannot test (this is not failure)"); return; + } catch (IllegalArgumentException ex) { + log(ex); + log("Cannot test (this is not failure)"); + return; } log("clip: " + clip.getClass().getName()); diff --git a/test/javax/swing/border/Test4856008.java b/test/javax/swing/border/Test4856008.java index a98e474fbaf357c51e613fd4faa1ccb6c461c320..7c0da08e9309d8d79d45630c0fa18e09aec9987b 100644 --- a/test/javax/swing/border/Test4856008.java +++ b/test/javax/swing/border/Test4856008.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2011, Oracle and/or its affiliates. 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 4856008 + * @bug 4856008 7025987 * @summary Tests border insets * @author Sergey Malenkov */ @@ -59,6 +59,7 @@ import javax.swing.plaf.basic.BasicBorders; import javax.swing.plaf.basic.BasicToolBarUI; import javax.swing.plaf.metal.MetalBorders; import javax.swing.plaf.metal.MetalComboBoxEditor; +import javax.swing.plaf.nimbus.NimbusLookAndFeel; import sun.swing.plaf.synth.SynthFileChooserUI; @@ -134,6 +135,9 @@ public class Test4856008 { //+ SynthFileChooserUI.UIBorder: new SynthFileChooser().getUIBorder(), + + //+ LoweredBorder: + new NimbusLookAndFeel().getDefaults().getBorder("TitledBorder.border"), }; public static void main(String[] args) { diff --git a/test/javax/swing/border/Test6978482.java b/test/javax/swing/border/Test6978482.java index 8bf6b9b33d4aa6681357b1071ec3238664db41ab..804970f2210056cc42e6a2170d9ac0c00d1eea24 100644 --- a/test/javax/swing/border/Test6978482.java +++ b/test/javax/swing/border/Test6978482.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2011, Oracle and/or its affiliates. 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 6978482 + * @bug 6978482 7025987 * @summary Tests unchecked casts * @author Sergey Malenkov */ @@ -58,6 +58,7 @@ import javax.swing.plaf.basic.BasicBorders; import javax.swing.plaf.basic.BasicToolBarUI; import javax.swing.plaf.metal.MetalBorders; import javax.swing.plaf.metal.MetalComboBoxEditor; +import javax.swing.plaf.nimbus.NimbusLookAndFeel; import sun.swing.plaf.synth.SynthFileChooserUI; @@ -132,6 +133,9 @@ public class Test6978482 { //+ SynthFileChooserUI.UIBorder: new SynthFileChooser().getUIBorder(), + + //+ LoweredBorder: + new NimbusLookAndFeel().getDefaults().getBorder("TitledBorder.border"), }; public static void main(String[] args) {

Bubble Sort Bidirectional Bubble Sort