From 7690c18be2a1fb727805ef0e520ba992b040268a Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 19 Jun 2008 18:03:43 +0400 Subject: [PATCH 01/45] 4114658: DOC: Unspecified behaviour for java.beans.PropertyEditorSupport Reviewed-by: peterz, loneid --- .../classes/java/beans/PropertyEditor.java | 17 ++++++------ .../java/beans/PropertyEditorSupport.java | 26 ++++++++++++++----- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/jdk/src/share/classes/java/beans/PropertyEditor.java b/jdk/src/share/classes/java/beans/PropertyEditor.java index b6ddf415354..965775898a8 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditor.java +++ b/jdk/src/share/classes/java/beans/PropertyEditor.java @@ -204,20 +204,21 @@ public interface PropertyEditor { //---------------------------------------------------------------------- /** - * Register a listener for the PropertyChange event. When a - * PropertyEditor changes its value it should fire a PropertyChange - * event on all registered PropertyChangeListeners, specifying the - * null value for the property name and itself as the source. + * Adds a listener for the value change. + * When the property editor changes its value + * it should fire a {@link PropertyChangeEvent} + * on all registered {@link PropertyChangeListener}s, + * specifying the {@code null} value for the property name + * and itself as the source. * - * @param listener An object to be invoked when a PropertyChange - * event is fired. + * @param listener the {@link PropertyChangeListener} to add */ void addPropertyChangeListener(PropertyChangeListener listener); /** - * Remove a listener for the PropertyChange event. + * Removes a listener for the value change. * - * @param listener The PropertyChange listener to be removed. + * @param listener the {@link PropertyChangeListener} to remove */ void removePropertyChangeListener(PropertyChangeListener listener); diff --git a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java index 12f07c06bb1..57fddf04365 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java +++ b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java @@ -233,11 +233,20 @@ public class PropertyEditorSupport implements PropertyEditor { //---------------------------------------------------------------------- /** - * Register a listener for the PropertyChange event. The class will - * fire a PropertyChange value whenever the value is updated. + * Adds a listener for the value change. + * When the property editor changes its value + * it should fire a {@link PropertyChangeEvent} + * on all registered {@link PropertyChangeListener}s, + * specifying the {@code null} value for the property name. + * If the source property is set, + * it should be used as the source of the event. + *

+ * The same listener object may be added more than once, + * and will be called as many times as it is added. + * If {@code listener} is {@code null}, + * no exception is thrown and no action is taken. * - * @param listener An object to be invoked when a PropertyChange - * event is fired. + * @param listener the {@link PropertyChangeListener} to add */ public synchronized void addPropertyChangeListener( PropertyChangeListener listener) { @@ -248,9 +257,14 @@ public class PropertyEditorSupport implements PropertyEditor { } /** - * Remove a listener for the PropertyChange event. + * Removes a listener for the value change. + *

+ * If the same listener was added more than once, + * it will be notified one less time after being removed. + * If {@code listener} is {@code null}, or was never added, + * no exception is thrown and no action is taken. * - * @param listener The PropertyChange listener to be removed. + * @param listener the {@link PropertyChangeListener} to remove */ public synchronized void removePropertyChangeListener( PropertyChangeListener listener) { From 762ea5875b8d38a67aa2e524b4756fdfb02c115e Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Mon, 23 Jun 2008 15:21:37 -0400 Subject: [PATCH 02/45] 6623943: javax.swing.TimerQueue's thread occasionally fails to start Reviewed-by: alexp --- .../share/classes/javax/swing/JApplet.java | 5 +- .../share/classes/javax/swing/TimerQueue.java | 67 ++++++++++--------- 2 files changed, 35 insertions(+), 37 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/JApplet.java b/jdk/src/share/classes/javax/swing/JApplet.java index b9b5b2506b9..47f792a942d 100644 --- a/jdk/src/share/classes/javax/swing/JApplet.java +++ b/jdk/src/share/classes/javax/swing/JApplet.java @@ -131,10 +131,7 @@ public class JApplet extends Applet implements Accessible, // Check the timerQ and restart if necessary. TimerQueue q = TimerQueue.sharedInstance(); if(q != null) { - synchronized(q) { - if(!q.running) - q.start(); - } + q.startIfNeeded(); } /* Workaround for bug 4155072. The shared double buffer image diff --git a/jdk/src/share/classes/javax/swing/TimerQueue.java b/jdk/src/share/classes/javax/swing/TimerQueue.java index 2121939011f..1f694d1c820 100644 --- a/jdk/src/share/classes/javax/swing/TimerQueue.java +++ b/jdk/src/share/classes/javax/swing/TimerQueue.java @@ -31,6 +31,7 @@ package javax.swing; import java.util.*; import java.util.concurrent.*; +import java.util.concurrent.locks.*; import java.util.concurrent.atomic.AtomicLong; import sun.awt.AppContext; @@ -52,7 +53,8 @@ class TimerQueue implements Runnable new StringBuffer("TimerQueue.expiredTimersKey"); private final DelayQueue queue; - volatile boolean running; + private volatile boolean running; + private final Lock runningLock; /* Lock object used in place of class object for synchronization. * (4187686) @@ -69,7 +71,8 @@ class TimerQueue implements Runnable super(); queue = new DelayQueue(); // Now start the TimerQueue thread. - start(); + runningLock = new ReentrantLock(); + startIfNeeded(); } @@ -87,33 +90,30 @@ class TimerQueue implements Runnable } - synchronized void start() { - if (running) { - throw new RuntimeException("Can't start a TimerQueue " + - "that is already running"); - } - else { - final ThreadGroup threadGroup = - AppContext.getAppContext().getThreadGroup(); - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - Thread timerThread = new Thread(threadGroup, TimerQueue.this, - "TimerQueue"); - timerThread.setDaemon(true); - timerThread.setPriority(Thread.NORM_PRIORITY); - timerThread.start(); - return null; - } - }); - running = true; + void startIfNeeded() { + if (! running) { + runningLock.lock(); + try { + final ThreadGroup threadGroup = + AppContext.getAppContext().getThreadGroup(); + java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Object run() { + Thread timerThread = new Thread(threadGroup, TimerQueue.this, + "TimerQueue"); + timerThread.setDaemon(true); + timerThread.setPriority(Thread.NORM_PRIORITY); + timerThread.start(); + return null; + } + }); + running = true; + } finally { + runningLock.unlock(); + } } } - synchronized void stop() { - running = false; - } - void addTimer(Timer timer, long delayMillis) { timer.getLock().lock(); try { @@ -164,6 +164,7 @@ class TimerQueue implements Runnable public void run() { + runningLock.lock(); try { while (running) { try { @@ -195,14 +196,14 @@ class TimerQueue implements Runnable } } catch (ThreadDeath td) { - synchronized (this) { - running = false; - // Mark all the timers we contain as not being queued. - for (DelayedTimer delayedTimer : queue) { - delayedTimer.getTimer().cancelEvent(); - } - throw td; + // Mark all the timers we contain as not being queued. + for (DelayedTimer delayedTimer : queue) { + delayedTimer.getTimer().cancelEvent(); } + throw td; + } finally { + running = false; + runningLock.unlock(); } } From 9d7b3f41e04e5a8d75d948e22b79c49b45fde494 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 26 Jun 2008 15:11:04 +0400 Subject: [PATCH 03/45] 6718964: Swing border tests should be open source Reviewed-by: peterz --- jdk/test/javax/swing/border/Test4120351.java | 43 ++++++++++++ jdk/test/javax/swing/border/Test4124729.java | 38 ++++++++++ jdk/test/javax/swing/border/Test4243289.html | 9 +++ jdk/test/javax/swing/border/Test4243289.java | 52 ++++++++++++++ jdk/test/javax/swing/border/Test4247606.html | 10 +++ jdk/test/javax/swing/border/Test4247606.java | 62 +++++++++++++++++ jdk/test/javax/swing/border/Test4252164.html | 10 +++ jdk/test/javax/swing/border/Test4252164.java | 73 ++++++++++++++++++++ jdk/test/javax/swing/border/Test6461042.java | 57 +++++++++++++++ 9 files changed, 354 insertions(+) create mode 100644 jdk/test/javax/swing/border/Test4120351.java create mode 100644 jdk/test/javax/swing/border/Test4124729.java create mode 100644 jdk/test/javax/swing/border/Test4243289.html create mode 100644 jdk/test/javax/swing/border/Test4243289.java create mode 100644 jdk/test/javax/swing/border/Test4247606.html create mode 100644 jdk/test/javax/swing/border/Test4247606.java create mode 100644 jdk/test/javax/swing/border/Test4252164.html create mode 100644 jdk/test/javax/swing/border/Test4252164.java create mode 100644 jdk/test/javax/swing/border/Test6461042.java diff --git a/jdk/test/javax/swing/border/Test4120351.java b/jdk/test/javax/swing/border/Test4120351.java new file mode 100644 index 00000000000..1253e638a0e --- /dev/null +++ b/jdk/test/javax/swing/border/Test4120351.java @@ -0,0 +1,43 @@ +/* + * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4120351 + * @summary Tests that the methods createEtchedBorder(int type) and + * createEtchedBorder(int type, Color highlight, Color shadows) are added + * @author Andrey Pikalev + */ + +import java.awt.Color; +import javax.swing.BorderFactory; +import javax.swing.border.EtchedBorder; + +public class Test4120351 { + public static void main(String[] args) { + BorderFactory.createEtchedBorder(EtchedBorder.RAISED); + BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); + BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.BLACK, Color.WHITE); + BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.WHITE, Color.BLACK); + } +} diff --git a/jdk/test/javax/swing/border/Test4124729.java b/jdk/test/javax/swing/border/Test4124729.java new file mode 100644 index 00000000000..d48ce9d1d5f --- /dev/null +++ b/jdk/test/javax/swing/border/Test4124729.java @@ -0,0 +1,38 @@ +/* + * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4124729 + * @summary Test that constrtructor LineBorder(?,?,?) is public + * @author Andrey Pikalev + */ + +import java.awt.Color; +import javax.swing.border.LineBorder; + +public class Test4124729 { + public static void main(String[] args) { + new LineBorder(Color.BLUE, 3, true); + } +} diff --git a/jdk/test/javax/swing/border/Test4243289.html b/jdk/test/javax/swing/border/Test4243289.html new file mode 100644 index 00000000000..9133d99c582 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4243289.html @@ -0,0 +1,9 @@ + + +When applet starts, you'll see a panel with a TitledBorder with title "Panel Title". +If this title is overstriken with the border line, test fails, otherwise it passes. + + + + + diff --git a/jdk/test/javax/swing/border/Test4243289.java b/jdk/test/javax/swing/border/Test4243289.java new file mode 100644 index 00000000000..1c462a85973 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4243289.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4243289 + * @summary Tests that TitledBorder do not draw line through its caption + * @author Peter Zhelezniakov + * @run applet/manual=yesno Test4243289.html + */ + +import java.awt.Font; +import javax.swing.BorderFactory; +import javax.swing.JApplet; +import javax.swing.JPanel; +import javax.swing.border.TitledBorder; + +public class Test4243289 extends JApplet { + public void init() { + Font font = new Font("Dialog", Font.PLAIN, 12); // NON-NLS: the font name + TitledBorder border = BorderFactory.createTitledBorder( + BorderFactory.createEtchedBorder(), + "Panel Title", // NON-NLS: the title of the border + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, + font); + + JPanel panel = new JPanel(); + panel.setBorder(border); + getContentPane().add(panel); + } +} diff --git a/jdk/test/javax/swing/border/Test4247606.html b/jdk/test/javax/swing/border/Test4247606.html new file mode 100644 index 00000000000..d501ab221d6 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4247606.html @@ -0,0 +1,10 @@ + + +If the button do not fit into the titled border bounds +and cover the bottom border's line then test fails. +Otherwise test passes. + + + + + diff --git a/jdk/test/javax/swing/border/Test4247606.java b/jdk/test/javax/swing/border/Test4247606.java new file mode 100644 index 00000000000..b598d4a1b9e --- /dev/null +++ b/jdk/test/javax/swing/border/Test4247606.java @@ -0,0 +1,62 @@ +/* + * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4247606 + * @summary BorderedPane appears wrong with Title Position Below Bottom + * @author Andrey Pikalev + * @run applet/manual=yesno Test4247606.html + */ + +import java.awt.BorderLayout; +import java.awt.Color; +import javax.swing.BorderFactory; +import javax.swing.JApplet; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +public class Test4247606 extends JApplet { + public void init() { + JButton button = new JButton("Button"); // NON-NLS: the button text + button.setBorder(BorderFactory.createLineBorder(Color.red, 1)); + + TitledBorder border = new TitledBorder("Bordered Pane"); // NON-NLS: the panel title + border.setTitlePosition(TitledBorder.BELOW_BOTTOM); + + JPanel panel = create(button, border); + panel.setBackground(Color.green); + + getContentPane().add(create(panel, BorderFactory.createEmptyBorder(10, 10, 10, 10))); + } + + private static JPanel create(JComponent component, Border border) { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(border); + panel.add(component); + return panel; + } +} diff --git a/jdk/test/javax/swing/border/Test4252164.html b/jdk/test/javax/swing/border/Test4252164.html new file mode 100644 index 00000000000..eb436c53fe3 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4252164.html @@ -0,0 +1,10 @@ + + +Please, ensure that rounded border is filled completely. +It should not contain white points inside. +Use Mouse Wheel to change thickness of the border. + + + + + diff --git a/jdk/test/javax/swing/border/Test4252164.java b/jdk/test/javax/swing/border/Test4252164.java new file mode 100644 index 00000000000..a39193fc6f9 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4252164.java @@ -0,0 +1,73 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4252164 + * @summary Tests rounded LineBorder for components + * @author Sergey Malenkov + * @run applet/manual=yesno Test4252164.html + */ + +import java.awt.Color; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import javax.swing.JApplet; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.border.LineBorder; + +public class Test4252164 extends JApplet implements MouseWheelListener { + private int thickness; + private JLabel rounded; + private JLabel straight; + + public void mouseWheelMoved(MouseWheelEvent event) { + update(event.getWheelRotation()); + } + + public void init() { + add(createUI()); + addMouseWheelListener(this); + } + + private JPanel createUI() { + this.rounded = new JLabel("ROUNDED"); // NON-NLS: the label for rounded border + this.straight = new JLabel("STRAIGHT"); // NON-NLS: the label for straight border + + JPanel panel = new JPanel(); + panel.add(this.rounded); + panel.add(this.straight); + + update(10); + + return panel; + } + + private void update(int thickness) { + this.thickness += thickness; + + this.rounded.setBorder(new LineBorder(Color.RED, this.thickness, true)); + this.straight.setBorder(new LineBorder(Color.RED, this.thickness, false)); + } +} diff --git a/jdk/test/javax/swing/border/Test6461042.java b/jdk/test/javax/swing/border/Test6461042.java new file mode 100644 index 00000000000..3224b1db83e --- /dev/null +++ b/jdk/test/javax/swing/border/Test6461042.java @@ -0,0 +1,57 @@ +/* + * Copyright 2006-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6461042 + * @summary Tests that toString() doesn't cause StackOverflowException + * when a JComponent is its own border + * @author Shannon Hickey + */ + +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Insets; +import javax.swing.JComponent; +import javax.swing.border.Border; + +public class Test6461042 extends JComponent implements Border { + public static void main(String[] args) { + new Test6461042().toString(); + } + + public Test6461042() { + setBorder(this); + } + + public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { + } + + public Insets getBorderInsets(Component c) { + return null; + } + + public boolean isBorderOpaque() { + return false; + } +} From ef9b3891fc4b83e611765fbc187e6ceb8510cb57 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 26 Jun 2008 15:39:12 +0400 Subject: [PATCH 04/45] 6718965: Swing color chooser tests should be open source Reviewed-by: peterz --- .../swing/JColorChooser/Test4165217.java | 78 +++++++++++++++ .../swing/JColorChooser/Test4177735.java | 95 +++++++++++++++++++ .../swing/JColorChooser/Test4193384.java | 70 ++++++++++++++ .../swing/JColorChooser/Test4234761.java | 60 ++++++++++++ .../swing/JColorChooser/Test4380468.html | 17 ++++ .../swing/JColorChooser/Test4380468.java | 40 ++++++++ .../swing/JColorChooser/Test4461329.java | 46 +++++++++ .../swing/JColorChooser/Test4711996.java | 41 ++++++++ .../swing/JColorChooser/Test4759306.html | 8 ++ .../swing/JColorChooser/Test4759306.java | 42 ++++++++ .../swing/JColorChooser/Test4759934.html | 14 +++ .../swing/JColorChooser/Test4759934.java | 80 ++++++++++++++++ .../swing/JColorChooser/Test4887836.html | 9 ++ .../swing/JColorChooser/Test4887836.java | 43 +++++++++ 14 files changed, 643 insertions(+) create mode 100644 jdk/test/javax/swing/JColorChooser/Test4165217.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4177735.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4193384.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4234761.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4380468.html create mode 100644 jdk/test/javax/swing/JColorChooser/Test4380468.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4461329.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4711996.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4759306.html create mode 100644 jdk/test/javax/swing/JColorChooser/Test4759306.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4759934.html create mode 100644 jdk/test/javax/swing/JColorChooser/Test4759934.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4887836.html create mode 100644 jdk/test/javax/swing/JColorChooser/Test4887836.java diff --git a/jdk/test/javax/swing/JColorChooser/Test4165217.java b/jdk/test/javax/swing/JColorChooser/Test4165217.java new file mode 100644 index 00000000000..59a80e89848 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4165217.java @@ -0,0 +1,78 @@ +/* + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4165217 + * @summary Tests JColorChooser serialization + * @author Ilya Boyandin + */ + +import java.awt.Color; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Random; +import javax.swing.JColorChooser; + +public class Test4165217 { + public static void main(String[] args) { + JColorChooser chooser = new JColorChooser(); + chooser.setColor(new Color(new Random().nextInt())); + + Color before = chooser.getColor(); + Color after = copy(chooser).getColor(); + + if (!after.equals(before)) { + throw new Error("color is changed after serialization"); + } + } + + private static JColorChooser copy(JColorChooser chooser) { + try { + return (JColorChooser) deserialize(serialize(chooser)); + } + catch (ClassNotFoundException exception) { + throw new Error("unexpected exception during class creation", exception); + } + catch (IOException exception) { + throw new Error("unexpected exception during serialization", exception); + } + } + + private static byte[] serialize(Object object) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(object); + oos.flush(); + return baos.toByteArray(); + } + + private static Object deserialize(byte[] array) throws IOException, ClassNotFoundException { + ByteArrayInputStream bais = new ByteArrayInputStream(array); + ObjectInputStream ois = new ObjectInputStream(bais); + return ois.readObject(); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4177735.java b/jdk/test/javax/swing/JColorChooser/Test4177735.java new file mode 100644 index 00000000000..b8b2d93f47e --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4177735.java @@ -0,0 +1,95 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4177735 + * @summary Tests that JColorChooser leaves no threads when disposed + * @author Shannon Hickey + */ + +import java.awt.Point; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.SwingUtilities; +import javax.swing.colorchooser.AbstractColorChooserPanel; + +public class Test4177735 implements Runnable { + private static final long DELAY = 1000L; + + public static void main(String[] args) throws Exception { + JColorChooser chooser = new JColorChooser(); + AbstractColorChooserPanel[] panels = chooser.getChooserPanels(); + chooser.setChooserPanels(new AbstractColorChooserPanel[] { panels[1] }); + + JDialog dialog = show(chooser); + pause(DELAY); + + dialog.dispose(); + pause(DELAY); + + Test4177735 test = new Test4177735(); + SwingUtilities.invokeAndWait(test); + if (test.count != 0) { + throw new Error("JColorChooser leaves " + test.count + " threads running"); + } + } + + static JDialog show(JColorChooser chooser) { + JDialog dialog = JColorChooser.createDialog(null, null, false, chooser, null, null); + dialog.setVisible(true); + // block till displayed + Point point = null; + while (point == null) { + try { + point = dialog.getLocationOnScreen(); + } + catch (IllegalStateException exception) { + pause(DELAY); + } + } + return dialog; + } + + private static void pause(long delay) { + try { + Thread.sleep(delay); + } + catch (InterruptedException exception) { + } + } + + private int count; + + public void run() { + ThreadGroup group = Thread.currentThread().getThreadGroup(); + Thread[] threads = new Thread[group.activeCount()]; + int count = group.enumerate(threads, false); + for (int i = 0; i < count; i++) { + String name = threads[i].getName(); + if ("SyntheticImageGenerator".equals(name)) { // NON-NLS: thread name + this.count++; + } + } + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4193384.java b/jdk/test/javax/swing/JColorChooser/Test4193384.java new file mode 100644 index 00000000000..e9ed74728a4 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4193384.java @@ -0,0 +1,70 @@ +/* + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4193384 4200976 + * @summary Tests the color conversions and the preview panel foreground color + * @author Mark Davidson + */ + +import java.awt.Color; +import javax.swing.JColorChooser; +import javax.swing.JLabel; + +public class Test4193384 { + public static void main(String[] args) { + test(new Color[] { + new Color(11, 12, 13), + new Color(204, 0, 204), + new Color(0, 51, 51) + }); + } + + private static void test(Color[] colors) { + JLabel label = new JLabel("Preview Panel"); // NON-NLS: simple label + + JColorChooser chooser = new JColorChooser(); + chooser.setPreviewPanel(label); + + float[] hsb = new float[3]; + for (int i = 0; i < colors.length; i++) { + Color color = colors[i]; + // Make sure sure that there wasn't a regression + // in java.awt.Color and the conversion methods + Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsb); + if (!color.equals(Color.getHSBColor(hsb[0], hsb[1], hsb[2]))) { + throw new Error("color conversion is failed"); + } + // 4193384 regression test + if (!color.equals(new JColorChooser(color).getColor())) { + throw new Error("constructor sets incorrect initial color"); + } + // 4200976 regression test + chooser.setColor(color); + if (!color.equals(label.getForeground())) { + throw new Error("a custom preview panel doesn't handle colors"); + } + } + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4234761.java b/jdk/test/javax/swing/JColorChooser/Test4234761.java new file mode 100644 index 00000000000..aa3d972a642 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4234761.java @@ -0,0 +1,60 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4234761 + * @summary RGB values sholdn't be changed in transition to HSB tab + * @author Oleg Mokhovikov + */ + +import java.awt.Color; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.JTabbedPane; + +public class Test4234761 implements PropertyChangeListener { + private static final Color COLOR = new Color(51, 51, 51); + + public static void main(String[] args) { + JColorChooser chooser = new JColorChooser(COLOR); + JDialog dialog = Test4177735.show(chooser); + + PropertyChangeListener listener = new Test4234761(); + chooser.addPropertyChangeListener("color", listener); // NON-NLS: property name + + JTabbedPane tabbedPane = (JTabbedPane) chooser.getComponent(0); + tabbedPane.setSelectedIndex(1); // HSB tab index + + if (!chooser.getColor().equals(COLOR)) { + listener.propertyChange(null); + } + dialog.dispose(); + } + + public void propertyChange(PropertyChangeEvent event) { + throw new Error("RGB value is changed after transition to HSB tab"); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4380468.html b/jdk/test/javax/swing/JColorChooser/Test4380468.html new file mode 100644 index 00000000000..fbbba0d2e64 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4380468.html @@ -0,0 +1,17 @@ + + +1. Click the HSB tab at the ColorChooser. +2. Click in the lower left corner of the gradient palette + in order to select a color such that all three RGB values + are single digit colors (such as 0, 0, 0 or 5, 3, 1). +3. Click another tab, then click back to the HSB tab. +4. Now click the lighter colors that should have + 2 and 3 digit RGB values (in the upper right corner). + +If all digits of each RGB value are shown then test passes. +If only the last digit of their values are shown then test fails. + + + + + diff --git a/jdk/test/javax/swing/JColorChooser/Test4380468.java b/jdk/test/javax/swing/JColorChooser/Test4380468.java new file mode 100644 index 00000000000..7e903317121 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4380468.java @@ -0,0 +1,40 @@ +/* + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4380468 + * @summary JColorChooser's HSB panel should display all RGB digits + * @author Andrey Pikalev + * @run applet/manual=yesno Test4380468.html + */ + +import java.awt.Color; +import javax.swing.JApplet; +import javax.swing.JColorChooser; + +public class Test4380468 extends JApplet { + public void init() { + add(new JColorChooser(Color.GREEN)); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4461329.java b/jdk/test/javax/swing/JColorChooser/Test4461329.java new file mode 100644 index 00000000000..2f23bc1ec6c --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4461329.java @@ -0,0 +1,46 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4461329 + * @summary Tests getPreviewPanel() and setPreviewPanel() methods + * @author Leif Samuelsson + */ + +import javax.swing.JButton; +import javax.swing.JColorChooser; + +public class Test4461329 { + public static void main(String[] args) { + JColorChooser chooser = new JColorChooser(); + if (null == chooser.getPreviewPanel()) { + throw new Error("Failed: getPreviewPanel() returned null"); + } + JButton button = new JButton("Color"); // NON-NLS: simple label + chooser.setPreviewPanel(button); + if (button != chooser.getPreviewPanel()) { + throw new Error("Failed in setPreviewPanel()"); + } + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4711996.java b/jdk/test/javax/swing/JColorChooser/Test4711996.java new file mode 100644 index 00000000000..fb6007712cf --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4711996.java @@ -0,0 +1,41 @@ +/* + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4711996 + * @summary Checks if IllegalArgumentException is thrown when updating JColorChooserUI + * @author Konstantin Eremin + */ + +import javax.swing.JColorChooser; +import javax.swing.colorchooser.AbstractColorChooserPanel; + +public class Test4711996 { + public static void main(String[] args) { + JColorChooser chooser = new JColorChooser(); + AbstractColorChooserPanel[] panels = chooser.getChooserPanels(); + chooser.removeChooserPanel(panels[0]); + chooser.updateUI(); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4759306.html b/jdk/test/javax/swing/JColorChooser/Test4759306.html new file mode 100644 index 00000000000..8a4d53f00e9 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4759306.html @@ -0,0 +1,8 @@ + + +If you see the preview panel, then test failed, otherwise it passed. + + + + + diff --git a/jdk/test/javax/swing/JColorChooser/Test4759306.java b/jdk/test/javax/swing/JColorChooser/Test4759306.java new file mode 100644 index 00000000000..726ed798f0e --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4759306.java @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4759306 + * @summary Checks if JColorChooser.setPreviewPanel removes the old one + * @author Konstantin Eremin + @run applet/manual=yesno Test4759306.html + */ + +import javax.swing.JApplet; +import javax.swing.JColorChooser; +import javax.swing.JPanel; + +public class Test4759306 extends JApplet { + public void init() { + JColorChooser chooser = new JColorChooser(); + chooser.setPreviewPanel(new JPanel()); + getContentPane().add(chooser); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4759934.html b/jdk/test/javax/swing/JColorChooser/Test4759934.html new file mode 100644 index 00000000000..0441b67ac66 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4759934.html @@ -0,0 +1,14 @@ + + +1. Press button "Show Dialog" at the frame "Test" and + the dialog with button "Show ColorChooser" should appears. +2. Press button "Show ColorChooser" at the dialog "Dialog" and + the colorchooser should appears. +3. Press the button "Cancel" of colorchooser. + If the focus will come to the frame "Test" then test fails. + If the focus will come to the dialog "Dialog" then test passes. + + + + + diff --git a/jdk/test/javax/swing/JColorChooser/Test4759934.java b/jdk/test/javax/swing/JColorChooser/Test4759934.java new file mode 100644 index 00000000000..27137726ea0 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4759934.java @@ -0,0 +1,80 @@ +/* + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4759934 + * @summary Tests windows activation problem + * @author Andrey Pikalev + * @run applet/manual=yesno Test4759934.html + */ + +import java.awt.Color; +import java.awt.Component; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JApplet; +import javax.swing.JButton; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.JFrame; + +public class Test4759934 extends JApplet implements ActionListener { + private static final String CMD_DIALOG = "Show Dialog"; // NON-NLS: first button + private static final String CMD_CHOOSER = "Show ColorChooser"; // NON-NLS: second button + + private final JFrame frame = new JFrame("Test"); // NON-NLS: frame title + + public void init() { + show(this.frame, CMD_DIALOG); + } + + public void actionPerformed(ActionEvent event) { + String command = event.getActionCommand(); + if (CMD_DIALOG.equals(command)) { + JDialog dialog = new JDialog(this.frame, "Dialog"); // NON-NLS: dialog title + dialog.setLocation(200, 0); + show(dialog, CMD_CHOOSER); + } + else if (CMD_CHOOSER.equals(command)) { + Object source = event.getSource(); + Component component = (source instanceof Component) + ? (Component) source + : null; + + JColorChooser.showDialog(component, "ColorChooser", Color.BLUE); // NON-NLS: title + } + } + + private void show(Window window, String command) { + JButton button = new JButton(command); + button.setActionCommand(command); + button.addActionListener(this); + button.setFont(button.getFont().deriveFont(64.0f)); + + window.add(button); + window.pack(); + window.setVisible(true); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4887836.html b/jdk/test/javax/swing/JColorChooser/Test4887836.html new file mode 100644 index 00000000000..324d5afe368 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4887836.html @@ -0,0 +1,9 @@ + + +If you do not see white area under swatches, +then test passed, otherwise it failed. + + + + + diff --git a/jdk/test/javax/swing/JColorChooser/Test4887836.java b/jdk/test/javax/swing/JColorChooser/Test4887836.java new file mode 100644 index 00000000000..3c6bb3832de --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4887836.java @@ -0,0 +1,43 @@ +/* + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4887836 + * @summary Checks if no tooltip modification when no KeyStroke modifier + * @author Konstantin Eremin + * @run applet/manual=yesno Test4887836.html + */ + +import java.awt.Color; +import java.awt.Font; +import javax.swing.JApplet; +import javax.swing.JColorChooser; +import javax.swing.UIManager; + +public class Test4887836 extends JApplet { + public void init() { + UIManager.put("Label.font", new Font("Perpetua", 0, 36)); // NON-NLS: property and font names + add(new JColorChooser(Color.LIGHT_GRAY)); + } +} From 3f961d60620c36044759732d87d32f7d22ebeff6 Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Wed, 2 Jul 2008 18:17:56 +0400 Subject: [PATCH 05/45] 6618401: Input method cannot be selected from System menu Lock.wait() added in sun.awt.im.InputMethodManager.showInputMethodMenuOnRequesterEDT() Reviewed-by: alexp --- jdk/src/share/classes/sun/awt/im/InputMethodManager.java | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/src/share/classes/sun/awt/im/InputMethodManager.java b/jdk/src/share/classes/sun/awt/im/InputMethodManager.java index f95b13c63ab..caba8d6a152 100644 --- a/jdk/src/share/classes/sun/awt/im/InputMethodManager.java +++ b/jdk/src/share/classes/sun/awt/im/InputMethodManager.java @@ -358,6 +358,7 @@ class ExecutableInputMethodManager extends InputMethodManager AppContext requesterAppContext = SunToolkit.targetToAppContext(requester); synchronized (lock) { SunToolkit.postEvent(requesterAppContext, event); + lock.wait(); } Throwable eventThrowable = event.getThrowable(); From 1dce7af76f26ab1860a83f60e9f4853e56952d8e Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Mon, 7 Jul 2008 16:56:23 +0400 Subject: [PATCH 06/45] 6647340: Minimized JInternalFrame icons appear in incorrect positions if the main frame is resized Now BasicInternalFrameUI and BasicDesktopIconUI both recalculate frame icon position Reviewed-by: peterz --- .../swing/plaf/basic/BasicDesktopIconUI.java | 12 +- .../plaf/basic/BasicInternalFrameUI.java | 45 ++--- .../swing/plaf/basic/DesktopIconMover.java | 168 ++++++++++++++++++ .../JInternalFrame/6647340/bug6647340.java | 146 +++++++++++++++ 4 files changed, 335 insertions(+), 36 deletions(-) create mode 100644 jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java create mode 100644 jdk/test/javax/swing/JInternalFrame/6647340/bug6647340.java diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java index 9aab4dbe17d..5ebb6289440 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,6 +47,7 @@ public class BasicDesktopIconUI extends DesktopIconUI { protected JInternalFrame.JDesktopIcon desktopIcon; protected JInternalFrame frame; + private DesktopIconMover desktopIconMover; /** * The title pane component used in the desktop icon. @@ -127,12 +128,21 @@ public class BasicDesktopIconUI extends DesktopIconUI { mouseInputListener = createMouseInputListener(); desktopIcon.addMouseMotionListener(mouseInputListener); desktopIcon.addMouseListener(mouseInputListener); + getDesktopIconMover().installListeners(); } protected void uninstallListeners() { desktopIcon.removeMouseMotionListener(mouseInputListener); desktopIcon.removeMouseListener(mouseInputListener); mouseInputListener = null; + getDesktopIconMover().uninstallListeners(); + } + + private DesktopIconMover getDesktopIconMover() { + if (desktopIconMover == null) { + desktopIconMover = new DesktopIconMover(desktopIcon); + } + return desktopIconMover; } protected void installDefaults() { diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java index 83b0fd73bd9..86a8f15ddd0 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,7 +55,6 @@ public class BasicInternalFrameUI extends InternalFrameUI protected MouseInputAdapter borderListener; protected PropertyChangeListener propertyChangeListener; protected LayoutManager internalFrameLayout; - protected ComponentListener componentListener; protected MouseInputListener glassPaneDispatcher; private InternalFrameListener internalFrameListener; @@ -67,9 +66,9 @@ public class BasicInternalFrameUI extends InternalFrameUI protected BasicInternalFrameTitlePane titlePane; // access needs this private static DesktopManager sharedDesktopManager; - private boolean componentListenerAdded = false; private Rectangle parentBounds; + private DesktopIconMover desktopIconMover; private boolean dragging = false; private boolean resizing = false; @@ -210,14 +209,17 @@ public class BasicInternalFrameUI extends InternalFrameUI frame.getGlassPane().addMouseListener(glassPaneDispatcher); frame.getGlassPane().addMouseMotionListener(glassPaneDispatcher); } - componentListener = createComponentListener(); if (frame.getParent() != null) { parentBounds = frame.getParent().getBounds(); } - if ((frame.getParent() != null) && !componentListenerAdded) { - frame.getParent().addComponentListener(componentListener); - componentListenerAdded = true; + getDesktopIconMover().installListeners(); + } + + private DesktopIconMover getDesktopIconMover() { + if (desktopIconMover == null) { + desktopIconMover = new DesktopIconMover(frame); } + return desktopIconMover; } // Provide a FocusListener to listen for a WINDOW_LOST_FOCUS event, @@ -288,11 +290,7 @@ public class BasicInternalFrameUI extends InternalFrameUI * @since 1.3 */ protected void uninstallListeners() { - if ((frame.getParent() != null) && componentListenerAdded) { - frame.getParent().removeComponentListener(componentListener); - componentListenerAdded = false; - } - componentListener = null; + getDesktopIconMover().uninstallListeners(); if (glassPaneDispatcher != null) { frame.getGlassPane().removeMouseListener(glassPaneDispatcher); frame.getGlassPane().removeMouseMotionListener(glassPaneDispatcher); @@ -1230,15 +1228,6 @@ public class BasicInternalFrameUI extends InternalFrameUI } } - // Relocate the icon base on the new parent bounds. - if (icon != null) { - Rectangle iconBounds = icon.getBounds(); - int y = iconBounds.y + - (parentNewBounds.height - parentBounds.height); - icon.setBounds(iconBounds.x, y, - iconBounds.width, iconBounds.height); - } - // Update the new parent bounds for next resize. if (!parentBounds.equals(parentNewBounds)) { parentBounds = parentNewBounds; @@ -1413,10 +1402,6 @@ public class BasicInternalFrameUI extends InternalFrameUI // Cancel a resize in progress if the internal frame // gets a setClosed(true) or dispose(). cancelResize(); - if ((frame.getParent() != null) && componentListenerAdded) { - frame.getParent().removeComponentListener( - componentListener); - } closeFrame(f); } } else if (JInternalFrame.IS_MAXIMUM_PROPERTY == prop) { @@ -1449,16 +1434,6 @@ public class BasicInternalFrameUI extends InternalFrameUI } else { parentBounds = null; } - if ((frame.getParent() != null) && !componentListenerAdded) { - f.getParent().addComponentListener(componentListener); - componentListenerAdded = true; - } else if ((newValue == null) && componentListenerAdded) { - if (f.getParent() != null) { - f.getParent().removeComponentListener( - componentListener); - } - componentListenerAdded = false; - } } else if (JInternalFrame.TITLE_PROPERTY == prop || prop == "closable" || prop == "iconable" || prop == "maximizable") { diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java b/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java new file mode 100644 index 00000000000..deff4f27a5f --- /dev/null +++ b/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java @@ -0,0 +1,168 @@ +/* + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.plaf.basic; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.beans.*; + +/** + * DesktopIconMover is intended to move desktop icon + * when parent window is resized. + */ +class DesktopIconMover implements ComponentListener, PropertyChangeListener { + private Component parent; + private JInternalFrame frame; // if not null, DesktopIconMover(frame) + // constructor was used + private JInternalFrame.JDesktopIcon icon; + private Rectangle parentBounds; + private boolean componentListenerAdded = false; + + public DesktopIconMover(JInternalFrame frame) { + if (frame == null) { + throw new NullPointerException("Frame cannot be null"); + } + this.frame = frame; + this.icon = frame.getDesktopIcon(); + if (icon == null) { + throw new NullPointerException( + "frame.getDesktopIcon() cannot be null"); + } + this.parent = frame.getParent(); + if (this.parent != null) { + parentBounds = this.parent.getBounds(); + } + } + + public DesktopIconMover(JInternalFrame.JDesktopIcon icon) { + if (icon == null) { + throw new NullPointerException("Icon cannot be null"); + } + this.icon = icon; + this.parent = icon.getParent(); + if (this.parent != null) { + parentBounds = this.parent.getBounds(); + } + } + + public void installListeners() { + if (frame != null) { + frame.addPropertyChangeListener(this); + } else { + icon.addPropertyChangeListener(this); + } + addComponentListener(); + } + + public void uninstallListeners() { + if (frame != null) { + frame.removePropertyChangeListener(this); + } else { + icon.removePropertyChangeListener(this); + } + removeComponentListener(); + } + + public void propertyChange(PropertyChangeEvent evt) { + String propName = evt.getPropertyName(); + if ("ancestor".equals(propName)) { + Component newAncestor = (Component) evt.getNewValue(); + + // Remove component listener if parent is changing + Component probablyNewParent = getCurrentParent(); + if ((probablyNewParent != null) && + (!probablyNewParent.equals(parent))) { + removeComponentListener(); + parent = probablyNewParent; + } + + if (newAncestor == null) { + removeComponentListener(); + } else { + addComponentListener(); + } + + // Update parentBounds + if (parent != null) { + parentBounds = parent.getBounds(); + } else { + parentBounds = null; + } + } else if (JInternalFrame.IS_CLOSED_PROPERTY.equals(propName)) { + removeComponentListener(); + } + } + + private void addComponentListener() { + if (!componentListenerAdded && (parent != null)) { + parent.addComponentListener(this); + componentListenerAdded = true; + } + } + + private void removeComponentListener() { + if ((parent != null) && componentListenerAdded) { + parent.removeComponentListener(this); + componentListenerAdded = false; + } + } + + private Component getCurrentParent() { + if (frame != null) { + return frame.getParent(); + } else { + return icon.getParent(); + } + } + + public void componentResized(ComponentEvent e) { + if ((parent == null) || (parentBounds == null)) { + return; + } + + Rectangle parentNewBounds = parent.getBounds(); + if ((parentNewBounds == null) || parentNewBounds.equals(parentBounds)) { + return; + } + + // Move desktop icon only in up-down direction + int newIconY = icon.getLocation().y + + (parentNewBounds.height - parentBounds.height); + icon.setLocation(icon.getLocation().x, newIconY); + + parentBounds = parentNewBounds; + } + + public void componentMoved(ComponentEvent e) { + } + + public void componentShown(ComponentEvent e) { + } + + public void componentHidden(ComponentEvent e) { + } +} diff --git a/jdk/test/javax/swing/JInternalFrame/6647340/bug6647340.java b/jdk/test/javax/swing/JInternalFrame/6647340/bug6647340.java new file mode 100644 index 00000000000..b4c180140bd --- /dev/null +++ b/jdk/test/javax/swing/JInternalFrame/6647340/bug6647340.java @@ -0,0 +1,146 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6647340 + * @summary Checks that iconified internal frame follows + * the main frame borders properly. + * @author Mikhail Lapshin + */ + +import sun.awt.SunToolkit; + +import javax.swing.*; +import java.awt.*; +import java.beans.PropertyVetoException; + +public class bug6647340 { + private JFrame frame; + private Point location; + private JInternalFrame jif; + + public static void main(String[] args) throws Exception { + final bug6647340 test = new bug6647340(); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + test.setupUI(); + } + }); + test.test(); + } finally { + if (test.frame != null) { + test.frame.dispose(); + } + } + } + + private void setupUI() { + frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JDesktopPane desktop = new JDesktopPane(); + frame.add(desktop); + + jif = new JInternalFrame("Internal Frame", true, true, true, true); + jif.setBounds(20, 20, 200, 100); + desktop.add(jif); + jif.setVisible(true); + + Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + frame.setBounds((screen.width - 400) / 2, (screen.height - 400) / 2, 400, 400); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private void test() throws Exception { + realSync(); + test1(); + realSync(); + check1(); + realSync(); + test2(); + realSync(); + check2(); + } + + private void test1() throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + setIcon(true); + location = jif.getDesktopIcon().getLocation(); + Dimension size = frame.getSize(); + frame.setSize(size.width + 100, size.height + 100); + } + }); + } + + private void test2() throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + setIcon(false); + } + }); + realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + Dimension size = frame.getSize(); + frame.setSize(size.width - 100, size.height - 100); + } + }); + realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + setIcon(true); + } + }); + } + + private void check1() { + if (!jif.getDesktopIcon().getLocation().equals(location)) { + System.out.println("First test passed"); + } else { + throw new RuntimeException("Icon isn't shifted with the frame bounds"); + } + } + + private void check2() { + if (jif.getDesktopIcon().getLocation().equals(location)) { + System.out.println("Second test passed"); + } else { + throw new RuntimeException("Icon isn't located near the frame bottom"); + } + } + + private static void realSync() { + ((SunToolkit) (Toolkit.getDefaultToolkit())).realSync(); + } + + private void setIcon(boolean b) { + try { + jif.setIcon(b); + } catch (PropertyVetoException e) { + e.printStackTrace(); + } + } +} From b4be323f02abd645a977db142d496eb8512e7d90 Mon Sep 17 00:00:00 2001 From: Peter Zhelezniakov Date: Tue, 8 Jul 2008 11:36:19 +0400 Subject: [PATCH 07/45] 6635663: make/tools/AutoMulti/{AutoMulti,TestALFGenerator}.java still generate files with wrong legal notices Removed unused files Reviewed-by: ohair --- jdk/make/tools/Makefile | 1 - jdk/make/tools/auto_multi/Makefile | 43 -- .../src/build/tools/automulti/AutoMulti.java | 458 ------------------ .../src/build/tools/automulti/README.txt | 36 -- .../tools/automulti/TestALFGenerator.java | 401 --------------- .../tools/automulti/TestALFLookAndFeel.java | 182 ------- 6 files changed, 1121 deletions(-) delete mode 100644 jdk/make/tools/auto_multi/Makefile delete mode 100644 jdk/make/tools/src/build/tools/automulti/AutoMulti.java delete mode 100644 jdk/make/tools/src/build/tools/automulti/README.txt delete mode 100644 jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java delete mode 100644 jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java diff --git a/jdk/make/tools/Makefile b/jdk/make/tools/Makefile index be1c59a7cfa..c396097c086 100644 --- a/jdk/make/tools/Makefile +++ b/jdk/make/tools/Makefile @@ -32,7 +32,6 @@ include $(BUILDDIR)/common/Defs.gmk SUBDIRS = \ addjsum \ - auto_multi \ buildmetaindex \ commentchecker \ compile_font_config \ diff --git a/jdk/make/tools/auto_multi/Makefile b/jdk/make/tools/auto_multi/Makefile deleted file mode 100644 index f5db35099ad..00000000000 --- a/jdk/make/tools/auto_multi/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# -# Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. Sun designates this -# particular file as subject to the "Classpath" exception as provided -# by Sun in the LICENSE file that accompanied this code. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, -# CA 95054 USA or visit www.sun.com if you need additional information or -# have any questions. -# - -# -# Makefile for building the automulti tool -# - -BUILDDIR = ../.. -PACKAGE = build.tools.automulti -PRODUCT = tools -PROGRAM = automulti -include $(BUILDDIR)/common/Defs.gmk - -BUILDTOOL_SOURCE_ROOT = $(BUILDDIR)/tools/src -BUILDTOOL_MAIN = $(PKGDIR)/AutoMulti.java - -# -# Build tool jar rules. -# -include $(BUILDDIR)/common/BuildToolJar.gmk - diff --git a/jdk/make/tools/src/build/tools/automulti/AutoMulti.java b/jdk/make/tools/src/build/tools/automulti/AutoMulti.java deleted file mode 100644 index a59edc856ca..00000000000 --- a/jdk/make/tools/src/build/tools/automulti/AutoMulti.java +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package build.tools.automulti; - -import java.lang.reflect.*; -import java.util.*; -import java.io.*; - -/** - * Automatically generates the Multiplexing UI classes - * for Swing. - *

- * To use, type 'java AutoMulti ' where - * is the directory containing the source for Swing's UI classes and - * is the package prefix to use before ".swing.plaf.multi". - * For example: - * - *

- * cd TEST
- * ../../../../build/solaris-sparc/bin/java AutoMulti ../../../../src/share/classes/javax/swing/plaf javax
- * 
- * - * AutoMulti will scour the plaf directory for *UI.java files and - * generate Multi*UI.java files that do the multiplexing thing. - *

- * NOTE: This tool depends upon the existence of and on the - * compiled classes from being somewhere in the class path. - * - * @author Willie Walker - */ -public class AutoMulti { - static String importLines; - - /** - * A silly list of parameter names to use. Skips "i" because we use - * it as a 'for' loop counter. If you want to get fancy, please feel - * to change how parameter names are obtained. This will break if - * someone decides to create a UI method that takes more than 8 - * parameters. Which one is a bug (this breaking or having a method - * with more than eight parameters) is a subjective thing. - */ - public static String[] paramNames = {"a","b","c","d","e","f","g","h"}; - - /** - * Removes the package names (e.g., javax.swing) from the name. - */ - public static String unqualifyName(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - String unqualifiedName = null; - while (parser.hasMoreTokens()) { - unqualifiedName = parser.nextToken(); - } - return removeDollars(unqualifiedName); - } - - /** - * Strips the extension from the filename. - */ - public static String stripExtension(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - return parser.nextToken(); - } - - /** - * Adds some spaces. - */ - public static void indent(StringBuffer s, int i) { - while (i > 0) { - s.append(" "); - i--; - } - } - - /** - * Spits out all the beginning stuff. - */ - public static StringBuffer createPreamble(String prefixName) { - StringBuffer s = new StringBuffer(); - s.append("/*\n"); - s.append(" *\n"); - s.append(" * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.\n"); - s.append(" * \n"); - s.append(" * This software is the proprietary information of Sun Microsystems, Inc. \n"); - s.append(" * Use is subject to license terms.\n"); - s.append(" * \n"); - s.append(" */\n"); - s.append("package " + prefixName + ".swing.plaf.multi;\n"); - s.append("\n"); - return s; - } - - /** - * Replaces 'Xxx$Yyy' with "Xxx'. Used by addImport because you - * can't import nested classes directly. - */ - public static String removeNestedClassName(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - sb.setLength(dollarPosition); - return sb.toString(); - } else { // no '$' - return s; - } - } - - /** - * Replaces '$' with ".'. Needed for printing inner class names - * for argument and return types. - */ - public static String removeDollars(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - while (dollarPosition >= 0) { - //XXX: will there ever be more than one '$'? - sb.replace(dollarPosition, dollarPosition+1, "."); - dollarPosition = sb.indexOf("$", dollarPosition); - } - return sb.toString(); - } else { // no $ - return s; - } - } - - /** - * Adds an import line to the String. - */ - public static void addImport(String s, Class theClass) { - if (!theClass.isPrimitive() && (theClass != Object.class)) { - String className = removeNestedClassName(theClass.getName()); - String importLine = new String("import " + className + ";\n"); - if (importLines.indexOf(importLine) == -1) { - importLines += importLine; - } - } - } - - /** - * Spits out the class header information. - */ - public static void addHeader(StringBuffer s, String className) { - s.append("/**\n"); - s.append(" * A multiplexing UI used to combine " + className + "s.\n"); - s.append(" * \n"); - s.append(" *

This file was automatically generated by AutoMulti.\n"); - s.append(" *\n"); - s.append(" * @author Otto Multey\n"); // Get it? I crack myself up. - s.append(" */\n"); - s.append("public class Multi" + className + " extends " + className + " {\n"); - s.append("\n"); - s.append(" /**\n"); - s.append(" * The vector containing the real UIs. This is populated \n"); - s.append(" * in the call to createUI, and can be obtained by calling\n"); - s.append(" * the getUIs method. The first element is guaranteed to be the real UI \n"); - s.append(" * obtained from the default look and feel.\n"); - s.append(" */\n"); - s.append(" protected Vector uis = new Vector();\n"); - s.append("\n"); - s.append("////////////////////\n"); - s.append("// Common UI methods\n"); - s.append("////////////////////\n"); - s.append("\n"); - s.append(" /**\n"); - s.append(" * Returns the list of UIs associated with this multiplexing UI. This \n"); - s.append(" * allows processing of the UIs by an application aware of multiplexing \n"); - s.append(" * UIs on components.\n"); - s.append(" */\n"); - s.append(" public ComponentUI[] getUIs() {\n"); - s.append(" return MultiLookAndFeel.uisToArray(uis);\n"); - s.append(" }\n"); - } - - /** - * Prints out the code for a method. This is pretty specific to the - * Multiplexing UI code, so don't get any fancy ideas. - */ - public static void addMethod(StringBuffer s, Method m, String origName, String className) { - - // Get the method name and the return type. Be a little careful about arrays. - // - String methodName = unqualifyName(m.getName()); - String returnType; - if (!m.getReturnType().isArray()) { - returnType = unqualifyName(m.getReturnType().toString()); - addImport(importLines,m.getReturnType()); - } else { - returnType = unqualifyName(m.getReturnType().getComponentType().toString()) - + "[]"; - addImport(importLines,m.getReturnType().getComponentType()); - } - - // Print the javadoc - // - s.append("\n"); - if (methodName.equals("createUI")) { - s.append(" /**\n"); - s.append(" * Returns a multiplexing UI instance if any of the auxiliary\n"); - s.append(" * LookAndFeels supports this UI. Otherwise, just returns the \n"); - s.append(" * UI object obtained from the default LookAndFeel.\n"); - s.append(" */\n"); - } else if (!returnType.equals("void")) { - s.append(" /**\n"); - s.append(" * Invokes the " + methodName + " method on each UI handled by this object.\n"); - s.append(" * \n"); - s.append(" * @return the value obtained from the first UI, which is\n"); - s.append(" * the UI obtained from the default LookAndFeel\n"); - s.append(" */\n"); - } else { - s.append(" /**\n"); - s.append(" * Invokes the " + methodName - + " method on each UI handled by this object.\n"); - s.append(" */\n"); - } - - // Print the method signature - // - s.append(" public"); - if (Modifier.isStatic(m.getModifiers())) { - s.append(" static"); - } - s.append(" " + returnType); - s.append(" " + methodName); - s.append("("); - - Class[] params = m.getParameterTypes(); - Class temp; - String braces; - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(", "); - } - temp = params[i]; - braces = new String(""); - while (temp.isArray()) { - braces += "[]"; - temp = temp.getComponentType(); - } - s.append(unqualifyName(temp.getName()) + braces + " " + paramNames[i]); - addImport(importLines,temp); - } - s.append(")"); - - // Don't forget about exceptions - // - Class exceptions[] = m.getExceptionTypes(); - String throwsString = new String(""); - - if (exceptions.length > 0) { - s.append("\n"); - indent(s,12); - s.append("throws "); - for (int i = 0; i < exceptions.length; i++) { - if (i > 0) { - s.append(", "); - } - s.append(unqualifyName(exceptions[i].getName())); - addImport(importLines,exceptions[i]); - } - } - s.append(throwsString + " {\n"); - - // Now print out the contents of the method. We do a special thing - // for the createUI method, another thing if the method returns 'void' - // and a third thing if we don't do either of the first two. If - // you want to squash this down, feel free. - // - if (methodName.equals("createUI")) { - indent(s,8); - s.append("ComponentUI mui = new Multi" + origName + "();\n"); - indent(s,8); - s.append("return MultiLookAndFeel.createUIs(mui,\n"); - indent(s,42); - s.append("((Multi" + origName +") mui).uis,\n"); - indent(s,42); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - } else if (!returnType.equals("void")) { - indent(s,8); - s.append(returnType + " returnValue = \n"); - indent(s,12); - s.append("((" + className + ") (uis.elementAt(0)))." - + methodName + "("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - indent(s,8); - s.append("for (int i = 1; i < uis.size(); i++) {\n"); - indent(s,12); - s.append("((" + className + ") (uis.elementAt(i)))." - + methodName + "("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - indent(s,8); - s.append("}\n"); - indent(s,8); - s.append("return returnValue;\n"); - } else { - indent(s,8); - s.append("for (int i = 0; i < uis.size(); i++) {\n"); - indent(s,12); - s.append("((" + className + ") (uis.elementAt(i)))." - + methodName + "("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - indent(s,8); - s.append("}\n"); - } - indent(s,4); - s.append("}\n"); - } - - /** - * Takes a plaf class name (e.g., "MenuUI") and generates the corresponding - * Multiplexing UI Java source code (e.g., "MultiMenuUI.java"). - */ - public static void generateFile(String prefixName, String className) { - try { - FileOutputStream fos; - PrintWriter outFile; - - importLines = new String(); - importLines += new String("import java.util.Vector;\n"); - - StringBuffer body = new StringBuffer(); - Class wee = Class.forName(prefixName + ".swing.plaf." + className); - String weeName = unqualifyName(wee.getName()); - addImport(importLines,wee); - while (!weeName.equals("Object")) { - body.append("\n"); - body.append("////////////////////\n"); - body.append("// " + weeName + " methods\n"); - body.append("////////////////////\n"); - Method[] methods = wee.getDeclaredMethods(); - for (int i=0; i < methods.length; i++) { - if (Modifier.isPublic(methods[i].getModifiers())) { - addMethod(body,methods[i],className,weeName); - } - } - wee = wee.getSuperclass(); - weeName = unqualifyName(wee.getName()); - addImport(importLines,wee); - } - - fos = new FileOutputStream("Multi" + className + ".java"); - outFile = new PrintWriter(fos); - StringBuffer outText = createPreamble(prefixName); - outText.append(importLines.toString() + "\n"); - addHeader(outText,className); - outText.append(body.toString()); - outText.append("}\n"); - outFile.write(outText.toString()); - outFile.flush(); - outFile.close(); - } catch (Exception e) { - System.err.println(e); - } - } - - /** - * D'Oh! Something bad happened. - */ - public static void usage(String s) throws IOException { - System.err.println("Usage: AutoMulti [com.sun]"); - throw new IllegalArgumentException(s); - } - - /** - * Takes the plaf directory name and generates the multiplexing UI - * source code. - */ - public static void main(String[] args) throws IOException { - - if (args.length < 1) { - usage(""); - } - - String dirName = args[0]; - File dir = new File(dirName); - if (!dir.isDirectory()) { - System.err.println("No such directory: " + dirName); - usage(""); - } - - String prefixName; - if (args.length > 1) { - prefixName = args[1]; - } else { - prefixName = "com.sun.java"; - } - - String plafUIs[] = dir.list(new UIJavaFilter()); - for (int i = 0; i < plafUIs.length; i++) { - generateFile(prefixName,stripExtension(plafUIs[i])); - } - } -} - -/** - * Only accepts file names of the form *UI.java. The one exception - * is not accepting ComponentUI.java because we don't need to generate - * a multiplexing class for it. - */ -class UIJavaFilter implements FilenameFilter { - public boolean accept(File dir, String name) { - if (name.equals("ComponentUI.java")) { - return false; - } else if (name.endsWith("UI.java")) { - return true; - } else { - return false; - } - } -} diff --git a/jdk/make/tools/src/build/tools/automulti/README.txt b/jdk/make/tools/src/build/tools/automulti/README.txt deleted file mode 100644 index b5de5afe910..00000000000 --- a/jdk/make/tools/src/build/tools/automulti/README.txt +++ /dev/null @@ -1,36 +0,0 @@ -AutoMulti is the tool that automatically generates the -Multi*UI classes for the Multiplexing look and feel. -Instructions for using it are in AutoMulti.java. - -TestALFGenerator is a tool (a variation of AutoMulti) -that automatically generates an auxiliary look and -feel that you can use to test the Multiplexing look -and feel. The TestALF look and feel implements every -method by printing the message "In the xxx method of -the TextALFYyyUI class." and, except in the case of -createUI, returning something meaningless (since, -except in the case of createUI, the return value is -ignored). - -TestALFLookAndFeel.java is the only non-auto-generated -file for the TestALF L&F. If you specify a package -argument to TestALFGenerator, you'll have to change -the code in TestALFLookAndFeel.java to reflect the -package name. - -To test any application with the TestALF, make sure the -compiled TestALF classes are in the class path. Then add -this to the /lib/swing.properties file (which -you'll probably have to create): - -swing.auxiliarylaf=TestALFLookAndFeel - -E.g., if you're running SwingSet2 against your solaris -build, then you'd create/edit the swing.properties file -in /build/solaris-sparc/lib. - -Then run any app. You'll see lots of thrilling "In the -Xxxx method of the Yyy class" messages. If you get anything -else (especially an exception), then you've found a bug. -Probably in the default look and feel. - diff --git a/jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java b/jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java deleted file mode 100644 index 9b07dbc4048..00000000000 --- a/jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package build.tools.automulti; - -import java.lang.reflect.*; -import java.util.*; -import java.io.*; - -/** - * Automatically generates an auxiliary look and feel to be - * used for testing the Multiplexing look and feel. - *

- * To use, type 'java TestALFGenerator []' where - * is the directory containing the source for Swing's UI classes. - * is an optional argument that specifies the package - * of the TestALF classes. If it's omitted, the classes are in - * the default package. - * For example: - * - *

- * ../../../../build/solaris-sparc/bin/java TestALFGenerator ../../../../src/share/classes/javax/swing/plaf com.myco.myalaf
- * 
- * - * TestALFGenerator will scour the plaf directory for *UI.java files and - * generate TestALF*UI.java files. - *

- * NOTE: This tool depends upon the existence of and on the - * compiled classes from being somewhere in the class path. - * - * @author Willie Walker - */ -public class TestALFGenerator { - static String importLines; - static String packageName; - static String classPrefix = "TestALF"; - - /** - * A silly list of parameter names to use. Skips "i" because we use - * it as a 'for' loop counter. If you want to get fancy, please feel - * to change how parameter names are obtained. This will break if - * someone decides to create a UI method that takes more than 8 - * parameters. Which one is a bug (this breaking or having a method - * with more than eight parameters) is a subjective thing. - */ - public static String[] paramNames = {"a","b","c","d","e","f","g","h"}; - - /** - * Removes the package names (e.g., javax.swing) from the name. - */ - public static String unqualifyName(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - String unqualifiedName = null; - while (parser.hasMoreTokens()) { - unqualifiedName = parser.nextToken(); - } - return removeDollars(unqualifiedName); - } - - /** - * Strips the extension from the filename. - */ - public static String stripExtension(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - return parser.nextToken(); - } - - /** - * Adds some spaces. - */ - public static void indent(StringBuffer s, int i) { - while (i > 0) { - s.append(" "); - i--; - } - } - - /** - * Spits out all the beginning stuff. - */ - public static StringBuffer createPreamble(String prefixName) { - StringBuffer s = new StringBuffer(); - s.append("/*\n"); - s.append(" *\n"); - s.append(" * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.\n"); - s.append(" * \n"); - s.append(" * This software is the proprietary information of Sun Microsystems, Inc. \n"); - s.append(" * Use is subject to license terms.\n"); - s.append(" * \n"); - s.append(" */\n"); - if (packageName != null) { - s.append("package " + packageName + ";\n"); - s.append("\n"); - } - return s; - } - - /** - * Replaces 'Xxx$Yyy' with "Xxx'. Used by addImport because you - * can't import nested classes directly. - */ - public static String removeNestedClassName(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - sb.setLength(dollarPosition); - return sb.toString(); - } else { // no '$' - return s; - } - } - - /** - * Replaces '$' with ".'. Needed for printing inner class names - * for argument and return types. - */ - public static String removeDollars(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - while (dollarPosition >= 0) { - //XXX: will there ever be more than one '$'? - sb.replace(dollarPosition, dollarPosition+1, "."); - dollarPosition = sb.indexOf("$", dollarPosition); - } - return sb.toString(); - } else { // no $ - return s; - } - } - - /** - * Adds an import line to the String. - */ - public static void addImport(String s, Class theClass) { - if (!theClass.isPrimitive() && (theClass != Object.class)) { - String className = removeNestedClassName(theClass.getName()); - String importLine = new String("import " + className + ";\n"); - if (importLines.indexOf(importLine) == -1) { - importLines += importLine; - } - } - } - - /** - * Spits out the class header information. - */ - public static void addHeader(StringBuffer s, String className) { - s.append("/**\n"); - s.append(" * An auxiliary UI for " + className + "s.\n"); - s.append(" * \n"); - s.append(" *

This file was automatically generated by TestALFGenerator.\n"); - s.append(" *\n"); - s.append(" * @author Otto Multey\n"); // Get it? I crack myself up. - s.append(" */\n"); - s.append("public class " + classPrefix + className + " extends " + className + " {\n"); - s.append("\n"); - } - - /** - * Prints out the code for a method. - */ - public static void addMethod(StringBuffer s, Method m, String origName, String className) { - - // Get the method name and the return type. Be a little careful about arrays. - // - String methodName = unqualifyName(m.getName()); - String returnType; - - if (!m.getReturnType().isArray()) { - returnType = unqualifyName(m.getReturnType().toString()); - addImport(importLines,m.getReturnType()); - } else { - returnType = unqualifyName(m.getReturnType().getComponentType().toString()) - + "[]"; - addImport(importLines,m.getReturnType().getComponentType()); - } - - // Print the javadoc - // - s.append("\n"); - - if (methodName.equals("createUI")) { - s.append(" /**\n"); - s.append(" * Returns a UI object for this component.\n"); - s.append(" */\n"); - } else { - s.append(" /**\n"); - s.append(" * Prints a message saying this method has been invoked.\n"); - s.append(" */\n"); - } - - // Print the method signature - // - s.append(" public"); - if (Modifier.isStatic(m.getModifiers())) { - s.append(" static"); - } - s.append(" " + returnType); - s.append(" " + methodName); - s.append("("); - - Class[] params = m.getParameterTypes(); - Class temp; - String braces; - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(", "); - } - temp = params[i]; - braces = new String(""); - while (temp.isArray()) { - braces += "[]"; - temp = temp.getComponentType(); - } - s.append(unqualifyName(temp.getName()) + braces + " " + paramNames[i]); - addImport(importLines,temp); - } - s.append(")"); - - // Don't forget about exceptions - // - Class exceptions[] = m.getExceptionTypes(); - String throwsString = new String(""); - - if (exceptions.length > 0) { - s.append("\n"); - indent(s,12); - s.append("throws "); - for (int i = 0; i < exceptions.length; i++) { - if (i > 0) { - s.append(", "); - } - s.append(unqualifyName(exceptions[i].getName())); - addImport(importLines,exceptions[i]); - } - } - s.append(throwsString + " {\n"); - - // Now print out the contents of the method. - indent(s,8); - s.append("System.out.println(\"In the " + methodName - + " method of the " - + classPrefix + origName + " class.\");\n"); - if (methodName.equals("createUI")) { - indent(s,8); - s.append("return ui;\n"); - } else { - // If we have to return something, do so. - if (!returnType.equals("void")) { - Class rType = m.getReturnType(); - indent(s,8); - if (!rType.isPrimitive()) { - s.append("return null;\n"); - } else if (rType == Boolean.TYPE) { - s.append("return false;\n"); - } else if (rType == Character.TYPE) { - s.append("return '0';\n"); - } else { // byte, short, int, long, float, or double - s.append("return 0;\n"); - } - } - } - - indent(s,4); - s.append("}\n"); - } - - /** - * Takes a plaf class name (e.g., "MenuUI") and generates the corresponding - * TestALF UI Java source code (e.g., "TestALFMenuUI.java"). - */ - public static void generateFile(String prefixName, String className) { - try { - FileOutputStream fos; - PrintWriter outFile; - - importLines = new String(); - importLines += new String("import java.util.Vector;\n"); - - StringBuffer body = new StringBuffer(); - Class wee = Class.forName(prefixName + ".swing.plaf." + className); - String weeName = unqualifyName(wee.getName()); - String thisClassName = classPrefix + className; - addImport(importLines,wee); - - // Declare and initialize the shared UI object. - body.append("\n"); - body.append("////////////////////\n"); - body.append("// Shared UI object\n"); - body.append("////////////////////\n"); - body.append("private final static " + thisClassName - + " ui = new " + thisClassName + "();\n"); - - while (!weeName.equals("Object")) { - body.append("\n"); - body.append("////////////////////\n"); - body.append("// " + weeName + " methods\n"); - body.append("////////////////////\n"); - Method[] methods = wee.getDeclaredMethods(); - for (int i=0; i < methods.length; i++) { - if (Modifier.isPublic(methods[i].getModifiers())) { - addMethod(body,methods[i],className,weeName); - } - } - wee = wee.getSuperclass(); - weeName = unqualifyName(wee.getName()); - addImport(importLines,wee); - } - - fos = new FileOutputStream(classPrefix + className + ".java"); - outFile = new PrintWriter(fos); - StringBuffer outText = createPreamble(prefixName); - outText.append(importLines.toString() + "\n"); - addHeader(outText,className); - outText.append(body.toString()); - outText.append("}\n"); - outFile.write(outText.toString()); - outFile.flush(); - outFile.close(); - } catch (Exception e) { - System.err.println(e); - } - } - - /** - * D'Oh! Something bad happened. - */ - public static void usage(String s) throws IOException { - System.err.println("Usage: java TestALFGenerator []"); - throw new IllegalArgumentException(s); - } - - /** - * Takes the plaf directory name and generates the TestALF UI - * source code. - */ - public static void main(String[] args) throws IOException { - - if (args.length < 1) { - usage(""); - } - - String dirName = args[0]; - File dir = new File(dirName); - if (!dir.isDirectory()) { - System.err.println("No such directory: " + dirName); - usage(""); - } - - if (args.length > 1) { - packageName = args[1]; - } - - String plafUIs[] = dir.list(new UIJavaFilter()); - for (int i = 0; i < plafUIs.length; i++) { - generateFile("javax",stripExtension(plafUIs[i])); - } - } -} - -/** - * Only accepts file names of the form *UI.java. The one exception - * is not accepting ComponentUI.java because we don't need to generate - * a TestALF class for it. - */ -class UIJavaFilter implements FilenameFilter { - public boolean accept(File dir, String name) { - if (name.equals("ComponentUI.java")) { - return false; - } else if (name.endsWith("UI.java")) { - return true; - } else { - return false; - } - } -} diff --git a/jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java b/jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java deleted file mode 100644 index aadab48cac1..00000000000 --- a/jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -//package com.myco.myalaf; //search for myalaf for other refs to package name - - -package build.tools.automulti; - -import java.util.Vector; -import java.lang.reflect.Method; -import javax.swing.*; -import javax.swing.plaf.*; - -/** - *

An auxiliary look and feel used for testing the Multiplexing - * look and feel. - *

- * - * @see UIManager#addAuxiliaryLookAndFeel - * @see javax.swing.plaf.multi - * - * @author Kathy Walrath - * @author Will Walker - */ -public class TestALFLookAndFeel extends LookAndFeel { - -////////////////////////////// -// LookAndFeel methods -////////////////////////////// - - /** - * Returns a string, suitable for use in menus, - * that identifies this look and feel. - * - * @return a string such as "Test Auxiliary Look and Feel" - */ - public String getName() { - return "Test Auxiliary Look and Feel"; - } - - /** - * Returns a string, suitable for use by applications/services, - * that identifies this look and feel. - * - * @return "TestALF" - */ - public String getID() { - return "TestALF"; - } - - /** - * Returns a one-line description of this look and feel. - * - * @return a descriptive string such as "Allows multiple UI instances per component instance" - */ - public String getDescription() { - return "Allows multiple UI instances per component instance"; - } - - /** - * Returns false; - * this look and feel is not native to any platform. - * - * @return false - */ - public boolean isNativeLookAndFeel() { - return false; - } - - /** - * Returns true; - * every platform permits this look and feel. - * - * @return true - */ - public boolean isSupportedLookAndFeel() { - return true; - } - - /** - * Creates, initializes, and returns - * the look and feel specific defaults. - * For this look and feel, - * the defaults consist solely of - * mappings of UI class IDs - * (such as "ButtonUI") - * to ComponentUI class names - * (such as "com.myco.myalaf.MultiButtonUI"). - * - * @return an initialized UIDefaults object - * @see javax.swing.JComponent#getUIClassID - */ - public UIDefaults getDefaults() { - System.out.println("In the TestALFLookAndFeel getDefaults method."); - UIDefaults table = new TestALFUIDefaults(); - //String prefix = "com.myco.myalaf.TestALF"; - String prefix = "TestALF"; - Object[] uiDefaults = { - "ButtonUI", prefix + "ButtonUI", - "CheckBoxMenuItemUI", prefix + "MenuItemUI", - "CheckBoxUI", prefix + "ButtonUI", - "ColorChooserUI", prefix + "ColorChooserUI", - "ComboBoxUI", prefix + "ComboBoxUI", - "DesktopIconUI", prefix + "DesktopIconUI", - "DesktopPaneUI", prefix + "DesktopPaneUI", - "EditorPaneUI", prefix + "TextUI", - "FileChooserUI", prefix + "FileChooserUI", - "FormattedTextFieldUI", prefix + "TextUI", - "InternalFrameUI", prefix + "InternalFrameUI", - "LabelUI", prefix + "LabelUI", - "ListUI", prefix + "ListUI", - "MenuBarUI", prefix + "MenuBarUI", - "MenuItemUI", prefix + "MenuItemUI", - "MenuUI", prefix + "MenuItemUI", - "OptionPaneUI", prefix + "OptionPaneUI", - "PanelUI", prefix + "PanelUI", - "PasswordFieldUI", prefix + "TextUI", - "PopupMenuSeparatorUI", prefix + "SeparatorUI", - "PopupMenuUI", prefix + "PopupMenuUI", - "ProgressBarUI", prefix + "ProgressBarUI", - "RadioButtonMenuItemUI", prefix + "MenuItemUI", - "RadioButtonUI", prefix + "ButtonUI", - "RootPaneUI", prefix + "RootPaneUI", - "ScrollBarUI", prefix + "ScrollBarUI", - "ScrollPaneUI", prefix + "ScrollPaneUI", - "SeparatorUI", prefix + "SeparatorUI", - "SliderUI", prefix + "SliderUI", - "SpinnerUI", prefix + "SpinnerUI", - "SplitPaneUI", prefix + "SplitPaneUI", - "TabbedPaneUI", prefix + "TabbedPaneUI", - "TableHeaderUI", prefix + "TableHeaderUI", - "TableUI", prefix + "TableUI", - "TextAreaUI", prefix + "TextUI", - "TextFieldUI", prefix + "TextUI", - "TextPaneUI", prefix + "TextUI", - "ToggleButtonUI", prefix + "ButtonUI", - "ToolBarSeparatorUI", prefix + "SeparatorUI", - "ToolBarUI", prefix + "ToolBarUI", - "ToolTipUI", prefix + "ToolTipUI", - "TreeUI", prefix + "TreeUI", - "ViewportUI", prefix + "ViewportUI", - }; - - table.putDefaults(uiDefaults); - return table; - } - -} - -/** - * We want the Test auxiliary look and feel to be quiet and fallback - * gracefully if it cannot find a UI. This class overrides the - * getUIError method of UIDefaults, which is the method that - * emits error messages when it cannot find a UI class in the - * LAF. - */ -class TestALFUIDefaults extends UIDefaults { - protected void getUIError(String msg) { - System.err.println("Test auxiliary L&F: " + msg); - } -} From e2a366414cf30606390865ef7044efa145133348 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Tue, 8 Jul 2008 16:40:38 +0400 Subject: [PATCH 08/45] 4916852: RFE: LTP: BorderLayout Persistence Delegate should use 1.5 API Reviewed-by: peterz, loneid --- .../share/classes/java/beans/MetaData.java | 54 +++++++----- .../XMLEncoder/java_awt_BorderLayout.java | 82 +++++++++++++++++++ .../beans/XMLEncoder/java_awt_Component.java | 58 +++++++++++++ 3 files changed, 172 insertions(+), 22 deletions(-) create mode 100644 jdk/test/java/beans/XMLEncoder/java_awt_BorderLayout.java create mode 100644 jdk/test/java/beans/XMLEncoder/java_awt_Component.java diff --git a/jdk/src/share/classes/java/beans/MetaData.java b/jdk/src/share/classes/java/beans/MetaData.java index 9bcd505c215..e2cb0326c69 100644 --- a/jdk/src/share/classes/java/beans/MetaData.java +++ b/jdk/src/share/classes/java/beans/MetaData.java @@ -986,14 +986,20 @@ class java_awt_Component_PersistenceDelegate extends DefaultPersistenceDelegate // null to defined values after the Windows are made visible - // special case them for now. if (!(oldInstance instanceof java.awt.Window)) { - String[] fieldNames = new String[]{"background", "foreground", "font"}; - for(int i = 0; i < fieldNames.length; i++) { - String name = fieldNames[i]; - Object oldValue = ReflectionUtils.getPrivateField(oldInstance, java.awt.Component.class, name, out.getExceptionListener()); - Object newValue = (newInstance == null) ? null : ReflectionUtils.getPrivateField(newInstance, java.awt.Component.class, name, out.getExceptionListener()); - if (oldValue != null && !oldValue.equals(newValue)) { - invokeStatement(oldInstance, "set" + NameGenerator.capitalize(name), new Object[]{oldValue}, out); - } + Object oldBackground = c.isBackgroundSet() ? c.getBackground() : null; + Object newBackground = c2.isBackgroundSet() ? c2.getBackground() : null; + if (!MetaData.equals(oldBackground, newBackground)) { + invokeStatement(oldInstance, "setBackground", new Object[] { oldBackground }, out); + } + Object oldForeground = c.isForegroundSet() ? c.getForeground() : null; + Object newForeground = c2.isForegroundSet() ? c2.getForeground() : null; + if (!MetaData.equals(oldForeground, newForeground)) { + invokeStatement(oldInstance, "setForeground", new Object[] { oldForeground }, out); + } + Object oldFont = c.isFontSet() ? c.getFont() : null; + Object newFont = c2.isFontSet() ? c2.getFont() : null; + if (!MetaData.equals(oldFont, newFont)) { + invokeStatement(oldInstance, "setFont", new Object[] { oldFont }, out); } } @@ -1104,26 +1110,30 @@ class java_awt_List_PersistenceDelegate extends DefaultPersistenceDelegate { // BorderLayout class java_awt_BorderLayout_PersistenceDelegate extends DefaultPersistenceDelegate { + private static final String[] CONSTRAINTS = { + BorderLayout.NORTH, + BorderLayout.SOUTH, + BorderLayout.EAST, + BorderLayout.WEST, + BorderLayout.CENTER, + BorderLayout.PAGE_START, + BorderLayout.PAGE_END, + BorderLayout.LINE_START, + BorderLayout.LINE_END, + }; + @Override protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); - String[] locations = {"north", "south", "east", "west", "center"}; - String[] names = {java.awt.BorderLayout.NORTH, java.awt.BorderLayout.SOUTH, - java.awt.BorderLayout.EAST, java.awt.BorderLayout.WEST, - java.awt.BorderLayout.CENTER}; - for(int i = 0; i < locations.length; i++) { - Object oldC = ReflectionUtils.getPrivateField(oldInstance, - java.awt.BorderLayout.class, - locations[i], - out.getExceptionListener()); - Object newC = ReflectionUtils.getPrivateField(newInstance, - java.awt.BorderLayout.class, - locations[i], - out.getExceptionListener()); + BorderLayout oldLayout = (BorderLayout) oldInstance; + BorderLayout newLayout = (BorderLayout) newInstance; + for (String constraints : CONSTRAINTS) { + Object oldC = oldLayout.getLayoutComponent(constraints); + Object newC = newLayout.getLayoutComponent(constraints); // Pending, assume any existing elements are OK. if (oldC != null && newC == null) { invokeStatement(oldInstance, "addLayoutComponent", - new Object[]{oldC, names[i]}, out); + new Object[] { oldC, constraints }, out); } } } diff --git a/jdk/test/java/beans/XMLEncoder/java_awt_BorderLayout.java b/jdk/test/java/beans/XMLEncoder/java_awt_BorderLayout.java new file mode 100644 index 00000000000..1eba0c21bac --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/java_awt_BorderLayout.java @@ -0,0 +1,82 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4916852 + * @summary Tests BorderLayout encoding + * @author Sergey Malenkov + */ + +import java.awt.BorderLayout; +import javax.swing.JLabel; + +public final class java_awt_BorderLayout extends AbstractTest { + private static final String[] CONSTRAINTS = { + BorderLayout.NORTH, + BorderLayout.SOUTH, + BorderLayout.EAST, + BorderLayout.WEST, + BorderLayout.CENTER, + BorderLayout.PAGE_START, + BorderLayout.PAGE_END, + BorderLayout.LINE_START, + BorderLayout.LINE_END, + }; + + public static void main(String[] args) { + new java_awt_BorderLayout().test(true); + } + + @Override + protected BorderLayout getObject() { + BorderLayout layout = new BorderLayout(); + update(layout, BorderLayout.EAST); + update(layout, BorderLayout.WEST); + update(layout, BorderLayout.NORTH); + update(layout, BorderLayout.SOUTH); + return layout; + } + + @Override + protected BorderLayout getAnotherObject() { + BorderLayout layout = getObject(); + update(layout, BorderLayout.CENTER); + return layout; + } + + @Override + protected void validate(BorderLayout before, BorderLayout after) { + super.validate(before, after); + + BeanValidator validator = new BeanValidator(); + for (String constraint : CONSTRAINTS) { + validator.validate(before.getLayoutComponent(constraint), + after.getLayoutComponent(constraint)); + } + } + + private static void update(BorderLayout layout, String constraints) { + layout.addLayoutComponent(new JLabel(constraints), constraints); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/java_awt_Component.java b/jdk/test/java/beans/XMLEncoder/java_awt_Component.java new file mode 100644 index 00000000000..a98424a3b7a --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/java_awt_Component.java @@ -0,0 +1,58 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4916852 + * @summary Tests Component encoding (background, foreground and font) + * @author Sergey Malenkov + */ + +import java.awt.Color; +import java.awt.Component; +import java.awt.Font; + +public final class java_awt_Component extends AbstractTest { + public static void main(String[] args) { + new java_awt_Component().test(true); + } + + @Override + protected Component getObject() { + Component component = new MyComponent(); + component.setBackground(Color.WHITE); + component.setFont(new Font(null, Font.BOLD, 5)); + return component; + } + + @Override + protected Component getAnotherObject() { + Component component = new MyComponent(); + component.setForeground(Color.BLACK); + component.setFont(new Font(null, Font.ITALIC, 6)); + return component; + } + + public static final class MyComponent extends Component { + } +} \ No newline at end of file From 1bdca97b29cf1ccfa27349d1198d07849df1c256 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 9 Jul 2008 15:25:38 +0400 Subject: [PATCH 09/45] 6351692: catch(Throwable) in java.beans.MetaData preventing thread shutdown Reviewed-by: peterz, loneid --- .../share/classes/java/beans/DefaultPersistenceDelegate.java | 2 +- jdk/src/share/classes/java/beans/EventHandler.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java b/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java index 6553a517200..5339aba83e4 100644 --- a/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java +++ b/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java @@ -298,7 +298,7 @@ public class DefaultPersistenceDelegate extends PersistenceDelegate { oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{}); newL = (EventListener[])MethodUtil.invoke(m, newInstance, new Object[]{}); } - catch (Throwable e2) { + catch (Exception e2) { try { Method m = type.getMethod("getListeners", new Class[]{Class.class}); oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{listenerType}); diff --git a/jdk/src/share/classes/java/beans/EventHandler.java b/jdk/src/share/classes/java/beans/EventHandler.java index 9d50dea91d1..43cd76ff383 100644 --- a/jdk/src/share/classes/java/beans/EventHandler.java +++ b/jdk/src/share/classes/java/beans/EventHandler.java @@ -404,7 +404,7 @@ public class EventHandler implements InvocationHandler { Object newTarget = MethodUtil.invoke(getter, target, new Object[]{}); return applyGetters(newTarget, rest); } - catch (Throwable e) { + catch (Exception e) { throw new RuntimeException("Failed to call method: " + first + " on " + target, e); } From 3916f38bd49205164c4f8c68c12cb46ee64204da Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 9 Jul 2008 19:29:07 +0400 Subject: [PATCH 10/45] 4994637: LTP: java.beans.java_util_Map_PersistenceDelegate: ConcurrentModificationException Reviewed-by: peterz, loneid --- .../share/classes/java/beans/MetaData.java | 2 +- .../java/beans/XMLEncoder/Test4994637.java | 58 +++++++++++++++++++ .../beans/XMLEncoder/java_util_HashMap.java | 24 ++++++-- 3 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 jdk/test/java/beans/XMLEncoder/Test4994637.java diff --git a/jdk/src/share/classes/java/beans/MetaData.java b/jdk/src/share/classes/java/beans/MetaData.java index e2cb0326c69..5d8fd697918 100644 --- a/jdk/src/share/classes/java/beans/MetaData.java +++ b/jdk/src/share/classes/java/beans/MetaData.java @@ -650,7 +650,7 @@ class java_util_Map_PersistenceDelegate extends DefaultPersistenceDelegate { // Remove the new elements. // Do this first otherwise we undo the adding work. if (newMap != null) { - for ( Object newKey : newMap.keySet() ) { + for (Object newKey : newMap.keySet().toArray()) { // PENDING: This "key" is not in the right environment. if (!oldMap.containsKey(newKey)) { invokeStatement(oldInstance, "remove", new Object[]{newKey}, out); diff --git a/jdk/test/java/beans/XMLEncoder/Test4994637.java b/jdk/test/java/beans/XMLEncoder/Test4994637.java new file mode 100644 index 00000000000..5476a8100bb --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/Test4994637.java @@ -0,0 +1,58 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4994637 + * @summary Tests custom map encoding + * @author Sergey Malenkov + */ + +import java.util.HashMap; + +public final class Test4994637 extends AbstractTest { + public static void main(String[] args) { + new Test4994637().test(true); + } + + @Override + protected CustomMap getObject() { + return new CustomMap(); + } + + @Override + protected CustomMap getAnotherObject() { + CustomMap map = new CustomMap(); + map.clear(); + map.put(null, "zero"); + return map; + } + + public static final class CustomMap extends HashMap { + public CustomMap() { + put("1", "one"); + put("2", "two"); + put("3", "three"); + } + } +} diff --git a/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java b/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java index 9a9771f80db..d9058003e4d 100644 --- a/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java +++ b/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2006-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 4631471 4921212 + * @bug 4631471 4921212 4994637 * @summary Tests HashMap encoding * @author Sergey Malenkov */ @@ -36,10 +36,17 @@ public final class java_util_HashMap extends AbstractTest> { new java_util_HashMap().test(true); } + @Override protected Map getObject() { - return new HashMap(); + Map map = new HashMap(); + map.put(null, null); + map.put("key", "value"); + map.put("key-null", "null-value"); + map.put("way", "remove"); + return map; } + @Override protected Map getAnotherObject() { Map map = new HashMap(); map.put(null, "null-value"); @@ -48,6 +55,7 @@ public final class java_util_HashMap extends AbstractTest> { return map; } + @Override protected void validate(Map before, Map after) { super.validate(before, after); validate(before); @@ -55,10 +63,18 @@ public final class java_util_HashMap extends AbstractTest> { } private static void validate(Map map) { - if (!map.isEmpty()) { + switch (map.size()) { + case 3: validate(map, null, "null-value"); validate(map, "key", "value"); validate(map, "key-null", null); + break; + case 4: + validate(map, null, null); + validate(map, "key", "value"); + validate(map, "key-null", "null-value"); + validate(map, "way", "remove"); + break; } } From e91ae90285a36fff3584aaf5b2017f8b762de829 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Fri, 18 Jul 2008 18:26:22 +0400 Subject: [PATCH 11/45] 6552812: Add HSL tab to JColorChooser Reviewed-by: peterz, avu --- .../plaf/basic/resources/basic.properties | 33 +- .../plaf/basic/resources/basic_de.properties | 33 +- .../plaf/basic/resources/basic_es.properties | 33 +- .../plaf/basic/resources/basic_fr.properties | 33 +- .../plaf/basic/resources/basic_it.properties | 33 +- .../plaf/basic/resources/basic_ja.properties | 33 +- .../plaf/basic/resources/basic_ko.properties | 33 +- .../plaf/basic/resources/basic_sv.properties | 33 +- .../basic/resources/basic_zh_CN.properties | 33 +- .../basic/resources/basic_zh_TW.properties | 33 +- .../ColorChooserComponentFactory.java | 19 +- .../swing/colorchooser/ColorChooserPanel.java | 182 ++++ .../javax/swing/colorchooser/ColorModel.java | 102 +++ .../swing/colorchooser/ColorModelCMYK.java | 94 ++ .../swing/colorchooser/ColorModelHSL.java | 188 ++++ .../swing/colorchooser/ColorModelHSV.java | 138 +++ .../javax/swing/colorchooser/ColorPanel.java | 210 +++++ .../colorchooser/DefaultHSBChooserPanel.java | 801 ------------------ .../colorchooser/DefaultRGBChooserPanel.java | 294 ------- .../swing/colorchooser/DiagramComponent.java | 160 ++++ .../swing/colorchooser/SlidingSpinner.java | 118 +++ .../swing/colorchooser/SyntheticImage.java | 166 ---- .../swing/colorchooser/ValueFormatter.java | 151 ++++ .../swing/plaf/basic/BasicColorChooserUI.java | 6 +- .../swing/JColorChooser/Test6524757.java | 166 ++-- .../swing/JColorChooser/Test6559154.java | 75 ++ 26 files changed, 1726 insertions(+), 1474 deletions(-) create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java delete mode 100644 jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java delete mode 100644 jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java delete mode 100644 jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ValueFormatter.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test6559154.java diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties index 6087def3607..4dac249bfa0 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=Sample Text Sample Text ColorChooser.swatchesNameText=Swatches ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Recent: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Red ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=Green ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=Blue ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties index 93660548035..b3455977738 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=90 ColorChooser.sampleText=Beispieltext Beispieltext ColorChooser.swatchesNameText=Muster ColorChooser.swatchesMnemonic=77 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Aktuell: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rot ColorChooser.rgbRedMnemonic=82 ColorChooser.rgbGreenText=Gr\u00fcn ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=Blau ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties index b553b26f065..75877dd6560 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=Texto de ejemplo Texto de ejemplo ColorChooser.swatchesNameText=Muestras ColorChooser.swatchesMnemonic=77 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Reciente: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=V -ColorChooser.hsbBlueText=A +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rojo ColorChooser.rgbRedMnemonic=74 ColorChooser.rgbGreenText=Verde ColorChooser.rgbGreenMnemonic=86 ColorChooser.rgbBlueText=Azul ColorChooser.rgbBlueMnemonic=76 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties index b18de0274a8..333a1a82fa1 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=Echantillon de texte Echantillon de texte ColorChooser.swatchesNameText=Echantillons ColorChooser.swatchesMnemonic=69 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Dernier : -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=V -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RVB ColorChooser.rgbMnemonic=86 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rouge ColorChooser.rgbRedMnemonic=71 ColorChooser.rgbGreenText=Vert ColorChooser.rgbGreenMnemonic=84 ColorChooser.rgbBlueText=Bleu ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties index 1c9f3790e6f..7bc69dbcf5e 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=Testo di prova Testo di prova ColorChooser.swatchesNameText=Colori campione ColorChooser.swatchesMnemonic=67 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Recenti: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rosso ColorChooser.rgbRedMnemonic=79 ColorChooser.rgbGreenText=Verde ColorChooser.rgbGreenMnemonic=69 ColorChooser.rgbBlueText=Blu ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties index 1b5a131cabd..5603e9aa1bc 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=\u30b5\u30f3\u30d7\u30eb\u30c6\u30ad\u30b9\u30c8 \u30b5\u30f3\u30d7\u30eb\u30c6\u30ad\u30b9\u30c8 ColorChooser.swatchesNameText=\u30b5\u30f3\u30d7\u30eb(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=5 ColorChooser.swatchesRecentText=\u6700\u65b0: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\u8d64(D) ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\u7dd1(N) ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\u9752(B) ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties index 9b873a43a61..f3866d01f31 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=\uc0d8\ud50c \ud14d\uc2a4\ud2b8 \uc0d8\ud50c \ud14d\uc2a4\ud2b8 ColorChooser.swatchesNameText=\uacac\ubcf8(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=3 ColorChooser.swatchesRecentText=\ucd5c\uadfc \ubaa9\ub85d: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\ube68\uac04\uc0c9(D) ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\ub179\uc0c9(N) ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\ud30c\ub780\uc0c9(B) ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties index 2b8561b812e..17ef3b2be26 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=84 ColorChooser.sampleText=Exempeltext Exempeltext ColorChooser.swatchesNameText=Prov ColorChooser.swatchesMnemonic=80 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Tidigare: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=R\u00f6d ColorChooser.rgbRedMnemonic=82 ColorChooser.rgbGreenText=Gr\u00f6n ColorChooser.rgbGreenMnemonic=71 ColorChooser.rgbBlueText=Bl\u00e5 ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties index 7ef35330d86..b030c20a944 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=\u6837\u54c1\u6587\u672c \u6837\u54c1\u6587\u672c ColorChooser.swatchesNameText=\u6837\u54c1(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=3 ColorChooser.swatchesRecentText=\u6700\u8fd1: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\u7ea2 ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\u7eff ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\u84dd ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties index dba0d76de28..47f99f0dcc9 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=\u7bc4\u4f8b\u6587\u5b57 \u7bc4\u4f8b\u6587\u5b57 ColorChooser.swatchesNameText=\u8abf\u8272\u677f(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=4 ColorChooser.swatchesRecentText=\u6700\u65b0\u9078\u64c7: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\u7d05\u8272(D) ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\u7da0\u8272(N) ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\u85cd\u8272(B) ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java index b36c6524d8a..0ee01e6cb5a 100644 --- a/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,7 @@ package javax.swing.colorchooser; -import javax.swing.*; - - +import javax.swing.JComponent; /** * A class designed to produce preconfigured "accessory" objects to @@ -49,16 +47,17 @@ public class ColorChooserComponentFactory { private ColorChooserComponentFactory() { } // can't instantiate - public static AbstractColorChooserPanel[] getDefaultChooserPanels() { - AbstractColorChooserPanel[] choosers = { new DefaultSwatchChooserPanel(), - new DefaultHSBChooserPanel(), - new DefaultRGBChooserPanel() }; - return choosers; + return new AbstractColorChooserPanel[] { + new DefaultSwatchChooserPanel(), + new ColorChooserPanel(new ColorModelHSV()), + new ColorChooserPanel(new ColorModelHSL()), + new ColorChooserPanel(new ColorModel()), + new ColorChooserPanel(new ColorModelCMYK()), + }; } public static JComponent getPreviewPanel() { return new DefaultPreviewPanel(); } - } diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java new file mode 100644 index 00000000000..46b5351c695 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java @@ -0,0 +1,182 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import java.awt.Color; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import javax.swing.Icon; +import javax.swing.JComponent; +import javax.swing.JFormattedTextField; +import javax.swing.JLabel; +import javax.swing.SwingConstants; + +final class ColorChooserPanel extends AbstractColorChooserPanel implements PropertyChangeListener { + + private static final int MASK = 0xFF000000; + private final ColorModel model; + private final ColorPanel panel; + private final DiagramComponent slider; + private final DiagramComponent diagram; + private final JFormattedTextField text; + private final JLabel label; + + ColorChooserPanel(ColorModel model) { + this.model = model; + this.panel = new ColorPanel(this.model); + this.slider = new DiagramComponent(this.panel, false); + this.diagram = new DiagramComponent(this.panel, true); + this.text = new JFormattedTextField(); + this.label = new JLabel(null, null, SwingConstants.RIGHT); + ValueFormatter.init(6, true, this.text); + } + + @Override + public void updateChooser() { + Color color = getColorFromModel(); + this.panel.setColor(color); + this.text.setValue(Integer.valueOf(color.getRGB())); + this.slider.repaint(); + this.diagram.repaint(); + } + + @Override + protected void buildChooser() { + if (0 == getComponentCount()) { + setLayout(new GridBagLayout()); + + GridBagConstraints gbc = new GridBagConstraints(); + + gbc.gridx = 3; + gbc.gridwidth = 2; + gbc.weighty = 1.0; + gbc.anchor = GridBagConstraints.NORTH; + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.insets.top = 10; + gbc.insets.right = 10; + add(this.panel, gbc); + + gbc.gridwidth = 1; + gbc.weightx = 1.0; + gbc.weighty = 0.0; + gbc.anchor = GridBagConstraints.CENTER; + gbc.insets.right = 5; + gbc.insets.bottom = 10; + add(this.label, gbc); + + gbc.gridx = 4; + gbc.weightx = 0.0; + gbc.insets.right = 10; + add(this.text, gbc); + + gbc.gridx = 2; + gbc.gridheight = 2; + gbc.anchor = GridBagConstraints.NORTH; + gbc.ipadx = this.text.getPreferredSize().height; + gbc.ipady = getPreferredSize().height; + add(this.slider, gbc); + + gbc.gridx = 1; + gbc.insets.left = 10; + gbc.ipadx = gbc.ipady; + add(this.diagram, gbc); + + this.label.setLabelFor(this.text); + this.text.addPropertyChangeListener("value", this); // NON-NLS: the property name + this.slider.setBorder(this.text.getBorder()); + this.diagram.setBorder(this.text.getBorder()); + + setInheritsPopupMenu(this, true); // CR:4966112 + } + String label = this.model.getText(this, "HexCode"); // NON-NLS: suffix + boolean visible = label != null; + this.text.setVisible(visible); + this.label.setVisible(visible); + if (visible) { + this.label.setText(label); + int mnemonic = this.model.getInteger(this, "HexCodeMnemonic"); // NON-NLS: suffix + if (mnemonic > 0) { + this.label.setDisplayedMnemonic(mnemonic); + mnemonic = this.model.getInteger(this, "HexCodeMnemonicIndex"); // NON-NLS: suffix + if (mnemonic >= 0) { + this.label.setDisplayedMnemonicIndex(mnemonic); + } + } + } + this.panel.buildPanel(); + } + + @Override + public String getDisplayName() { + return this.model.getText(this, "Name"); // NON-NLS: suffix + } + + @Override + public int getMnemonic() { + return this.model.getInteger(this, "Mnemonic"); // NON-NLS: suffix + } + + @Override + public int getDisplayedMnemonicIndex() { + return this.model.getInteger(this, "DisplayedMnemonicIndex"); // NON-NLS: suffix + } + + @Override + public Icon getSmallDisplayIcon() { + return null; + } + + @Override + public Icon getLargeDisplayIcon() { + return null; + } + + public void propertyChange(PropertyChangeEvent event) { + Object object = event.getNewValue(); + if (object instanceof Integer) { + int value = MASK & getColorFromModel().getRGB() | (Integer) object; + getColorSelectionModel().setSelectedColor(new Color(value, true)); + } + this.text.selectAll(); + } + + /** + * Allows to show context popup for all components recursively. + * + * @param component the root component of the tree + * @param value whether or not the popup menu is inherited + */ + private static void setInheritsPopupMenu(JComponent component, boolean value) { + component.setInheritsPopupMenu(value); + for (Object object : component.getComponents()) { + if (object instanceof JComponent) { + setInheritsPopupMenu((JComponent) object, value); + } + } + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java new file mode 100644 index 00000000000..955ed162663 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java @@ -0,0 +1,102 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import java.awt.Component; +import javax.swing.UIManager; + +class ColorModel { + + private final String prefix; + private final String[] labels; + + ColorModel(String name, String... labels) { + this.prefix = "ColorChooser." + name; // NON-NLS: default prefix + this.labels = labels; + } + + ColorModel() { + this("rgb", "Red", "Green", "Blue", "Alpha"); // NON-NLS: components + } + + void setColor(int color, float[] model) { + model[0] = normalize(color >> 16); + model[1] = normalize(color >> 8); + model[2] = normalize(color); + model[3] = normalize(color >> 24); + } + + int getColor(float[] model) { + return to8bit(model[2]) | (to8bit(model[1]) << 8) | (to8bit(model[0]) << 16) | (to8bit(model[3]) << 24); + } + + int getCount() { + return this.labels.length; + } + + int getMinimum(int index) { + return 0; + } + + int getMaximum(int index) { + return 255; + } + + float getDefault(int index) { + return 0.0f; + } + + final String getLabel(Component component, int index) { + return getText(component, this.labels[index]); + } + + private static float normalize(int value) { + return (float) (value & 0xFF) / 255.0f; + } + + private static int to8bit(float value) { + return (int) (255.0f * value); + } + + final String getText(Component component, String suffix) { + return UIManager.getString(this.prefix + suffix + "Text", component.getLocale()); // NON-NLS: default postfix + } + + final int getInteger(Component component, String suffix) { + Object value = UIManager.get(this.prefix + suffix, component.getLocale()); + if (value instanceof Integer) { + return (Integer) value; + } + if (value instanceof String) { + try { + return Integer.parseInt((String) value); + } + catch (NumberFormatException exception) { + } + } + return -1; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java new file mode 100644 index 00000000000..77a7ca55594 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java @@ -0,0 +1,94 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +final class ColorModelCMYK extends ColorModel { + + ColorModelCMYK() { + super("cmyk", "Cyan", "Magenta", "Yellow", "Black", "Alpha"); // NON-NLS: components + } + + @Override + void setColor(int color, float[] space) { + super.setColor(color, space); + space[4] = space[3]; + RGBtoCMYK(space, space); + } + + @Override + int getColor(float[] space) { + CMYKtoRGB(space, space); + space[3] = space[4]; + return super.getColor(space); + } + + /** + * Converts CMYK components of a color to a set of RGB components. + * + * @param cmyk a float array with length equal to + * the number of CMYK components + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @return a float array that contains RGB components + */ + private static float[] CMYKtoRGB(float[] cmyk, float[] rgb) { + if (rgb == null) { + rgb = new float[3]; + } + rgb[0] = 1.0f + cmyk[0] * cmyk[3] - cmyk[3] - cmyk[0]; + rgb[1] = 1.0f + cmyk[1] * cmyk[3] - cmyk[3] - cmyk[1]; + rgb[2] = 1.0f + cmyk[2] * cmyk[3] - cmyk[3] - cmyk[2]; + return rgb; + } + + /** + * Converts RGB components of a color to a set of CMYK components. + * + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @param cmyk a float array with length equal to + * the number of CMYK components + * @return a float array that contains CMYK components + */ + private static float[] RGBtoCMYK(float[] rgb, float[] cmyk) { + if (cmyk == null) { + cmyk = new float[4]; + } + float max = ColorModelHSL.max(rgb[0], rgb[1], rgb[2]); + if (max > 0.0f) { + cmyk[0] = 1.0f - rgb[0] / max; + cmyk[1] = 1.0f - rgb[1] / max; + cmyk[2] = 1.0f - rgb[2] / max; + } + else { + cmyk[0] = 0.0f; + cmyk[1] = 0.0f; + cmyk[2] = 0.0f; + } + cmyk[3] = 1.0f - max; + return cmyk; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java new file mode 100644 index 00000000000..85b0c8e5da4 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java @@ -0,0 +1,188 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +final class ColorModelHSL extends ColorModel { + + ColorModelHSL() { + super("hsl", "Hue", "Saturation", "Lightness", "Transparency"); // NON-NLS: components + } + + @Override + void setColor(int color, float[] space) { + super.setColor(color, space); + RGBtoHSL(space, space); + space[3] = 1.0f - space[3]; + } + + @Override + int getColor(float[] space) { + space[3] = 1.0f - space[3]; + HSLtoRGB(space, space); + return super.getColor(space); + } + + @Override + int getMaximum(int index) { + return (index == 0) ? 360 : 100; + } + + @Override + float getDefault(int index) { + return (index == 0) ? -1.0f : (index == 2) ? 0.5f : 1.0f; + } + + /** + * Converts HSL components of a color to a set of RGB components. + * + * @param hsl a float array with length equal to + * the number of HSL components + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @return a float array that contains RGB components + */ + private static float[] HSLtoRGB(float[] hsl, float[] rgb) { + if (rgb == null) { + rgb = new float[3]; + } + float hue = hsl[0]; + float saturation = hsl[1]; + float lightness = hsl[2]; + + if (saturation > 0.0f) { + hue = (hue < 1.0f) ? hue * 6.0f : 0.0f; + float q = lightness + saturation * ((lightness > 0.5f) ? 1.0f - lightness : lightness); + float p = 2.0f * lightness - q; + rgb[0]= normalize(q, p, (hue < 4.0f) ? (hue + 2.0f) : (hue - 4.0f)); + rgb[1]= normalize(q, p, hue); + rgb[2]= normalize(q, p, (hue < 2.0f) ? (hue + 4.0f) : (hue - 2.0f)); + } + else { + rgb[0] = lightness; + rgb[1] = lightness; + rgb[2] = lightness; + } + return rgb; + } + + /** + * Converts RGB components of a color to a set of HSL components. + * + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @param hsl a float array with length equal to + * the number of HSL components + * @return a float array that contains HSL components + */ + private static float[] RGBtoHSL(float[] rgb, float[] hsl) { + if (hsl == null) { + hsl = new float[3]; + } + float max = max(rgb[0], rgb[1], rgb[2]); + float min = min(rgb[0], rgb[1], rgb[2]); + + float summa = max + min; + float saturation = max - min; + if (saturation > 0.0f) { + saturation /= (summa > 1.0f) + ? 2.0f - summa + : summa; + } + hsl[0] = getHue(rgb[0], rgb[1], rgb[2], max, min); + hsl[1] = saturation; + hsl[2] = summa / 2.0f; + return hsl; + } + + /** + * Returns the smaller of three color components. + * + * @param red the red component of the color + * @param green the green component of the color + * @param blue the blue component of the color + * @return the smaller of {@code red}, {@code green} and {@code blue} + */ + static float min(float red, float green, float blue) { + float min = (red < green) ? red : green; + return (min < blue) ? min : blue; + } + + /** + * Returns the larger of three color components. + * + * @param red the red component of the color + * @param green the green component of the color + * @param blue the blue component of the color + * @return the larger of {@code red}, {@code green} and {@code blue} + */ + static float max(float red, float green, float blue) { + float max = (red > green) ? red : green; + return (max > blue) ? max : blue; + } + + /** + * Calculates the hue component for HSL and HSV color spaces. + * + * @param red the red component of the color + * @param green the green component of the color + * @param blue the blue component of the color + * @param max the larger of {@code red}, {@code green} and {@code blue} + * @param min the smaller of {@code red}, {@code green} and {@code blue} + * @return the hue component + */ + static float getHue(float red, float green, float blue, float max, float min) { + float hue = max - min; + if (hue > 0.0f) { + if (max == red) { + hue = (green - blue) / hue; + if (hue < 0.0f) { + hue += 6.0f; + } + } + else if (max == green) { + hue = 2.0f + (blue - red) / hue; + } + else /*max == blue*/ { + hue = 4.0f + (red - green) / hue; + } + hue /= 6.0f; + } + return hue; + } + + private static float normalize(float q, float p, float color) { + if (color < 1.0f) { + return p + (q - p) * color; + } + if (color < 3.0f) { + return q; + } + if (color < 4.0f) { + return p + (q - p) * (4.0f - color); + } + return p; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java new file mode 100644 index 00000000000..e33eef77dfe --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java @@ -0,0 +1,138 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +final class ColorModelHSV extends ColorModel { + + ColorModelHSV() { + super("hsv", "Hue", "Saturation", "Value", "Transparency"); // NON-NLS: components + } + + @Override + void setColor(int color, float[] space) { + super.setColor(color, space); + RGBtoHSV(space, space); + space[3] = 1.0f - space[3]; + } + + @Override + int getColor(float[] space) { + space[3] = 1.0f - space[3]; + HSVtoRGB(space, space); + return super.getColor(space); + } + + @Override + int getMaximum(int index) { + return (index == 0) ? 360 : 100; + } + + @Override + float getDefault(int index) { + return (index == 0) ? -1.0f : 1.0f; + } + + /** + * Converts HSV components of a color to a set of RGB components. + * + * @param hsv a float array with length equal to + * the number of HSV components + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @return a float array that contains RGB components + */ + private static float[] HSVtoRGB(float[] hsv, float[] rgb) { + if (rgb == null) { + rgb = new float[3]; + } + float hue = hsv[0]; + float saturation = hsv[1]; + float value = hsv[2]; + + rgb[0] = value; + rgb[1] = value; + rgb[2] = value; + + if (saturation > 0.0f) { + hue = (hue < 1.0f) ? hue * 6.0f : 0.0f; + int integer = (int) hue; + float f = hue - (float) integer; + switch (integer) { + case 0: + rgb[1] *= 1.0f - saturation * (1.0f - f); + rgb[2] *= 1.0f - saturation; + break; + case 1: + rgb[0] *= 1.0f - saturation * f; + rgb[2] *= 1.0f - saturation; + break; + case 2: + rgb[0] *= 1.0f - saturation; + rgb[2] *= 1.0f - saturation * (1.0f - f); + break; + case 3: + rgb[0] *= 1.0f - saturation; + rgb[1] *= 1.0f - saturation * f; + break; + case 4: + rgb[0] *= 1.0f - saturation * (1.0f - f); + rgb[1] *= 1.0f - saturation; + break; + case 5: + rgb[1] *= 1.0f - saturation; + rgb[2] *= 1.0f - saturation * f; + break; + } + } + return rgb; + } + + /** + * Converts RGB components of a color to a set of HSV components. + * + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @param hsv a float array with length equal to + * the number of HSV components + * @return a float array that contains HSV components + */ + private static float[] RGBtoHSV(float[] rgb, float[] hsv) { + if (hsv == null) { + hsv = new float[3]; + } + float max = ColorModelHSL.max(rgb[0], rgb[1], rgb[2]); + float min = ColorModelHSL.min(rgb[0], rgb[1], rgb[2]); + + float saturation = max - min; + if (saturation > 0.0f) { + saturation /= max; + } + hsv[0] = ColorModelHSL.getHue(rgb[0], rgb[1], rgb[2], max, min); + hsv[1] = saturation; + hsv[2] = max; + return hsv; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java new file mode 100644 index 00000000000..6e9329dbefb --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java @@ -0,0 +1,210 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import java.awt.Color; +import java.awt.ContainerOrderFocusTraversalPolicy; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.ButtonGroup; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.border.EmptyBorder; + +final class ColorPanel extends JPanel implements ActionListener { + + private final SlidingSpinner[] spinners = new SlidingSpinner[5]; + private final float[] values = new float[this.spinners.length]; + + private final ColorModel model; + private Color color; + private int x = 1; + private int y = 2; + private int z; + + ColorPanel(ColorModel model) { + super(new GridBagLayout()); + + GridBagConstraints gbc = new GridBagConstraints(); + gbc.fill = GridBagConstraints.HORIZONTAL; + + gbc.gridx = 1; + ButtonGroup group = new ButtonGroup(); + EmptyBorder border = null; + for (int i = 0; i < this.spinners.length; i++) { + if (i < 3) { + JRadioButton button = new JRadioButton(); + if (i == 0) { + Insets insets = button.getInsets(); + insets.left = button.getPreferredSize().width; + border = new EmptyBorder(insets); + button.setSelected(true); + gbc.insets.top = 5; + } + add(button, gbc); + group.add(button); + button.setActionCommand(Integer.toString(i)); + button.addActionListener(this); + this.spinners[i] = new SlidingSpinner(this, button); + } + else { + JLabel label = new JLabel(); + add(label, gbc); + label.setBorder(border); + label.setFocusable(false); + this.spinners[i] = new SlidingSpinner(this, label); + } + } + gbc.gridx = 2; + gbc.weightx = 1.0; + gbc.insets.top = 0; + gbc.insets.left = 5; + for (SlidingSpinner spinner : this.spinners) { + add(spinner.getSlider(), gbc); + gbc.insets.top = 5; + } + gbc.gridx = 3; + gbc.weightx = 0.0; + gbc.insets.top = 0; + for (SlidingSpinner spinner : this.spinners) { + add(spinner.getSpinner(), gbc); + gbc.insets.top = 5; + } + setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy()); + setFocusTraversalPolicyProvider(true); + setFocusable(false); + + this.model = model; + } + + public void actionPerformed(ActionEvent event) { + try { + this.z = Integer.parseInt(event.getActionCommand()); + this.y = (this.z != 2) ? 2 : 1; + this.x = (this.z != 0) ? 0 : 1; + getParent().repaint(); + } + catch (NumberFormatException exception) { + } + } + + void buildPanel() { + int count = this.model.getCount(); + this.spinners[4].setVisible(count > 4); + for (int i = 0; i < count; i++) { + Object object = this.spinners[i].getLabel(); + if (object instanceof JRadioButton) { + JRadioButton button = (JRadioButton) object; + button.setText(this.model.getLabel(this, i)); + } + else if (object instanceof JLabel) { + JLabel label = (JLabel) object; + label.setText(this.model.getLabel(this, i)); + } + this.spinners[i].setRange(this.model.getMinimum(i), this.model.getMaximum(i)); + this.spinners[i].setValue(this.values[i]); + } + } + + void colorChanged() { + this.color = new Color(getColor(0), true); + Object parent = getParent(); + if (parent instanceof ColorChooserPanel) { + ColorChooserPanel chooser = (ColorChooserPanel) parent; + chooser.getColorSelectionModel().setSelectedColor(this.color); + chooser.repaint(); + } + } + + float getValueX() { + return this.spinners[this.x].getValue(); + } + + float getValueY() { + return 1.0f - this.spinners[this.y].getValue(); + } + + float getValueZ() { + return 1.0f - this.spinners[this.z].getValue(); + } + + void setValue(float z) { + this.spinners[this.z].setValue(1.0f - z); + colorChanged(); + } + + void setValue(float x, float y) { + this.spinners[this.x].setValue(x); + this.spinners[this.y].setValue(1.0f - y); + colorChanged(); + } + + int getColor(float z) { + setDefaultValue(this.x); + setDefaultValue(this.y); + this.values[this.z] = 1.0f - z; + return getColor(3); + } + + int getColor(float x, float y) { + this.values[this.x] = x; + this.values[this.y] = 1.0f - y; + setValue(this.z); + return getColor(3); + } + + void setColor(Color color) { + if (!color.equals(this.color)) { + this.color = color; + this.model.setColor(color.getRGB(), this.values); + for (int i = 0; i < this.model.getCount(); i++) { + this.spinners[i].setValue(this.values[i]); + } + } + } + + private int getColor(int index) { + while (index < this.model.getCount()) { + setValue(index++); + } + return this.model.getColor(this.values); + } + + private void setValue(int index) { + this.values[index] = this.spinners[index].getValue(); + } + + private void setDefaultValue(int index) { + float value = this.model.getDefault(index); + this.values[index] = (value < 0.0f) + ? this.spinners[index].getValue() + : value; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java b/jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java deleted file mode 100644 index 89759e247a4..00000000000 --- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java +++ /dev/null @@ -1,801 +0,0 @@ -/* - * Copyright 1998-2004 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package javax.swing.colorchooser; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import javax.swing.event.*; -import javax.swing.border.*; -import java.awt.image.*; -import java.util.Locale; - -/** - * Implements the default HSB Color chooser - * - * @author Tom Santos - * @author Steve Wilson - * @author Mark Davidson - * @author Shannon Hickey - */ -class DefaultHSBChooserPanel extends AbstractColorChooserPanel implements ChangeListener, HierarchyListener { - - private transient HSBImage palette; - private transient HSBImage sliderPalette; - - private transient Image paletteImage; - private transient Image sliderPaletteImage; - - private JSlider slider; - private JSpinner hField; - private JSpinner sField; - private JSpinner bField; - - private JTextField redField; - private JTextField greenField; - private JTextField blueField; - - private boolean isAdjusting = false; // Flag which indicates that values are set internally - private Point paletteSelection = new Point(); - private JLabel paletteLabel; - private JLabel sliderPaletteLabel; - - private JRadioButton hRadio; - private JRadioButton sRadio; - private JRadioButton bRadio; - - private static final int PALETTE_DIMENSION = 200; - private static final int MAX_HUE_VALUE = 359; - private static final int MAX_SATURATION_VALUE = 100; - private static final int MAX_BRIGHTNESS_VALUE = 100; - - private int currentMode = HUE_MODE; - - private static final int HUE_MODE = 0; - private static final int SATURATION_MODE = 1; - private static final int BRIGHTNESS_MODE = 2; - - public DefaultHSBChooserPanel() { - } - - private void addPaletteListeners() { - paletteLabel.addMouseListener(new MouseAdapter() { - public void mousePressed(MouseEvent e ) { - float[] hsb = new float[3]; - palette.getHSBForLocation( e.getX(), e.getY(), hsb ); - updateHSB( hsb[0], hsb[1], hsb[2] ); - } - }); - - paletteLabel.addMouseMotionListener(new MouseMotionAdapter() { - public void mouseDragged( MouseEvent e ){ - int labelWidth = paletteLabel.getWidth(); - - int labelHeight = paletteLabel.getHeight(); - int x = e.getX(); - int y = e.getY(); - - if ( x >= labelWidth ) { - x = labelWidth - 1; - } - - if ( y >= labelHeight ) { - y = labelHeight - 1; - } - - if ( x < 0 ) { - x = 0; - } - - if ( y < 0 ) { - y = 0; - } - - float[] hsb = new float[3]; - palette.getHSBForLocation( x, y, hsb ); - updateHSB( hsb[0], hsb[1], hsb[2] ); - } - }); - } - - private void updatePalette( float h, float s, float b ) { - int x = 0; - int y = 0; - - switch ( currentMode ) { - case HUE_MODE: - if ( h != palette.getHue() ) { - palette.setHue( h ); - palette.nextFrame(); - } - x = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION); - y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION); - break; - case SATURATION_MODE: - if ( s != palette.getSaturation() ) { - palette.setSaturation( s ); - palette.nextFrame(); - } - x = (int)(h * PALETTE_DIMENSION); - y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION); - break; - case BRIGHTNESS_MODE: - if ( b != palette.getBrightness() ) { - palette.setBrightness( b ); - palette.nextFrame(); - } - x = (int)(h * PALETTE_DIMENSION); - y = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION); - break; - } - - paletteSelection.setLocation( x, y ); - paletteLabel.repaint(); - } - - private void updateSlider( float h, float s, float b ) { - // Update the slider palette if necessary. - // When the slider is the hue slider or the hue hasn't changed, - // the hue of the palette will not need to be updated. - if (currentMode != HUE_MODE && h != sliderPalette.getHue() ) { - sliderPalette.setHue( h ); - sliderPalette.nextFrame(); - } - - float value = 0f; - - switch ( currentMode ) { - case HUE_MODE: - value = h; - break; - case SATURATION_MODE: - value = s; - break; - case BRIGHTNESS_MODE: - value = b; - break; - } - - slider.setValue( Math.round(value * (slider.getMaximum())) ); - } - - private void updateHSBTextFields( float hue, float saturation, float brightness ) { - int h = Math.round(hue * 359); - int s = Math.round(saturation * 100); - int b = Math.round(brightness * 100); - - if (((Integer)hField.getValue()).intValue() != h) { - hField.setValue(new Integer(h)); - } - if (((Integer)sField.getValue()).intValue() != s) { - sField.setValue(new Integer(s)); - } - if (((Integer)bField.getValue()).intValue() != b) { - bField.setValue(new Integer(b)); - } - } - - /** - * Updates the values of the RGB fields to reflect the new color change - */ - private void updateRGBTextFields( Color color ) { - redField.setText(String.valueOf(color.getRed())); - greenField.setText(String.valueOf(color.getGreen())); - blueField.setText(String.valueOf(color.getBlue())); - } - - /** - * Main internal method of updating the ui controls and the color model. - */ - private void updateHSB( float h, float s, float b ) { - if ( !isAdjusting ) { - isAdjusting = true; - - updatePalette( h, s, b ); - updateSlider( h, s, b ); - updateHSBTextFields( h, s, b ); - - Color color = Color.getHSBColor(h, s, b); - updateRGBTextFields( color ); - - getColorSelectionModel().setSelectedColor( color ); - - isAdjusting = false; - } - } - - /** - * Invoked automatically when the model's state changes. - * It is also called by installChooserPanel to allow - * you to set up the initial state of your chooser. - * Override this method to update your ChooserPanel. - */ - public void updateChooser() { - if ( !isAdjusting ) { - float[] hsb = getHSBColorFromModel(); - updateHSB( hsb[0], hsb[1], hsb[2] ); - } - } - - public void installChooserPanel(JColorChooser enclosingChooser) { - super.installChooserPanel(enclosingChooser); - setInheritsPopupMenu(true); - addHierarchyListener(this); - } - - /** - * Invoked when the panel is removed from the chooser. - */ - public void uninstallChooserPanel(JColorChooser enclosingChooser) { - super.uninstallChooserPanel(enclosingChooser); - cleanupPalettesIfNecessary(); - removeAll(); - removeHierarchyListener(this); - } - - /** - * Returns an float array containing the HSB values of the selected color from - * the ColorSelectionModel - */ - private float[] getHSBColorFromModel() { - Color color = getColorFromModel(); - float[] hsb = new float[3]; - Color.RGBtoHSB( color.getRed(), color.getGreen(), color.getBlue(), hsb ); - - return hsb; - } - - /** - * Builds a new chooser panel. - */ - protected void buildChooser() { - setLayout(new BorderLayout()); - JComponent spp = buildSliderPalettePanel(); - spp.setInheritsPopupMenu(true); - add(spp, BorderLayout.BEFORE_LINE_BEGINS); - - JPanel controlHolder = new JPanel(new SmartGridLayout(1,3)); - JComponent hsbControls = buildHSBControls(); - hsbControls.setInheritsPopupMenu(true); - controlHolder.add(hsbControls); - - controlHolder.add(new JLabel(" ")); // spacer - - JComponent rgbControls = buildRGBControls(); - rgbControls.setInheritsPopupMenu(true); - controlHolder.add(rgbControls); - controlHolder.setInheritsPopupMenu(true); - - controlHolder.setBorder(new EmptyBorder( 10, 5, 10, 5)); - add( controlHolder, BorderLayout.CENTER); - } - - /** - * Creates the panel with the uneditable RGB field - */ - private JComponent buildRGBControls() { - JPanel panel = new JPanel(new SmartGridLayout(2,3)); - panel.setInheritsPopupMenu(true); - - Color color = getColorFromModel(); - redField = new JTextField( String.valueOf(color.getRed()), 3 ); - redField.setEditable(false); - redField.setHorizontalAlignment( JTextField.RIGHT ); - redField.setInheritsPopupMenu(true); - - greenField = new JTextField(String.valueOf(color.getGreen()), 3 ); - greenField.setEditable(false); - greenField.setHorizontalAlignment( JTextField.RIGHT ); - greenField.setInheritsPopupMenu(true); - - blueField = new JTextField( String.valueOf(color.getBlue()), 3 ); - blueField.setEditable(false); - blueField.setHorizontalAlignment( JTextField.RIGHT ); - blueField.setInheritsPopupMenu(true); - - Locale locale = getLocale(); - String redString = UIManager.getString("ColorChooser.hsbRedText", locale); - String greenString = UIManager.getString("ColorChooser.hsbGreenText", locale); - String blueString = UIManager.getString("ColorChooser.hsbBlueText", locale); - - panel.add( new JLabel(redString) ); - panel.add( redField ); - panel.add( new JLabel(greenString) ); - panel.add( greenField ); - panel.add( new JLabel(blueString) ); - panel.add( blueField ); - - return panel; - } - - /** - * Creates the panel with the editable HSB fields and the radio buttons. - */ - private JComponent buildHSBControls() { - - Locale locale = getLocale(); - String hueString = UIManager.getString("ColorChooser.hsbHueText", locale); - String saturationString = UIManager.getString("ColorChooser.hsbSaturationText", locale); - String brightnessString = UIManager.getString("ColorChooser.hsbBrightnessText", locale); - - RadioButtonHandler handler = new RadioButtonHandler(); - - hRadio = new JRadioButton(hueString); - hRadio.addActionListener(handler); - hRadio.setSelected(true); - hRadio.setInheritsPopupMenu(true); - - sRadio = new JRadioButton(saturationString); - sRadio.addActionListener(handler); - sRadio.setInheritsPopupMenu(true); - - bRadio = new JRadioButton(brightnessString); - bRadio.addActionListener(handler); - bRadio.setInheritsPopupMenu(true); - - ButtonGroup group = new ButtonGroup(); - group.add(hRadio); - group.add(sRadio); - group.add(bRadio); - - float[] hsb = getHSBColorFromModel(); - - hField = new JSpinner(new SpinnerNumberModel((int)(hsb[0] * 359), 0, 359, 1)); - sField = new JSpinner(new SpinnerNumberModel((int)(hsb[1] * 100), 0, 100, 1)); - bField = new JSpinner(new SpinnerNumberModel((int)(hsb[2] * 100), 0, 100, 1)); - - hField.addChangeListener(this); - sField.addChangeListener(this); - bField.addChangeListener(this); - - hField.setInheritsPopupMenu(true); - sField.setInheritsPopupMenu(true); - bField.setInheritsPopupMenu(true); - - JPanel panel = new JPanel( new SmartGridLayout(2, 3) ); - - panel.add(hRadio); - panel.add(hField); - panel.add(sRadio); - panel.add(sField); - panel.add(bRadio); - panel.add(bField); - panel.setInheritsPopupMenu(true); - - return panel; - } - - /** - * Handler for the radio button classes. - */ - private class RadioButtonHandler implements ActionListener { - public void actionPerformed(ActionEvent evt) { - Object obj = evt.getSource(); - - if (obj instanceof JRadioButton) { - JRadioButton button = (JRadioButton)obj; - if (button == hRadio) { - setMode(HUE_MODE); - } else if (button == sRadio) { - setMode(SATURATION_MODE); - } else if (button == bRadio) { - setMode(BRIGHTNESS_MODE); - } - } - } - } - - private void setMode(int mode) { - if (currentMode == mode) { - return; - } - - isAdjusting = true; // Ensure no events propagate from changing slider value. - currentMode = mode; - - float[] hsb = getHSBColorFromModel(); - - switch (currentMode) { - case HUE_MODE: - slider.setInverted(true); - slider.setMaximum(MAX_HUE_VALUE); - palette.setValues(HSBImage.HSQUARE, hsb[0], 1.0f, 1.0f); - sliderPalette.setValues(HSBImage.HSLIDER, 0f, 1.0f, 1.0f); - break; - case SATURATION_MODE: - slider.setInverted(false); - slider.setMaximum(MAX_SATURATION_VALUE); - palette.setValues(HSBImage.SSQUARE, hsb[0], hsb[1], 1.0f); - sliderPalette.setValues(HSBImage.SSLIDER, hsb[0], 1.0f, 1.0f); - break; - case BRIGHTNESS_MODE: - slider.setInverted(false); - slider.setMaximum(MAX_BRIGHTNESS_VALUE); - palette.setValues(HSBImage.BSQUARE, hsb[0], 1.0f, hsb[2]); - sliderPalette.setValues(HSBImage.BSLIDER, hsb[0], 1.0f, 1.0f); - break; - } - - isAdjusting = false; - - palette.nextFrame(); - sliderPalette.nextFrame(); - - updateChooser(); - } - - protected JComponent buildSliderPalettePanel() { - - // This slider has to have a minimum of 0. A lot of math in this file is simplified due to this. - slider = new JSlider(JSlider.VERTICAL, 0, MAX_HUE_VALUE, 0); - slider.setInverted(true); - slider.setPaintTrack(false); - slider.setPreferredSize(new Dimension(slider.getPreferredSize().width, PALETTE_DIMENSION + 15)); - slider.addChangeListener(this); - slider.setInheritsPopupMenu(true); - // We're not painting ticks, but need to ask UI classes to - // paint arrow shape anyway, if possible. - slider.putClientProperty("Slider.paintThumbArrowShape", Boolean.TRUE); - paletteLabel = createPaletteLabel(); - addPaletteListeners(); - sliderPaletteLabel = new JLabel(); - - JPanel panel = new JPanel(); - panel.add( paletteLabel ); - panel.add( slider ); - panel.add( sliderPaletteLabel ); - - initializePalettesIfNecessary(); - - return panel; - } - - private void initializePalettesIfNecessary() { - if (palette != null) { - return; - } - - float[] hsb = getHSBColorFromModel(); - - switch(currentMode){ - case HUE_MODE: - palette = new HSBImage(HSBImage.HSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, hsb[0], 1.0f, 1.0f); - sliderPalette = new HSBImage(HSBImage.HSLIDER, 16, PALETTE_DIMENSION, 0f, 1.0f, 1.0f); - break; - case SATURATION_MODE: - palette = new HSBImage(HSBImage.SSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, hsb[1], 1.0f); - sliderPalette = new HSBImage(HSBImage.SSLIDER, 16, PALETTE_DIMENSION, 1.0f, 0f, 1.0f); - break; - case BRIGHTNESS_MODE: - palette = new HSBImage(HSBImage.BSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, 1.0f, hsb[2]); - sliderPalette = new HSBImage(HSBImage.BSLIDER, 16, PALETTE_DIMENSION, 1.0f, 1.0f, 0f); - break; - } - paletteImage = Toolkit.getDefaultToolkit().createImage(palette); - sliderPaletteImage = Toolkit.getDefaultToolkit().createImage(sliderPalette); - - paletteLabel.setIcon(new ImageIcon(paletteImage)); - sliderPaletteLabel.setIcon(new ImageIcon(sliderPaletteImage)); - } - - private void cleanupPalettesIfNecessary() { - if (palette == null) { - return; - } - - palette.aborted = true; - sliderPalette.aborted = true; - - palette.nextFrame(); - sliderPalette.nextFrame(); - - palette = null; - sliderPalette = null; - - paletteImage = null; - sliderPaletteImage = null; - - paletteLabel.setIcon(null); - sliderPaletteLabel.setIcon(null); - } - - protected JLabel createPaletteLabel() { - return new JLabel() { - protected void paintComponent( Graphics g ) { - super.paintComponent( g ); - g.setColor( Color.white ); - g.drawOval( paletteSelection.x - 4, paletteSelection.y - 4, 8, 8 ); - } - }; - } - - public String getDisplayName() { - return UIManager.getString("ColorChooser.hsbNameText", getLocale()); - } - - /** - * Provides a hint to the look and feel as to the - * KeyEvent.VK constant that can be used as a mnemonic to - * access the panel. A return value <= 0 indicates there is no mnemonic. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. - *

- * This implementation looks up the value from the default - * ColorChooser.hsbMnemonic, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.rgbMnemonic");. - * - * @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no - * mnemonic - * @see #getDisplayedMnemonicIndex - * @since 1.4 - */ - public int getMnemonic() { - return getInt("ColorChooser.hsbMnemonic", -1); - } - - /** - * Provides a hint to the look and feel as to the index of the character in - * getDisplayName that should be visually identified as the - * mnemonic. The look and feel should only use this if - * getMnemonic returns a value > 0. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. For example, - * a look and feel may wish to render each - * AbstractColorChooserPanel in a JTabbedPane, - * and further use this return value to underline a character in - * the getDisplayName. - *

- * This implementation looks up the value from the default - * ColorChooser.rgbDisplayedMnemonicIndex, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.hsbDisplayedMnemonicIndex");. - * - * @return Character index to render mnemonic for; -1 to provide no - * visual identifier for this panel. - * @see #getMnemonic - * @since 1.4 - */ - public int getDisplayedMnemonicIndex() { - return getInt("ColorChooser.hsbDisplayedMnemonicIndex", -1); - } - - public Icon getSmallDisplayIcon() { - return null; - } - - public Icon getLargeDisplayIcon() { - return null; - } - - /** - * Class for the slider and palette images. - */ - class HSBImage extends SyntheticImage { - protected float h = .0f; - protected float s = .0f; - protected float b = .0f; - protected float[] hsb = new float[3]; - - protected boolean isDirty = true; - protected int cachedY; - protected int cachedColor; - protected int type; - - private static final int HSQUARE = 0; - private static final int SSQUARE = 1; - private static final int BSQUARE = 2; - private static final int HSLIDER = 3; - private static final int SSLIDER = 4; - private static final int BSLIDER = 5; - - protected HSBImage(int type, int width, int height, float h, float s, float b) { - super(width, height); - setValues(type, h, s, b); - } - - public void setValues(int type, float h, float s, float b) { - this.type = type; - cachedY = -1; - cachedColor = 0; - setHue( h ); - setSaturation( s ); - setBrightness( b ); - } - - public final void setHue( float hue ) { - h = hue; - } - - public final void setSaturation( float saturation ) { - s = saturation; - } - - public final void setBrightness( float brightness ) { - b = brightness; - } - - public final float getHue() { - return h; - } - - public final float getSaturation() { - return s; - } - - public final float getBrightness() { - return b; - } - - protected boolean isStatic() { - return false; - } - - public synchronized void nextFrame() { - isDirty = true; - notifyAll(); - } - - public synchronized void addConsumer(ImageConsumer ic) { - isDirty = true; - super.addConsumer(ic); - } - - private int getRGBForLocation( int x, int y ) { - if (type >= HSLIDER && y == cachedY) { - return cachedColor; - } - - getHSBForLocation( x, y, hsb ); - cachedY = y; - cachedColor = Color.HSBtoRGB( hsb[0], hsb[1], hsb[2] ); - - return cachedColor; - } - - public void getHSBForLocation( int x, int y, float[] hsbArray ) { - switch (type) { - case HSQUARE: { - float saturationStep = ((float)x) / width; - float brightnessStep = ((float)y) / height; - hsbArray[0] = h; - hsbArray[1] = s - saturationStep; - hsbArray[2] = b - brightnessStep; - break; - } - case SSQUARE: { - float brightnessStep = ((float)y) / height; - float step = 1.0f / ((float)width); - hsbArray[0] = x * step; - hsbArray[1] = s; - hsbArray[2] = 1.0f - brightnessStep; - break; - } - case BSQUARE: { - float saturationStep = ((float)y) / height; - float step = 1.0f / ((float)width); - hsbArray[0] = x * step; - hsbArray[1] = 1.0f - saturationStep; - hsbArray[2] = b; - break; - } - case HSLIDER: { - float step = 1.0f / ((float)height); - hsbArray[0] = y * step; - hsbArray[1] = s; - hsbArray[2] = b; - break; - } - case SSLIDER: { - float saturationStep = ((float)y) / height; - hsbArray[0] = h; - hsbArray[1] = s - saturationStep; - hsbArray[2] = b; - break; - } - case BSLIDER: { - float brightnessStep = ((float)y) / height; - hsbArray[0] = h; - hsbArray[1] = s; - hsbArray[2] = b - brightnessStep; - break; - } - } - } - - /** - * Overriden method from SyntheticImage - */ - protected void computeRow( int y, int[] row ) { - if ( y == 0 ) { - synchronized ( this ) { - try { - while ( !isDirty ) { - wait(); - } - } catch (InterruptedException ie) { - } - isDirty = false; - } - } - - if (aborted) { - return; - } - - for ( int i = 0; i < row.length; ++i ) { - row[i] = getRGBForLocation( i, y ); - } - } - } - - public void stateChanged(ChangeEvent e) { - if (e.getSource() == slider) { - boolean modelIsAdjusting = slider.getModel().getValueIsAdjusting(); - - if (!modelIsAdjusting && !isAdjusting) { - int sliderValue = slider.getValue(); - int sliderRange = slider.getMaximum(); - float value = (float)sliderValue / (float)sliderRange; - - float[] hsb = getHSBColorFromModel(); - - switch ( currentMode ){ - case HUE_MODE: - updateHSB(value, hsb[1], hsb[2]); - break; - case SATURATION_MODE: - updateHSB(hsb[0], value, hsb[2]); - break; - case BRIGHTNESS_MODE: - updateHSB(hsb[0], hsb[1], value); - break; - } - } - } else if (e.getSource() instanceof JSpinner) { - float hue = ((Integer)hField.getValue()).floatValue() / 359f; - float saturation = ((Integer)sField.getValue()).floatValue() / 100f; - float brightness = ((Integer)bField.getValue()).floatValue() / 100f; - - updateHSB(hue, saturation, brightness); - } - } - - public void hierarchyChanged(HierarchyEvent he) { - if ((he.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) { - if (isDisplayable()) { - initializePalettesIfNecessary(); - } else { - cleanupPalettesIfNecessary(); - } - } - } - -} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java b/jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java deleted file mode 100644 index 28850dffaac..00000000000 --- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright 1998-2004 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package javax.swing.colorchooser; - -import javax.swing.*; -import javax.swing.event.*; -import java.awt.*; -import java.util.Locale; - -/** - * The standard RGB chooser. - *

- * Warning: - * Serialized objects of this class will not be compatible with - * future Swing releases. The current serialization support is - * appropriate for short term storage or RMI between applications running - * the same version of Swing. As of 1.4, support for long term storage - * of all JavaBeansTM - * has been added to the java.beans package. - * Please see {@link java.beans.XMLEncoder}. - * - * @author Steve Wilson - * @author Mark Davidson - * @see JColorChooser - * @see AbstractColorChooserPanel - */ -class DefaultRGBChooserPanel extends AbstractColorChooserPanel implements ChangeListener { - - protected JSlider redSlider; - protected JSlider greenSlider; - protected JSlider blueSlider; - protected JSpinner redField; - protected JSpinner blueField; - protected JSpinner greenField; - - private final int minValue = 0; - private final int maxValue = 255; - - private boolean isAdjusting = false; // indicates the fields are being set internally - - public DefaultRGBChooserPanel() { - super(); - setInheritsPopupMenu(true); - } - - /** - * Sets the values of the controls to reflect the color - */ - private void setColor( Color newColor ) { - int red = newColor.getRed(); - int blue = newColor.getBlue(); - int green = newColor.getGreen(); - - if (redSlider.getValue() != red) { - redSlider.setValue(red); - } - if (greenSlider.getValue() != green) { - greenSlider.setValue(green); - } - if (blueSlider.getValue() != blue) { - blueSlider.setValue(blue); - } - - if (((Integer)redField.getValue()).intValue() != red) - redField.setValue(new Integer(red)); - if (((Integer)greenField.getValue()).intValue() != green) - greenField.setValue(new Integer(green)); - if (((Integer)blueField.getValue()).intValue() != blue ) - blueField.setValue(new Integer(blue)); - } - - public String getDisplayName() { - return UIManager.getString("ColorChooser.rgbNameText", getLocale()); - } - - /** - * Provides a hint to the look and feel as to the - * KeyEvent.VK constant that can be used as a mnemonic to - * access the panel. A return value <= 0 indicates there is no mnemonic. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. - *

- * This implementation looks up the value from the default - * ColorChooser.rgbMnemonic, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.rgbMnemonic");. - * - * @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no - * mnemonic - * @see #getDisplayedMnemonicIndex - * @since 1.4 - */ - public int getMnemonic() { - return getInt("ColorChooser.rgbMnemonic", -1); - } - - /** - * Provides a hint to the look and feel as to the index of the character in - * getDisplayName that should be visually identified as the - * mnemonic. The look and feel should only use this if - * getMnemonic returns a value > 0. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. For example, - * a look and feel may wish to render each - * AbstractColorChooserPanel in a JTabbedPane, - * and further use this return value to underline a character in - * the getDisplayName. - *

- * This implementation looks up the value from the default - * ColorChooser.rgbDisplayedMnemonicIndex, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.rgbDisplayedMnemonicIndex");. - * - * @return Character index to render mnemonic for; -1 to provide no - * visual identifier for this panel. - * @see #getMnemonic - * @since 1.4 - */ - public int getDisplayedMnemonicIndex() { - return getInt("ColorChooser.rgbDisplayedMnemonicIndex", -1); - } - - public Icon getSmallDisplayIcon() { - return null; - } - - public Icon getLargeDisplayIcon() { - return null; - } - - /** - * The background color, foreground color, and font are already set to the - * defaults from the defaults table before this method is called. - */ - public void installChooserPanel(JColorChooser enclosingChooser) { - super.installChooserPanel(enclosingChooser); - } - - protected void buildChooser() { - - Locale locale = getLocale(); - String redString = UIManager.getString("ColorChooser.rgbRedText", locale); - String greenString = UIManager.getString("ColorChooser.rgbGreenText", locale); - String blueString = UIManager.getString("ColorChooser.rgbBlueText", locale); - - setLayout( new BorderLayout() ); - Color color = getColorFromModel(); - - - JPanel enclosure = new JPanel(); - enclosure.setLayout( new SmartGridLayout( 3, 3 ) ); - enclosure.setInheritsPopupMenu(true); - - // The panel that holds the sliders - - add( enclosure, BorderLayout.CENTER ); - // sliderPanel.setBorder(new LineBorder(Color.black)); - - // The row for the red value - JLabel l = new JLabel(redString); - l.setDisplayedMnemonic(getInt("ColorChooser.rgbRedMnemonic", -1)); - enclosure.add(l); - redSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getRed()); - redSlider.setMajorTickSpacing( 85 ); - redSlider.setMinorTickSpacing( 17 ); - redSlider.setPaintTicks( true ); - redSlider.setPaintLabels( true ); - redSlider.setInheritsPopupMenu(true); - enclosure.add( redSlider ); - redField = new JSpinner( - new SpinnerNumberModel(color.getRed(), minValue, maxValue, 1)); - l.setLabelFor(redSlider); - redField.setInheritsPopupMenu(true); - JPanel redFieldHolder = new JPanel(new CenterLayout()); - redFieldHolder.setInheritsPopupMenu(true); - redField.addChangeListener(this); - redFieldHolder.add(redField); - enclosure.add(redFieldHolder); - - - // The row for the green value - l = new JLabel(greenString); - l.setDisplayedMnemonic(getInt("ColorChooser.rgbGreenMnemonic", -1)); - enclosure.add(l); - greenSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getGreen()); - greenSlider.setMajorTickSpacing( 85 ); - greenSlider.setMinorTickSpacing( 17 ); - greenSlider.setPaintTicks( true ); - greenSlider.setPaintLabels( true ); - greenSlider.setInheritsPopupMenu(true); - enclosure.add(greenSlider); - greenField = new JSpinner( - new SpinnerNumberModel(color.getGreen(), minValue, maxValue, 1)); - l.setLabelFor(greenSlider); - greenField.setInheritsPopupMenu(true); - JPanel greenFieldHolder = new JPanel(new CenterLayout()); - greenFieldHolder.add(greenField); - greenFieldHolder.setInheritsPopupMenu(true); - greenField.addChangeListener(this); - enclosure.add(greenFieldHolder); - - // The slider for the blue value - l = new JLabel(blueString); - l.setDisplayedMnemonic(getInt("ColorChooser.rgbBlueMnemonic", -1)); - enclosure.add(l); - blueSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getBlue()); - blueSlider.setMajorTickSpacing( 85 ); - blueSlider.setMinorTickSpacing( 17 ); - blueSlider.setPaintTicks( true ); - blueSlider.setPaintLabels( true ); - blueSlider.setInheritsPopupMenu(true); - enclosure.add(blueSlider); - blueField = new JSpinner( - new SpinnerNumberModel(color.getBlue(), minValue, maxValue, 1)); - l.setLabelFor(blueSlider); - blueField.setInheritsPopupMenu(true); - JPanel blueFieldHolder = new JPanel(new CenterLayout()); - blueFieldHolder.add(blueField); - blueField.addChangeListener(this); - blueFieldHolder.setInheritsPopupMenu(true); - enclosure.add(blueFieldHolder); - - redSlider.addChangeListener( this ); - greenSlider.addChangeListener( this ); - blueSlider.addChangeListener( this ); - - redSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE); - greenSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE); - blueSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE); - } - - public void uninstallChooserPanel(JColorChooser enclosingChooser) { - super.uninstallChooserPanel(enclosingChooser); - removeAll(); - } - - public void updateChooser() { - if (!isAdjusting) { - isAdjusting = true; - - setColor(getColorFromModel()); - - isAdjusting = false; - } - } - - public void stateChanged( ChangeEvent e ) { - if ( e.getSource() instanceof JSlider && !isAdjusting) { - - int red = redSlider.getValue(); - int green = greenSlider.getValue(); - int blue = blueSlider.getValue() ; - Color color = new Color (red, green, blue); - - getColorSelectionModel().setSelectedColor(color); - } else if (e.getSource() instanceof JSpinner && !isAdjusting) { - - int red = ((Integer)redField.getValue()).intValue(); - int green = ((Integer)greenField.getValue()).intValue(); - int blue = ((Integer)blueField.getValue()).intValue(); - Color color = new Color (red, green, blue); - - getColorSelectionModel().setSelectedColor(color); - } - } - -} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java b/jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java new file mode 100644 index 00000000000..04905589e99 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java @@ -0,0 +1,160 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.image.BufferedImage; +import javax.swing.JComponent; + +final class DiagramComponent extends JComponent implements MouseListener, MouseMotionListener { + + private final ColorPanel panel; + private final boolean diagram; + + private final Insets insets = new Insets(0, 0, 0, 0); + + private int width; + private int height; + + private int[] array; + private BufferedImage image; + + DiagramComponent(ColorPanel panel, boolean diagram) { + this.panel = panel; + this.diagram = diagram; + addMouseListener(this); + addMouseMotionListener(this); + } + + @Override + protected void paintComponent(Graphics g) { + getInsets(this.insets); + this.width = getWidth() - this.insets.left - this.insets.right; + this.height = getHeight() - this.insets.top - this.insets.bottom; + + boolean update = (this.image == null) + || (this.width != this.image.getWidth()) + || (this.height != this.image.getHeight()); + if (update) { + int size = this.width * this.height; + if ((this.array == null) || (this.array.length < size)) { + this.array = new int[size]; + } + this.image = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB); + } + { + float dx = 1.0f / (float) (this.width - 1); + float dy = 1.0f / (float) (this.height - 1); + + int offset = 0; + float y = 0.0f; + for (int h = 0; h < this.height; h++, y += dy) { + if (this.diagram) { + float x = 0.0f; + for (int w = 0; w < this.width; w++, x += dx, offset++) { + this.array[offset] = this.panel.getColor(x, y); + } + } + else { + int color = this.panel.getColor(y); + for (int w = 0; w < this.width; w++, offset++) { + this.array[offset] = color; + } + } + } + } + this.image.setRGB(0, 0, this.width, this.height, this.array, 0, this.width); + g.drawImage(this.image, this.insets.left, this.insets.top, this.width, this.height, this); + if (isEnabled()) { + this.width--; + this.height--; + g.setXORMode(Color.WHITE); + g.setColor(Color.BLACK); + if (this.diagram) { + int x = getValue(this.panel.getValueX(), this.insets.left, this.width); + int y = getValue(this.panel.getValueY(), this.insets.top, this.height); + g.drawLine(x - 8, y, x + 8, y); + g.drawLine(x, y - 8, x, y + 8); + } + else { + int z = getValue(this.panel.getValueZ(), this.insets.top, this.height); + g.drawLine(this.insets.left, z, this.insets.left + this.width, z); + } + g.setPaintMode(); + } + } + + public void mousePressed(MouseEvent event) { + mouseDragged(event); + } + + public void mouseReleased(MouseEvent event) { + } + + public void mouseClicked(MouseEvent event) { + } + + public void mouseEntered(MouseEvent event) { + } + + public void mouseExited(MouseEvent event) { + } + + public void mouseMoved(MouseEvent event) { + } + + public void mouseDragged(MouseEvent event) { + if (isEnabled()) { + float y = getValue(event.getY(), this.insets.top, this.height); + if (this.diagram) { + float x = getValue(event.getX(), this.insets.left, this.width); + this.panel.setValue(x, y); + } + else { + this.panel.setValue(y); + } + } + } + + private static int getValue(float value, int min, int max) { + return min + (int) (value * (float) (max)); + } + + private static float getValue(int value, int min, int max) { + if (min < value) { + value -= min; + return (value < max) + ? (float) value / (float) max + : 1.0f; + } + return 0.0f; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java b/jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java new file mode 100644 index 00000000000..99e9bf29858 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java @@ -0,0 +1,118 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import javax.swing.JComponent; +import javax.swing.JSlider; +import javax.swing.JSpinner; +import javax.swing.JSpinner.DefaultEditor; +import javax.swing.SpinnerNumberModel; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +final class SlidingSpinner implements ChangeListener { + + private final ColorPanel panel; + private final JComponent label; + private final SpinnerNumberModel model = new SpinnerNumberModel(); + private final JSlider slider = new JSlider(); + private final JSpinner spinner = new JSpinner(this.model); + private float value; + private boolean internal; + + SlidingSpinner(ColorPanel panel, JComponent label) { + this.panel = panel; + this.label = label; + this.slider.addChangeListener(this); + this.spinner.addChangeListener(this); + DefaultEditor editor = (DefaultEditor) this.spinner.getEditor(); + ValueFormatter.init(3, false, editor.getTextField()); + editor.setFocusable(false); + this.spinner.setFocusable(false); + } + + JComponent getLabel() { + return this.label; + } + + JSlider getSlider() { + return this.slider; + } + + JSpinner getSpinner() { + return this.spinner; + } + + float getValue() { + return this.value; + } + + void setValue(float value) { + int min = this.slider.getMinimum(); + int max = this.slider.getMaximum(); + this.internal = true; + this.slider.setValue(min + (int) (value * (float) (max - min))); + this.spinner.setValue(Integer.valueOf(this.slider.getValue())); + this.internal = false; + this.value = value; + } + + void setRange(int min, int max) { + this.internal = true; + this.slider.setMinimum(min); + this.slider.setMaximum(max); + this.model.setMinimum(Integer.valueOf(min)); + this.model.setMaximum(Integer.valueOf(max)); + this.internal = false; + } + + void setVisible(boolean visible) { + this.label.setVisible(visible); + this.slider.setVisible(visible); + this.spinner.setVisible(visible); + } + + public void stateChanged(ChangeEvent event) { + if (!this.internal) { + if (this.spinner == event.getSource()) { + Object value = this.spinner.getValue(); + if (value instanceof Integer) { + this.internal = true; + this.slider.setValue((Integer) value); + this.internal = false; + } + } + int value = this.slider.getValue(); + this.internal = true; + this.spinner.setValue(Integer.valueOf(value)); + this.internal = false; + int min = this.slider.getMinimum(); + int max = this.slider.getMaximum(); + this.value = (float) (value - min) / (float) (max - min); + this.panel.colorChanged(); + } + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java b/jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java deleted file mode 100644 index cec69e9c39d..00000000000 --- a/jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package javax.swing.colorchooser; - -import java.awt.*; -import java.awt.image.*; - -/** A helper class to make computing synthetic images a little easier. - * All you need to do is define a subclass that overrides computeRow - * to compute a row of the image. It is passed the y coordinate of the - * row and an array into which to put the pixels in - * - * standard ARGB format. - *

Normal usage looks something like this: - *

 Image i = createImage(new SyntheticImage(200, 100) {
- *       protected void computeRow(int y, int[] row) {
- *         for(int i = width; --i>=0; ) {
- *             int grey = i*255/(width-1);
- *             row[i] = (255<<24)|(grey<<16)|(grey<<8)|grey;
- *         }
- *       }
- *   }
- *  
This creates a image 200 pixels wide and 100 pixels high - * that is a horizontal grey ramp, going from black on the left to - * white on the right. - *

- * If the image is to be a movie, override isStatic to return false, - * y cycling back to 0 is computeRow's signal that the next - * frame has started. It is acceptable (expected?) for computeRow(0,r) - * to pause until the appropriate time to start the next frame. - * - * @author James Gosling - */ -abstract class SyntheticImage implements ImageProducer { - private SyntheticImageGenerator root; - protected int width=10, height=100; - static final ColorModel cm = ColorModel.getRGBdefault(); - public static final int pixMask = 0xFF; - private Thread runner; - protected SyntheticImage() { } - protected SyntheticImage(int w, int h) { width = w; height = h; } - protected void computeRow(int y, int[] row) { - int p = 255-255*y/(height-1); - p = (pixMask<<24)|(p<<16)|(p<<8)|p; - for (int i = row.length; --i>=0; ) row[i] = p; - } - public synchronized void addConsumer(ImageConsumer ic){ - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) - if (ics.ic == ic) return; - root = new SyntheticImageGenerator(ic, root, this); - } - public synchronized boolean isConsumer(ImageConsumer ic){ - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) - if (ics.ic == ic) return true; - return false; - } - public synchronized void removeConsumer(ImageConsumer ic) { - SyntheticImageGenerator prev = null; - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) { - if (ics.ic == ic) { - ics.useful = false; - if (prev!=null) prev.next = ics.next; - else root = ics.next; - return; - } - prev = ics; - } - } - public synchronized void startProduction(ImageConsumer ic) { - addConsumer(ic); - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) - if (ics.useful && !ics.isAlive()) - ics.start(); - } - protected boolean isStatic() { return true; } - public void nextFrame(int param) {}//Override if !isStatic - public void requestTopDownLeftRightResend(ImageConsumer ic){} - - protected volatile boolean aborted = false; -} - -class SyntheticImageGenerator extends Thread { - ImageConsumer ic; - boolean useful; - SyntheticImageGenerator next; - SyntheticImage parent; - SyntheticImageGenerator(ImageConsumer ic, SyntheticImageGenerator next, - SyntheticImage parent) { - super("SyntheticImageGenerator"); - this.ic = ic; - this.next = next; - this.parent = parent; - useful = true; - setDaemon(true); - } - public void run() { - ImageConsumer ic = this.ic; - int w = parent.width; - int h = parent.height; - int hints = ic.SINGLEPASS|ic.COMPLETESCANLINES|ic.TOPDOWNLEFTRIGHT; - if (parent.isStatic()) - hints |= ic.SINGLEFRAME; - ic.setHints(hints); - ic.setDimensions(w, h); - ic.setProperties(null); - ic.setColorModel(parent.cm); - - if (useful) { - int[] row=new int[w]; - doPrivileged( new Runnable() { - public void run() { - Thread.currentThread().setPriority(Thread.MIN_PRIORITY); - } - }); - - do { - for (int y = 0; y>= 4; + } + return new String(array).toUpperCase(ENGLISH); + } + throw new ParseException("illegal object", 0); + } + + @Override + protected DocumentFilter getDocumentFilter() { + return this.filter; + } + + public void focusGained(FocusEvent event) { + Object source = event.getSource(); + if (source instanceof JFormattedTextField) { + this.text = (JFormattedTextField) source; + SwingUtilities.invokeLater(this); + } + } + + public void focusLost(FocusEvent event) { + } + + public void run() { + if (this.text != null) { + this.text.selectAll(); + } + } + + private boolean isValid(int length) { + return (0 <= length) && (length <= this.length); + } + + private boolean isValid(String text) { + int length = text.length(); + for (int i = 0; i < length; i++) { + char ch = text.charAt(i); + if (Character.digit(ch, this.radix) < 0) { + return false; + } + } + return true; + } +} diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java index fd63e7fcbb6..09f9372b9c3 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java @@ -299,8 +299,10 @@ public class BasicColorChooserUI extends ColorChooserUI tabbedPane.addTab(name, centerWrapper); if (mnemonic > 0) { tabbedPane.setMnemonicAt(i, mnemonic); - tabbedPane.setDisplayedMnemonicIndexAt( - i, newPanels[i].getDisplayedMnemonicIndex()); + int index = newPanels[i].getDisplayedMnemonicIndex(); + if (index >= 0) { + tabbedPane.setDisplayedMnemonicIndexAt(i, index); + } } } } diff --git a/jdk/test/javax/swing/JColorChooser/Test6524757.java b/jdk/test/javax/swing/JColorChooser/Test6524757.java index 0389efc70ad..dc7fa06ce59 100644 --- a/jdk/test/javax/swing/JColorChooser/Test6524757.java +++ b/jdk/test/javax/swing/JColorChooser/Test6524757.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,14 +34,13 @@ import java.awt.Dimension; import java.util.ArrayList; import java.util.List; import java.util.Locale; -import javax.swing.JButton; +import javax.swing.AbstractButton; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; -import javax.swing.JRadioButton; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.colorchooser.AbstractColorChooserPanel; @@ -59,31 +58,41 @@ public class Test6524757 { "ColorChooser.swatchesNameText", // NON-NLS: string key from DefaultSwatchChooserPanel "ColorChooser.swatchesMnemonic", // NON-NLS: string key from DefaultSwatchChooserPanel:int - "ColorChooser.swatchesDisplayedMnemonicIndex", // NON-NLS: int key from DefaultSwatchChooserPanel "ColorChooser.swatchesSwatchSize", // NON-NLS: dimension key from DefaultSwatchChooserPanel "ColorChooser.swatchesRecentText", // NON-NLS: string key from DefaultSwatchChooserPanel "ColorChooser.swatchesRecentSwatchSize", // NON-NLS: dimension key from DefaultSwatchChooserPanel //NotAvail: "ColorChooser.swatchesDefaultRecentColor", // NON-NLS: color key from DefaultSwatchChooserPanel - "ColorChooser.hsbNameText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbMnemonic", // NON-NLS: int key from DefaultHSBChooserPanel - "ColorChooser.hsbDisplayedMnemonicIndex", // NON-NLS: int key from DefaultHSBChooserPanel - "ColorChooser.hsbHueText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbSaturationText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbBrightnessText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbRedText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbGreenText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbBlueText", // NON-NLS: string key from DefaultHSBChooserPanel + "ColorChooser.hsvNameText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hsvMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + "ColorChooser.hsvHueText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hsvSaturationText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hsvValueText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hsvTransparencyText", // NON-NLS: string key from HSV ColorChooserPanel - "ColorChooser.rgbNameText", // NON-NLS: string key from DefaultRGBChooserPanel - "ColorChooser.rgbMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel - "ColorChooser.rgbDisplayedMnemonicIndex", // NON-NLS: int key from DefaultRGBChooserPanel - "ColorChooser.rgbRedText", // NON-NLS: string key from DefaultRGBChooserPanel - "ColorChooser.rgbGreenText", // NON-NLS: string key from DefaultRGBChooserPanel - "ColorChooser.rgbBlueText", // NON-NLS: string key from DefaultRGBChooserPanel - "ColorChooser.rgbRedMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel - "ColorChooser.rgbGreenMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel - "ColorChooser.rgbBlueMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel + "ColorChooser.hslNameText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hslMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + "ColorChooser.hslHueText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hslSaturationText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hslLightnessText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hslTransparencyText", // NON-NLS: string key from HSV ColorChooserPanel + + "ColorChooser.rgbNameText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + "ColorChooser.rgbRedText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbGreenText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbBlueText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbAlphaText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbHexCodeText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbHexCodeMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + + "ColorChooser.cmykNameText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + "ColorChooser.cmykCyanText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykMagentaText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykYellowText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykBlackText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykAlphaText", // NON-NLS: string key from HSV ColorChooserPanel }; private static final Object[] KOREAN = convert(Locale.KOREAN, KEYS); private static final Object[] FRENCH = convert(Locale.FRENCH, KEYS); @@ -91,19 +100,15 @@ public class Test6524757 { public static void main(String[] args) { // it affects Swing because it is not initialized Locale.setDefault(Locale.KOREAN); - Object[] korean = create(); + validate(KOREAN, create()); // it does not affect Swing because it is initialized Locale.setDefault(Locale.CANADA); - Object[] canada = create(); + validate(KOREAN, create()); // it definitely should affect Swing JComponent.setDefaultLocale(Locale.FRENCH); - Object[] french = create(); - - validate(KOREAN, korean); - validate(KOREAN, canada); - validate(FRENCH, french); + validate(FRENCH, create()); } private static void validate(Object[] expected, Object[] actual) { @@ -153,10 +158,47 @@ public class Test6524757 { // process all values List list = new ArrayList(KEYS.length); - addMain(list, dialog); - addSwatch(list, chooser); - addHSB(list, chooser); - addRGB(list, chooser); + + Component component = getC(getC(dialog.getLayeredPane(), 0), 1); + AbstractButton ok = (AbstractButton) getC(component, 0); + AbstractButton cancel = (AbstractButton) getC(component, 1); + AbstractButton reset = (AbstractButton) getC(component, 2); + list.add(ok.getText()); + list.add(cancel.getText()); + list.add(reset.getText()); + list.add(Integer.valueOf(reset.getMnemonic())); + + for (int i = 0; i < 5; i++) { + AbstractColorChooserPanel panel = (AbstractColorChooserPanel) getC(getC(getC(chooser, 0), i), 0); + list.add(panel.getDisplayName()); + list.add(Integer.valueOf(panel.getMnemonic())); + if (i == 0) { + JLabel label = (JLabel) getC(getC(panel, 0), 1); + JPanel upper = (JPanel) getC(getC(getC(panel, 0), 0), 0); + JPanel lower = (JPanel) getC(getC(getC(panel, 0), 2), 0); + addSize(list, upper, 1, 1, 31, 9); + list.add(label.getText()); + addSize(list, lower, 1, 1, 5, 7); + } + else { + Component container = getC(panel, 0); + for (int j = 0; j < 3; j++) { + AbstractButton button = (AbstractButton) getC(container, j); + list.add(button.getText()); + } + JLabel label = (JLabel) getC(container, 3); + list.add(label.getText()); + if (i == 4) { + label = (JLabel) getC(container, 4); + list.add(label.getText()); + } + if (i == 3) { + label = (JLabel) getC(panel, 1); + list.add(label.getText()); + list.add(Integer.valueOf(label.getDisplayedMnemonic())); + } + } + } // close dialog dialog.setVisible(false); @@ -169,56 +211,6 @@ public class Test6524757 { return list.toArray(); } - private static void addMain(List list, JDialog dialog) { - Component component = getC(getC(dialog.getLayeredPane(), 0), 1); - JButton ok = (JButton) getC(component, 0); - JButton cancel = (JButton) getC(component, 1); - JButton reset = (JButton) getC(component, 2); - list.add(ok.getText()); - list.add(cancel.getText()); - list.add(reset.getText()); - list.add(Integer.valueOf(reset.getMnemonic())); - } - - private static void addSwatch(List list, JColorChooser chooser) { - Component component = addPanel(list, chooser, 0); - JLabel label = (JLabel) getC(getC(component, 0), 1); - JPanel upper = (JPanel) getC(getC(getC(component, 0), 0), 0); - JPanel lower = (JPanel) getC(getC(getC(component, 0), 2), 0); - addSize(list, upper, 1, 1, 31, 9); - list.add(label.getText()); - addSize(list, lower, 1, 1, 5, 7); - } - - private static void addHSB(List list, JColorChooser chooser) { - Component component = addPanel(list, chooser, 1); - JRadioButton h = (JRadioButton) getC(getC(getC(component, 1), 0), 0); - JRadioButton s = (JRadioButton) getC(getC(getC(component, 1), 0), 2); - JRadioButton b = (JRadioButton) getC(getC(getC(component, 1), 0), 4); - list.add(h.getText()); - list.add(s.getText()); - list.add(b.getText()); - JLabel red = (JLabel) getC(getC(getC(component, 1), 2), 0); - JLabel green = (JLabel) getC(getC(getC(component, 1), 2), 2); - JLabel blue = (JLabel) getC(getC(getC(component, 1), 2), 4); - list.add(red.getText()); - list.add(green.getText()); - list.add(blue.getText()); - } - - private static void addRGB(List list, JColorChooser chooser) { - Component component = addPanel(list, chooser, 2); - JLabel red = (JLabel) getC(getC(component, 0), 0); - JLabel green = (JLabel) getC(getC(component, 0), 3); - JLabel blue = (JLabel) getC(getC(component, 0), 6); - list.add(red.getText()); - list.add(green.getText()); - list.add(blue.getText()); - list.add(Integer.valueOf(red.getDisplayedMnemonic())); - list.add(Integer.valueOf(green.getDisplayedMnemonic())); - list.add(Integer.valueOf(blue.getDisplayedMnemonic())); - } - private static void addSize(List list, Component component, int x, int y, int w, int h) { Dimension size = component.getPreferredSize(); int width = (size.width + 1) / w - x; @@ -226,14 +218,6 @@ public class Test6524757 { list.add(new Dimension(width, height)); } - private static Component addPanel(List list, JColorChooser chooser, int index) { - AbstractColorChooserPanel panel = (AbstractColorChooserPanel) getC(getC(getC(chooser, 0), index), 0); - list.add(panel.getDisplayName()); - list.add(Integer.valueOf(panel.getMnemonic())); - list.add(Integer.valueOf(panel.getDisplayedMnemonicIndex())); - return panel; - } - private static Component getC(Component component, int index) { Container container = (Container) component; return container.getComponent(index); diff --git a/jdk/test/javax/swing/JColorChooser/Test6559154.java b/jdk/test/javax/swing/JColorChooser/Test6559154.java new file mode 100644 index 00000000000..e84d90539d4 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test6559154.java @@ -0,0 +1,75 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6559154 + * @summary Tests EDT hanging + * @author Sergey Malenkov + */ + +import java.awt.Component; +import java.awt.Container; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.SwingUtilities; +import javax.swing.Timer; + +public class Test6559154 implements ActionListener, Runnable { + + private JDialog dialog; + + public void actionPerformed(ActionEvent event) { + if (this.dialog != null) { + this.dialog.dispose(); + } + } + + public void run() { + Timer timer = new Timer(1000, this); + timer.setRepeats(false); + timer.start(); + + JColorChooser chooser = new JColorChooser(); + setEnabledRecursive(chooser, false); + + this.dialog = new JDialog(); + this.dialog.add(chooser); + this.dialog.setVisible(true); + } + + private static void setEnabledRecursive(Container container, boolean enabled) { + for (Component component : container.getComponents()) { + component.setEnabled(enabled); + if (component instanceof Container) { + setEnabledRecursive((Container) component, enabled); + } + } + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Test6559154()); + } +} From 7f530b42c8dc1ad26f21e4b1a7cff18fd8f21158 Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Mon, 21 Jul 2008 10:21:42 -0400 Subject: [PATCH 12/45] 6668281: NullPointerException in DefaultTableCellHeaderRenderer.getColumnSortOrder() Reviewed-by: alexp --- .../com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java index e2217e0f35a..0f2b39d8937 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java @@ -124,7 +124,7 @@ public class WindowsTableHeaderUI extends BasicTableHeaderUI { setIcon(null); sortIcon = null; SortOrder sortOrder = - getColumnSortOrder(header.getTable(), column); + getColumnSortOrder(table, column); if (sortOrder != null) { switch (sortOrder) { case ASCENDING: From a44852b8fe9e4cfe0ce204d61870c382998e18d8 Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Mon, 21 Jul 2008 19:58:43 +0400 Subject: [PATCH 13/45] 6607130: REGRESSION: JComboBox cell editor isn't hidden if the same value is selected with keyboard JComboBox cell editor now hides if the same value is selected with keyboard Reviewed-by: peterz, alexp --- .../swing/plaf/basic/BasicComboBoxUI.java | 12 +- .../swing/JComboBox/6607130/bug6607130.java | 149 ++++++++++++++++++ 2 files changed, 158 insertions(+), 3 deletions(-) create mode 100644 jdk/test/javax/swing/JComboBox/6607130/bug6607130.java diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java index f073eeda816..c49387fd91f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java @@ -1509,15 +1509,21 @@ public class BasicComboBoxUI extends ComboBoxUI { || ui.isTableCellEditor) { Object listItem = ui.popup.getList().getSelectedValue(); if (listItem != null) { - comboBox.getModel().setSelectedItem(listItem); - // Ensure that JComboBox.actionPerformed() - // doesn't set editor value as selected item + // Use the selected value from popup + // to set the selected item in combo box, + // but ensure before that JComboBox.actionPerformed() + // won't use editor's value to set the selected item comboBox.getEditor().setItem(listItem); + comboBox.setSelectedItem(listItem); } } comboBox.setPopupVisible(false); } else { + // Hide combo box if it is a table cell editor + if (ui.isTableCellEditor && !comboBox.isEditable()) { + comboBox.setSelectedItem(comboBox.getSelectedItem()); + } // Call the default button binding. // This is a pretty messy way of passing an event through // to the root pane. diff --git a/jdk/test/javax/swing/JComboBox/6607130/bug6607130.java b/jdk/test/javax/swing/JComboBox/6607130/bug6607130.java new file mode 100644 index 00000000000..5d465c9d79d --- /dev/null +++ b/jdk/test/javax/swing/JComboBox/6607130/bug6607130.java @@ -0,0 +1,149 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6607130 + * @summary Checks that JComboBox cell editor is hidden if the same + * item is selected with keyboard. + * Also checks that JComboBox cell editor is hidden if F2 and then + * ENTER were pressed. + * @author Mikhail Lapshin + */ + +import sun.awt.SunToolkit; + +import javax.swing.*; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.awt.event.KeyEvent; + +public class bug6607130 { + private JFrame frame; + private JComboBox cb; + private Robot robot; + + public static void main(String[] args) throws Exception { + final bug6607130 test = new bug6607130(); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + test.setupUI(); + } + }); + test.test(); + } finally { + if (test.frame != null) { + test.frame.dispose(); + } + } + } + + public bug6607130() throws AWTException { + robot = new Robot(); + } + + private void setupUI() { + frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + DefaultTableModel model = new DefaultTableModel(1, 1); + JTable table = new JTable(model); + + cb = new JComboBox(new String[]{"one", "two", "three"}); + table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(cb)); + frame.add(table); + + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private void test() throws Exception { + realSync(); + test1(); + realSync(); + checkResult("First test"); + test2(); + realSync(); + checkResult("Second test"); + } + + private void test1() throws Exception { + // Select 'one' + hitKey(KeyEvent.VK_TAB); + realSync(); + hitKey(KeyEvent.VK_F2); + realSync(); + hitKey(KeyEvent.VK_DOWN); + realSync(); + hitKey(KeyEvent.VK_DOWN); + realSync(); + hitKey(KeyEvent.VK_ENTER); + realSync(); + + // Select 'one' again + hitKey(KeyEvent.VK_F2); + realSync(); + hitKey(KeyEvent.VK_DOWN); + realSync(); + hitKey(KeyEvent.VK_ENTER); + realSync(); + } + + private void test2() throws Exception { + // Press F2 and then press ENTER + // Editor should be shown and then closed + hitKey(KeyEvent.VK_F2); + realSync(); + hitKey(KeyEvent.VK_ENTER); + realSync(); + } + + private void checkResult(String testName) { + if (!cb.isShowing()) { + System.out.println(testName + " passed"); + } else { + System.out.println(testName + " failed"); + throw new RuntimeException("JComboBox is showing " + + "after item selection."); + } + } + + private static void realSync() { + ((SunToolkit) (Toolkit.getDefaultToolkit())).realSync(); + } + + public void hitKey(int keycode) { + robot.keyPress(keycode); + robot.keyRelease(keycode); + delay(); + } + + private void delay() { + try { + Thread.sleep(1000); + } catch(InterruptedException ie) { + ie.printStackTrace(); + } + } +} From c3732ffc5d459769b969da2ae7c5b90d36d3d523 Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Thu, 24 Jul 2008 14:34:02 +0400 Subject: [PATCH 14/45] 6725409: Unable to localize JInternalFrame system menu during run-time Use of the static final constants replaced by direct calls of UIManager.getString(). Reviewed-by: alexp --- .../basic/BasicInternalFrameTitlePane.java | 19 +- .../JInternalFrame/6725409/bug6725409.java | 162 ++++++++++++++++++ 2 files changed, 175 insertions(+), 6 deletions(-) create mode 100644 jdk/test/javax/swing/JInternalFrame/6725409/bug6725409.java diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java index 344a4b2b512..d8f25731266 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java @@ -86,6 +86,7 @@ public class BasicInternalFrameTitlePane extends JComponent protected Action moveAction; protected Action sizeAction; + // These constants are not used in JDK code protected static final String CLOSE_CMD = UIManager.getString("InternalFrameTitlePane.closeButtonText"); protected static final String ICONIFY_CMD = @@ -600,7 +601,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class CloseAction extends AbstractAction { public CloseAction() { - super(CLOSE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.closeButtonText")); } public void actionPerformed(ActionEvent e) { @@ -616,7 +618,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class MaximizeAction extends AbstractAction { public MaximizeAction() { - super(MAXIMIZE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.maximizeButtonText")); } public void actionPerformed(ActionEvent evt) { @@ -644,7 +647,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class IconifyAction extends AbstractAction { public IconifyAction() { - super(ICONIFY_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.minimizeButtonText")); } public void actionPerformed(ActionEvent e) { @@ -664,7 +668,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class RestoreAction extends AbstractAction { public RestoreAction() { - super(RESTORE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.restoreButtonText")); } public void actionPerformed(ActionEvent evt) { @@ -690,7 +695,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class MoveAction extends AbstractAction { public MoveAction() { - super(MOVE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.moveButtonText")); } public void actionPerformed(ActionEvent e) { @@ -723,7 +729,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class SizeAction extends AbstractAction { public SizeAction() { - super(SIZE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.sizeButtonText")); } public void actionPerformed(ActionEvent e) { diff --git a/jdk/test/javax/swing/JInternalFrame/6725409/bug6725409.java b/jdk/test/javax/swing/JInternalFrame/6725409/bug6725409.java new file mode 100644 index 00000000000..b118fed88be --- /dev/null +++ b/jdk/test/javax/swing/JInternalFrame/6725409/bug6725409.java @@ -0,0 +1,162 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6725409 + * @summary Checks that JInternalFrame's system menu + * can be localized during run-time + * @author Mikhail Lapshin + */ + +import javax.swing.*; +import java.awt.*; + +public class bug6725409 { + private JFrame frame; + private JInternalFrame iFrame; + private TestTitlePane testTitlePane; + private boolean passed; + + public static void main(String[] args) throws Exception { + try { + UIManager.setLookAndFeel( + new com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel()); + } catch(UnsupportedLookAndFeelException e) { + System.out.println("The test is for Windows LaF only"); + System.exit(0); + } + + final bug6725409 bug6725409 = new bug6725409(); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + bug6725409.setupUIStep1(); + } + }); + realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + bug6725409.setupUIStep2(); + } + }); + realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + bug6725409.test(); + } + }); + realSync(); + bug6725409.checkResult(); + } finally { + if (bug6725409.frame != null) { + bug6725409.frame.dispose(); + } + } + } + + private void setupUIStep1() { + frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JDesktopPane desktop = new JDesktopPane(); + iFrame = new JInternalFrame("Internal Frame", true, true, true, true); + iFrame.setSize(200, 100); + desktop.add(iFrame); + frame.add(desktop); + iFrame.setVisible(true); + + frame.setSize(500, 300); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private void setupUIStep2() { + UIManager.put("InternalFrameTitlePane.restoreButtonText", + "CUSTOM.restoreButtonText"); + UIManager.put("InternalFrameTitlePane.moveButtonText", + "CUSTOM.moveButtonText"); + UIManager.put("InternalFrameTitlePane.sizeButtonText", + "CUSTOM.sizeButtonText"); + UIManager.put("InternalFrameTitlePane.minimizeButtonText", + "CUSTOM.minimizeButtonText"); + UIManager.put("InternalFrameTitlePane.maximizeButtonText", + "CUSTOM.maximizeButtonText"); + UIManager.put("InternalFrameTitlePane.closeButtonText", + "CUSTOM.closeButtonText"); + SwingUtilities.updateComponentTreeUI(frame); + } + + // The test depends on the order of the menu items in + // WindowsInternalFrameTitlePane.systemPopupMenu + private void test() { + testTitlePane = new TestTitlePane(iFrame); + passed = true; + checkMenuItemText(0, "CUSTOM.restoreButtonText"); + checkMenuItemText(1, "CUSTOM.moveButtonText"); + checkMenuItemText(2, "CUSTOM.sizeButtonText"); + checkMenuItemText(3, "CUSTOM.minimizeButtonText"); + checkMenuItemText(4, "CUSTOM.maximizeButtonText"); + // Skip separator + checkMenuItemText(6, "CUSTOM.closeButtonText"); + } + + private void checkMenuItemText(int index, String text) { + JMenuItem menuItem = (JMenuItem) + testTitlePane.getSystemPopupMenu().getComponent(index); + if (!text.equals(menuItem.getText())) { + passed = false; + } + } + + private void checkResult() { + if (passed) { + System.out.println("Test passed"); + } else { + throw new RuntimeException("Unable to localize " + + "JInternalFrame's system menu during run-time"); + } + } + + private static void realSync() { + ((sun.awt.SunToolkit) (Toolkit.getDefaultToolkit())).realSync(); + } + + // Extend WindowsInternalFrameTitlePane to get access to systemPopupMenu + private class TestTitlePane extends + com.sun.java.swing.plaf.windows.WindowsInternalFrameTitlePane { + private JPopupMenu systemPopupMenu; + + public TestTitlePane(JInternalFrame f) { + super(f); + } + + public JPopupMenu getSystemPopupMenu() { + return systemPopupMenu; + } + + protected void addSystemMenuItems(JPopupMenu menu) { + super.addSystemMenuItems(menu); + systemPopupMenu = menu; + } + } +} From 02a6cd79141120a36b79ee2e64c72b11f8269ab8 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 24 Jul 2008 14:51:13 +0400 Subject: [PATCH 15/45] 4778988: CompoundBorder.isBorderOpaque() has incorrect documentation Reviewed-by: peterz, rupashka --- .../share/classes/javax/swing/border/CompoundBorder.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/border/CompoundBorder.java b/jdk/src/share/classes/javax/swing/border/CompoundBorder.java index f736cf90278..46ac44e50c0 100644 --- a/jdk/src/share/classes/javax/swing/border/CompoundBorder.java +++ b/jdk/src/share/classes/javax/swing/border/CompoundBorder.java @@ -79,10 +79,13 @@ public class CompoundBorder extends AbstractBorder { } /** - * Returns whether or not this compound border is opaque. - * Returns true if both the inside and outside borders are - * non-null and opaque; returns false otherwise. + * Returns whether or not the compound border is opaque. + * + * @return {@code true} if the inside and outside borders + * are each either {@code null} or opaque; + * or {@code false} otherwise */ + @Override public boolean isBorderOpaque() { return (outsideBorder == null || outsideBorder.isBorderOpaque()) && (insideBorder == null || insideBorder.isBorderOpaque()); From 8ad3454b18021915cf22eacd3a87ede111620cb6 Mon Sep 17 00:00:00 2001 From: Florian Brunner Date: Thu, 24 Jul 2008 16:43:36 +0400 Subject: [PATCH 16/45] 6722802: Code improvement and warnings removing from the javax.swing.text package Removed unnecessary castings and other warnings Reviewed-by: peterz --- .../javax/swing/text/AbstractDocument.java | 29 +++-- .../javax/swing/text/AsyncBoxView.java | 12 +-- .../javax/swing/text/ComponentView.java | 5 +- .../javax/swing/text/DefaultCaret.java | 5 +- .../javax/swing/text/DefaultFormatter.java | 4 +- .../javax/swing/text/DefaultHighlighter.java | 20 ++-- .../swing/text/DefaultStyledDocument.java | 97 ++++++++--------- .../javax/swing/text/ElementIterator.java | 20 ++-- .../classes/javax/swing/text/FlowView.java | 6 +- .../classes/javax/swing/text/GapContent.java | 14 +-- .../swing/text/InternationalFormatter.java | 9 +- .../javax/swing/text/JTextComponent.java | 73 ++++++------- .../classes/javax/swing/text/LayoutQueue.java | 6 +- .../javax/swing/text/MaskFormatter.java | 6 +- .../javax/swing/text/NumberFormatter.java | 18 +--- .../javax/swing/text/PlainDocument.java | 4 +- .../javax/swing/text/SegmentCache.java | 6 +- .../javax/swing/text/SimpleAttributeSet.java | 6 +- .../javax/swing/text/StringContent.java | 10 +- .../javax/swing/text/StyleContext.java | 38 +++---- .../classes/javax/swing/text/TableView.java | 11 +- .../classes/javax/swing/text/TextAction.java | 8 +- .../javax/swing/text/TextLayoutStrategy.java | 12 +-- .../classes/javax/swing/text/ZoneView.java | 10 +- .../javax/swing/text/html/AccessibleHTML.java | 42 ++++---- .../classes/javax/swing/text/html/CSS.java | 71 ++++++------ .../classes/javax/swing/text/html/HTML.java | 18 ++-- .../javax/swing/text/html/HTMLDocument.java | 69 ++++++------ .../javax/swing/text/html/HTMLEditorKit.java | 25 +++-- .../javax/swing/text/html/HTMLWriter.java | 33 +++--- .../classes/javax/swing/text/html/Map.java | 18 ++-- .../swing/text/html/MinimalHTMLWriter.java | 8 +- .../swing/text/html/OptionListModel.java | 9 +- .../javax/swing/text/html/StyleSheet.java | 102 +++++++++--------- .../javax/swing/text/html/TableView.java | 10 +- .../swing/text/html/parser/AttributeList.java | 2 +- .../javax/swing/text/html/parser/DTD.java | 28 +++-- .../javax/swing/text/html/parser/Element.java | 4 +- .../javax/swing/text/html/parser/Entity.java | 4 +- .../javax/swing/text/html/parser/Parser.java | 14 ++- .../swing/text/html/parser/TagStack.java | 16 --- .../swing/text/rtf/MockAttributeSet.java | 2 +- .../javax/swing/text/rtf/RTFAttributes.java | 13 ++- .../javax/swing/text/rtf/RTFGenerator.java | 42 ++++---- .../javax/swing/text/rtf/RTFParser.java | 2 +- .../javax/swing/text/rtf/RTFReader.java | 102 +++++++++--------- 46 files changed, 499 insertions(+), 564 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java index 406350a9b10..a5cbdc2396c 100644 --- a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java +++ b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java @@ -123,15 +123,15 @@ public abstract class AbstractDocument implements Document, Serializable { if (defaultI18NProperty == null) { // determine default setting for i18n support - Object o = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + String o = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public String run() { return System.getProperty(I18NProperty); } } ); if (o != null) { - defaultI18NProperty = Boolean.valueOf((String)o); + defaultI18NProperty = Boolean.valueOf(o); } else { defaultI18NProperty = Boolean.FALSE; } @@ -163,7 +163,7 @@ public abstract class AbstractDocument implements Document, Serializable { */ public Dictionary getDocumentProperties() { if (documentProperties == null) { - documentProperties = new Hashtable(2); + documentProperties = new Hashtable(2); } return documentProperties; } @@ -467,8 +467,7 @@ public abstract class AbstractDocument implements Document, Serializable { * @since 1.4 */ public DocumentListener[] getDocumentListeners() { - return (DocumentListener[])listenerList.getListeners( - DocumentListener.class); + return listenerList.getListeners(DocumentListener.class); } /** @@ -508,8 +507,7 @@ public abstract class AbstractDocument implements Document, Serializable { * @since 1.4 */ public UndoableEditListener[] getUndoableEditListeners() { - return (UndoableEditListener[])listenerList.getListeners( - UndoableEditListener.class); + return listenerList.getListeners(UndoableEditListener.class); } /** @@ -610,7 +608,7 @@ public abstract class AbstractDocument implements Document, Serializable { DefaultDocumentEvent chng = new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE); - boolean isComposedTextElement = false; + boolean isComposedTextElement; // Check whether the position of interest is the composed text isComposedTextElement = Utilities.isComposedTextElement(this, offs); @@ -1051,7 +1049,7 @@ public abstract class AbstractDocument implements Document, Serializable { byte levels[] = calculateBidiLevels( firstPStart, lastPEnd ); - Vector newElements = new Vector(); + Vector newElements = new Vector(); // Calculate the first span of characters in the affected range with // the same bidi level. If this level is the same as the level of the @@ -1831,7 +1829,6 @@ public abstract class AbstractDocument implements Document, Serializable { } out.println("["+contentStr+"]"); } catch (BadLocationException e) { - ; } } else { @@ -2460,7 +2457,7 @@ public abstract class AbstractDocument implements Document, Serializable { if(nchildren == 0) return null; - Vector tempVector = new Vector(nchildren); + Vector tempVector = new Vector(nchildren); for(int counter = 0; counter < nchildren; counter++) tempVector.addElement(children[counter]); @@ -2749,7 +2746,7 @@ public abstract class AbstractDocument implements Document, Serializable { // if the number of changes gets too great, start using // a hashtable for to locate the change for a given element. if ((changeLookup == null) && (edits.size() > 10)) { - changeLookup = new Hashtable(); + changeLookup = new Hashtable(); int n = edits.size(); for (int i = 0; i < n; i++) { Object o = edits.elementAt(i); @@ -2918,7 +2915,7 @@ public abstract class AbstractDocument implements Document, Serializable { */ public DocumentEvent.ElementChange getChange(Element elem) { if (changeLookup != null) { - return (DocumentEvent.ElementChange) changeLookup.get(elem); + return changeLookup.get(elem); } int n = edits.size(); for (int i = 0; i < n; i++) { @@ -2937,7 +2934,7 @@ public abstract class AbstractDocument implements Document, Serializable { private int offset; private int length; - private Hashtable changeLookup; + private Hashtable changeLookup; private DocumentEvent.EventType type; } diff --git a/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java b/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java index 54a0e973553..ae11bde8122 100644 --- a/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java +++ b/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java @@ -25,6 +25,7 @@ package javax.swing.text; import java.util.*; +import java.util.List; import java.awt.*; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; @@ -58,7 +59,7 @@ public class AsyncBoxView extends View { */ public AsyncBoxView(Element elem, int axis) { super(elem); - stats = new ArrayList(); + stats = new ArrayList(); this.axis = axis; locator = new ChildLocator(); flushTask = new FlushTask(); @@ -197,7 +198,7 @@ public class AsyncBoxView extends View { protected ChildState getChildState(int index) { synchronized(stats) { if ((index >= 0) && (index < stats.size())) { - return (ChildState) stats.get(index); + return stats.get(index); } return null; } @@ -357,7 +358,7 @@ public class AsyncBoxView extends View { synchronized(stats) { // remove the replaced state records for (int i = 0; i < length; i++) { - ChildState cs = (ChildState)stats.remove(offset); + ChildState cs = stats.remove(offset); float csSpan = cs.getMajorSpan(); cs.getChildView().setParent(null); @@ -863,7 +864,7 @@ public class AsyncBoxView extends View { /** * The children and their layout statistics. */ - java.util.List stats; + List stats; /** * Current span along the major axis. This @@ -1110,7 +1111,7 @@ public class AsyncBoxView extends View { */ int updateChildOffsets(float targetOffset) { int n = getViewCount(); - int targetIndex = n - 1;; + int targetIndex = n - 1; int pos = lastValidOffset.getChildView().getStartOffset(); int startIndex = getViewIndex(pos, Position.Bias.Forward); float start = lastValidOffset.getMajorOffset(); @@ -1394,7 +1395,6 @@ public class AsyncBoxView extends View { private float min; private float pref; private float max; - private float align; private boolean minorValid; // major axis diff --git a/jdk/src/share/classes/javax/swing/text/ComponentView.java b/jdk/src/share/classes/javax/swing/text/ComponentView.java index 62e4bd02acb..085d999675d 100644 --- a/jdk/src/share/classes/javax/swing/text/ComponentView.java +++ b/jdk/src/share/classes/javax/swing/text/ComponentView.java @@ -27,6 +27,7 @@ package javax.swing.text; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; +import java.util.Set; import javax.swing.SwingUtilities; import javax.swing.event.*; @@ -434,7 +435,7 @@ public class ComponentView extends View { /** * Shows or hides this component depending on the value of parameter * b. - * @param b If true, shows this component; + * @param b If true, shows this component; * otherwise, hides this component. * @see #isVisible * @since JDK1.1 @@ -480,7 +481,7 @@ public class ComponentView extends View { return yalign; } - public java.util.Set getFocusTraversalKeys(int id) { + public Set getFocusTraversalKeys(int id) { return KeyboardFocusManager.getCurrentKeyboardFocusManager(). getDefaultFocusTraversalKeys(id); } diff --git a/jdk/src/share/classes/javax/swing/text/DefaultCaret.java b/jdk/src/share/classes/javax/swing/text/DefaultCaret.java index 22ec280ba09..e0e15681188 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultCaret.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultCaret.java @@ -774,8 +774,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } /** @@ -1330,7 +1329,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou if (this.dot != this.mark && component != null) { Clipboard clip = getSystemSelection(); if (clip != null) { - String selectedText = null; + String selectedText; if (component instanceof JPasswordField && component.getClientProperty("JPasswordField.cutCopyAllowed") != Boolean.TRUE) { diff --git a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java index 79419047273..51dab601ca1 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java @@ -68,7 +68,7 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter private boolean commitOnEdit; /** Class used to create new instances. */ - private Class valueClass; + private Class valueClass; /** NavigationFilter that forwards calls back to DefaultFormatter. */ private NavigationFilter navigationFilter; @@ -231,7 +231,7 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter * @return Object representation of text */ public Object stringToValue(String string) throws ParseException { - Class vc = getValueClass(); + Class vc = getValueClass(); JFormattedTextField ftf = getFormattedTextField(); if (vc == null && ftf != null) { diff --git a/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java b/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java index 9e3202130d3..028b24c0ea6 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java @@ -56,7 +56,7 @@ public class DefaultHighlighter extends LayeredHighlighter { // PENDING(prinz) - should cull ranges not visible int len = highlights.size(); for (int i = 0; i < len; i++) { - HighlightInfo info = (HighlightInfo) highlights.elementAt(i); + HighlightInfo info = highlights.elementAt(i); if (!(info instanceof LayeredHighlightInfo)) { // Avoid allocing unless we need it. Rectangle a = component.getBounds(); @@ -66,7 +66,7 @@ public class DefaultHighlighter extends LayeredHighlighter { a.width -= insets.left + insets.right; a.height -= insets.top + insets.bottom; for (; i < len; i++) { - info = (HighlightInfo)highlights.elementAt(i); + info = highlights.elementAt(i); if (!(info instanceof LayeredHighlightInfo)) { Highlighter.HighlightPainter p = info.getPainter(); p.paint(g, info.getStartOffset(), info.getEndOffset(), @@ -159,7 +159,7 @@ public class DefaultHighlighter extends LayeredHighlighter { int p0 = -1; int p1 = -1; for (int i = 0; i < len; i++) { - HighlightInfo hi = (HighlightInfo)highlights.elementAt(i); + HighlightInfo hi = highlights.elementAt(i); if (hi instanceof LayeredHighlightInfo) { LayeredHighlightInfo info = (LayeredHighlightInfo)hi; minX = Math.min(minX, info.x); @@ -195,7 +195,7 @@ public class DefaultHighlighter extends LayeredHighlighter { int p0 = Integer.MAX_VALUE; int p1 = 0; for (int i = 0; i < len; i++) { - HighlightInfo info = (HighlightInfo) highlights.elementAt(i); + HighlightInfo info = highlights.elementAt(i); p0 = Math.min(p0, info.p0.getOffset()); p1 = Math.max(p1, info.p1.getOffset()); } @@ -282,7 +282,7 @@ public class DefaultHighlighter extends LayeredHighlighter { Shape viewBounds, JTextComponent editor, View view) { for (int counter = highlights.size() - 1; counter >= 0; counter--) { - Object tag = highlights.elementAt(counter); + HighlightInfo tag = highlights.elementAt(counter); if (tag instanceof LayeredHighlightInfo) { LayeredHighlightInfo lhi = (LayeredHighlightInfo)tag; int start = lhi.getStartOffset(); @@ -333,7 +333,7 @@ public class DefaultHighlighter extends LayeredHighlighter { private final static Highlighter.Highlight[] noHighlights = new Highlighter.Highlight[0]; - private Vector highlights = new Vector(); // Vector + private Vector highlights = new Vector(); private JTextComponent component; private boolean drawsLayeredHighlights; private SafeDamager safeDamager = new SafeDamager(); @@ -573,8 +573,8 @@ public class DefaultHighlighter extends LayeredHighlighter { * call. */ class SafeDamager implements Runnable { - private Vector p0 = new Vector(10); - private Vector p1 = new Vector(10); + private Vector p0 = new Vector(10); + private Vector p1 = new Vector(10); private Document lastDoc = null; /** @@ -589,8 +589,8 @@ public class DefaultHighlighter extends LayeredHighlighter { int len = p0.size(); for (int i = 0; i < len; i++){ mapper.damageRange(component, - ((Position)p0.get(i)).getOffset(), - ((Position)p1.get(i)).getOffset()); + p0.get(i).getOffset(), + p1.get(i).getOffset()); } } } diff --git a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java index 4939a7615c3..d3ba5d98df8 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java @@ -84,7 +84,7 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc */ public DefaultStyledDocument(Content c, StyleContext styles) { super(c, styles); - listeningStyles = new Vector(); + listeningStyles = new Vector is received. */ - private java.util.List _stateInfos; + private List _stateInfos; /** * Current style. @@ -151,7 +152,7 @@ class SynthParser extends HandlerBase { /** * Bindings for the current InputMap */ - private java.util.List _inputMapBindings; + private List _inputMapBindings; /** * ID for the input map. This is cached as @@ -177,30 +178,30 @@ class SynthParser extends HandlerBase { /** * List of ColorTypes. This is populated in startColorType. */ - private java.util.List _colorTypes; + private List _colorTypes; /** * defaultsPropertys are placed here. */ - private Map _defaultsMap; + private Map _defaultsMap; /** * List of SynthStyle.Painters that will be applied to the current style. */ - private java.util.List _stylePainters; + private List _stylePainters; /** * List of SynthStyle.Painters that will be applied to the current state. */ - private java.util.List _statePainters; + private List _statePainters; SynthParser() { _mapping = new HashMap(); - _stateInfos = new ArrayList(); - _colorTypes = new ArrayList(); - _inputMapBindings = new ArrayList(); - _stylePainters = new ArrayList(); - _statePainters = new ArrayList(); + _stateInfos = new ArrayList(); + _colorTypes = new ArrayList(); + _inputMapBindings = new ArrayList(); + _stylePainters = new ArrayList(); + _statePainters = new ArrayList(); } /** @@ -219,7 +220,7 @@ class SynthParser extends HandlerBase { public void parse(InputStream inputStream, DefaultSynthStyleFactory factory, URL urlResourceBase, Class classResourceBase, - Map defaultsMap) + Map defaultsMap) throws ParseException, IllegalArgumentException { if (inputStream == null || factory == null || (urlResourceBase == null && classResourceBase == null)) { @@ -333,7 +334,7 @@ class SynthParser extends HandlerBase { * type type, this will throw an exception. */ private Object lookup(String key, Class type) throws SAXException { - Object value = null; + Object value; if (_handler != null) { if ((value = _handler.lookup(key)) != null) { return checkCast(value, type); @@ -423,15 +424,12 @@ class SynthParser extends HandlerBase { private void endStyle() throws SAXException { int size = _stylePainters.size(); if (size > 0) { - _style.setPainters((ParsedSynthStyle.PainterInfo[]) - _stylePainters.toArray(new ParsedSynthStyle. - PainterInfo[size])); + _style.setPainters(_stylePainters.toArray(new ParsedSynthStyle.PainterInfo[size])); _stylePainters.clear(); } size = _stateInfos.size(); if (size > 0) { - _style.setStateInfo((ParsedSynthStyle.StateInfo[])_stateInfos. - toArray(new ParsedSynthStyle.StateInfo[size])); + _style.setStateInfo(_stateInfos.toArray(new ParsedSynthStyle.StateInfo[size])); _stateInfos.clear(); } _style = null; @@ -501,9 +499,7 @@ class SynthParser extends HandlerBase { private void endState() throws SAXException { int size = _statePainters.size(); if (size > 0) { - _stateInfo.setPainters((ParsedSynthStyle.PainterInfo[]) - _statePainters.toArray(new ParsedSynthStyle. - PainterInfo[size])); + _stateInfo.setPainters(_statePainters.toArray(new ParsedSynthStyle.PainterInfo[size])); _statePainters.clear(); } _stateInfo = null; @@ -684,8 +680,7 @@ class SynthParser extends HandlerBase { int max = 0; for (int counter = _colorTypes.size() - 1; counter >= 0; counter--) { - max = Math.max(max, ((ColorType)_colorTypes.get(counter)). - getID()); + max = Math.max(max, _colorTypes.get(counter).getID()); } if (colors == null || colors.length <= max) { Color[] newColors = new Color[max + 1]; @@ -696,7 +691,7 @@ class SynthParser extends HandlerBase { } for (int counter = _colorTypes.size() - 1; counter >= 0; counter--) { - colors[((ColorType)_colorTypes.get(counter)).getID()] = color; + colors[_colorTypes.get(counter).getID()] = color; } _stateInfo.setColors(colors); } @@ -705,7 +700,7 @@ class SynthParser extends HandlerBase { private void startProperty(AttributeList attributes, Object property) throws SAXException { Object value = null; - Object key = null; + String key = null; // Type of the value: 0=idref, 1=boolean, 2=dimension, 3=insets, // 4=integer,5=string int iType = 0; @@ -1027,7 +1022,7 @@ class SynthParser extends HandlerBase { } } - private void addPainterOrMerge(java.util.List painters, String method, + private void addPainterOrMerge(List painters, String method, SynthPainter painter, int direction) { ParsedSynthStyle.PainterInfo painterInfo; painterInfo = new ParsedSynthStyle.PainterInfo(method, diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java index ddbc7ae7e69..21466d96093 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java @@ -48,13 +48,13 @@ class SynthSplitPaneUI extends BasicSplitPaneUI implements * Keys to use for forward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusForwardTraversalKeys; + private static Set managingFocusForwardTraversalKeys; /** * Keys to use for backward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusBackwardTraversalKeys; + private static Set managingFocusBackwardTraversalKeys; /** * Style for the JSplitPane. @@ -96,7 +96,7 @@ class SynthSplitPaneUI extends BasicSplitPaneUI implements // focus forward traversal key if (managingFocusForwardTraversalKeys==null) { - managingFocusForwardTraversalKeys = new HashSet(); + managingFocusForwardTraversalKeys = new HashSet(); managingFocusForwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); } @@ -104,7 +104,7 @@ class SynthSplitPaneUI extends BasicSplitPaneUI implements managingFocusForwardTraversalKeys); // focus backward traversal key if (managingFocusBackwardTraversalKeys==null) { - managingFocusBackwardTraversalKeys = new HashSet(); + managingFocusBackwardTraversalKeys = new HashSet(); managingFocusBackwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java index c9475f91b54..ab9e42b41e5 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java @@ -53,7 +53,7 @@ public abstract class SynthStyle { /** * Contains the default values for certain properties. */ - private static Map DEFAULT_VALUES; + private static Map DEFAULT_VALUES; /** * Shared SynthGraphics. @@ -715,7 +715,7 @@ public abstract class SynthStyle { private static Object getDefaultValue(Object key) { synchronized(SynthStyle.class) { if (DEFAULT_VALUES == null) { - DEFAULT_VALUES = new HashMap(); + DEFAULT_VALUES = new HashMap(); populateDefaultValues(); } Object value = DEFAULT_VALUES.get(key); diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java index f52d3a68b0d..d07c4d5ad88 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java @@ -66,7 +66,7 @@ class SynthTextAreaUI extends BasicTextAreaUI implements SynthUI { protected void installDefaults() { // Installs the text cursor on the component super.installDefaults(); - updateStyle((JTextComponent)getComponent()); + updateStyle(getComponent()); } protected void uninstallDefaults() { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java index 5b7cbd0a5f5..28bbdf843c4 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java @@ -232,7 +232,7 @@ class SynthTextFieldUI protected void installDefaults() { // Installs the text cursor on the component super.installDefaults(); - updateStyle((JTextComponent)getComponent()); + updateStyle(getComponent()); getComponent().addFocusListener(this); } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java index 1e12a820ece..464b947b071 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java @@ -390,7 +390,7 @@ class SynthTreeUI extends BasicTreeUI implements PropertyChangeListener, } private Rectangle getDropLineRect(JTree.DropLocation loc) { - Rectangle rect = null; + Rectangle rect; TreePath path = loc.getPath(); int index = loc.getChildIndex(); boolean ltr = tree.getComponentOrientation().isLeftToRight(); @@ -523,7 +523,7 @@ class SynthTreeUI extends BasicTreeUI implements PropertyChangeListener, // Don't paint the renderer if editing this row. boolean selected = tree.isRowSelected(row); - JTree.DropLocation dropLocation = (JTree.DropLocation)tree.getDropLocation(); + JTree.DropLocation dropLocation = tree.getDropLocation(); boolean isDrop = dropLocation != null && dropLocation.getChildIndex() == -1 && path == dropLocation.getPath(); diff --git a/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java b/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java index de209df68eb..f66692e5778 100644 --- a/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java +++ b/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java @@ -44,7 +44,7 @@ import javax.swing.plaf.*; * @author Scott Violet */ public class DefaultSynthStyle extends SynthStyle implements Cloneable { - private static final Object PENDING = new String("Pending"); + private static final String PENDING = "Pending"; /** * Should the component be opaque? @@ -690,8 +690,8 @@ public class DefaultSynthStyle extends SynthStyle implements Cloneable { StateInfo[] states = getStateInfo(); if (states != null) { buf.append("states["); - for (int i = 0; i < states.length; i++) { - buf.append(states[i].toString()).append(','); + for (StateInfo state : states) { + buf.append(state.toString()).append(','); } buf.append(']').append(','); } @@ -888,7 +888,7 @@ public class DefaultSynthStyle extends SynthStyle implements Cloneable { * Returns the number of states that are similar between the * ComponentState this StateInfo represents and val. */ - private final int getMatchCount(int val) { + private int getMatchCount(int val) { // This comes from BigInteger.bitCnt val &= state; val -= (0xaaaaaaaa & val) >>> 1; diff --git a/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java b/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java index abd99439ed0..2721764d1d7 100644 --- a/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java +++ b/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java @@ -735,7 +735,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { * Data model for a type-face selection combo-box. */ protected class DirectoryComboBoxModel extends AbstractListModel implements ComboBoxModel { - Vector directories = new Vector(); + Vector directories = new Vector(); int[] depths = null; File selectedDirectory = null; JFileChooser chooser = getFileChooser(); @@ -778,7 +778,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { // Get the canonical (full) path. This has the side // benefit of removing extraneous chars from the path, // for example /foo/bar/ becomes /foo/bar - File canonical = null; + File canonical; try { canonical = directory.getCanonicalFile(); } catch (IOException e) { @@ -791,7 +791,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { File sf = useShellFolder ? ShellFolder.getShellFolder(canonical) : canonical; File f = sf; - Vector path = new Vector(10); + Vector path = new Vector(10); do { path.addElement(f); } while ((f = f.getParentFile()) != null); @@ -799,7 +799,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { int pathCount = path.size(); // Insert chain at appropriate place in vector for (int i = 0; i < pathCount; i++) { - f = (File)path.get(i); + f = path.get(i); if (directories.contains(f)) { int topIndex = directories.indexOf(f); for (int j = i-1; j >= 0; j--) { @@ -818,12 +818,12 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { private void calculateDepths() { depths = new int[directories.size()]; for (int i = 0; i < depths.length; i++) { - File dir = (File)directories.get(i); + File dir = directories.get(i); File parent = dir.getParentFile(); depths[i] = 0; if (parent != null) { for (int j = i-1; j >= 0; j--) { - if (parent.equals((File)directories.get(j))) { + if (parent.equals(directories.get(j))) { depths[i] = depths[j] + 1; break; } @@ -940,8 +940,8 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { FileFilter currentFilter = getFileChooser().getFileFilter(); boolean found = false; if(currentFilter != null) { - for(int i=0; i < filters.length; i++) { - if(filters[i] == currentFilter) { + for (FileFilter filter : filters) { + if (filter == currentFilter) { found = true; } } From f7be937495c26e171cca46739ba26ac275468eb6 Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Fri, 25 Jul 2008 11:32:12 -0400 Subject: [PATCH 20/45] 6608456: need API to define RepaintManager per components hierarchy Reviewed-by: alexp --- jdk/make/javax/swing/Makefile | 2 +- .../com/sun/java/swing/SwingUtilities3.java | 91 ++++++++++ .../classes/javax/swing/RepaintManager.java | 51 ++++++ .../RepaintManager/6608456/bug6608456.java | 162 ++++++++++++++++++ 4 files changed, 305 insertions(+), 1 deletion(-) create mode 100644 jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java create mode 100644 jdk/test/javax/swing/RepaintManager/6608456/bug6608456.java diff --git a/jdk/make/javax/swing/Makefile b/jdk/make/javax/swing/Makefile index c2056a45ce2..e112e609cd9 100644 --- a/jdk/make/javax/swing/Makefile +++ b/jdk/make/javax/swing/Makefile @@ -33,7 +33,7 @@ include $(BUILDDIR)/common/Defs.gmk # Files # include FILES.gmk -AUTO_FILES_JAVA_DIRS = javax/swing sun/swing +AUTO_FILES_JAVA_DIRS = javax/swing sun/swing com/sun/java/swing AUTO_JAVA_PRUNE = plaf SUBDIRS = html32dtd plaf diff --git a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java new file mode 100644 index 00000000000..2ace1e4ce77 --- /dev/null +++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java @@ -0,0 +1,91 @@ +/* + * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package com.sun.java.swing; + +import sun.awt.AppContext; +import java.awt.Component; +import javax.swing.JComponent; +import javax.swing.RepaintManager; + +/** + * A collection of utility methods for Swing. + *

+ * WARNING: While this class is public, it should not be treated as + * public API and its API may change in incompatable ways between dot dot + * releases and even patch releases. You should not rely on this class even + * existing. + * + * This is a second part of sun.swing.SwingUtilities2. It is required + * to provide services for JavaFX applets. + * + */ +public class SwingUtilities3 { + /** + * The {@code clientProperty} key for delegate {@code RepaintManager} + */ + private static final Object DELEGATE_REPAINT_MANAGER_KEY = + new StringBuilder("DelegateRepaintManagerKey"); + + /** + * Registers delegate RepaintManager for {@code JComponent}. + */ + public static void setDelegateRepaintManager(JComponent component, + RepaintManager repaintManager) { + /* setting up flag in AppContext to speed up lookups in case + * there are no delegate RepaintManagers used. + */ + AppContext.getAppContext().put(DELEGATE_REPAINT_MANAGER_KEY, + Boolean.TRUE); + + component.putClientProperty(DELEGATE_REPAINT_MANAGER_KEY, + repaintManager); + } + + /** + * Returns delegate {@code RepaintManager} for {@code component} hierarchy. + */ + public static RepaintManager getDelegateRepaintManager(Component + component) { + RepaintManager delegate = null; + if (Boolean.TRUE == AppContext.getAppContext().get( + DELEGATE_REPAINT_MANAGER_KEY)) { + while (delegate == null && component != null) { + while (component != null + && ! (component instanceof JComponent)) { + component = component.getParent(); + } + if (component != null) { + delegate = (RepaintManager) + ((JComponent) component) + .getClientProperty(DELEGATE_REPAINT_MANAGER_KEY); + component = component.getParent(); + } + + } + } + return delegate; + } +} diff --git a/jdk/src/share/classes/javax/swing/RepaintManager.java b/jdk/src/share/classes/javax/swing/RepaintManager.java index 91034dbf8f2..81c81602255 100644 --- a/jdk/src/share/classes/javax/swing/RepaintManager.java +++ b/jdk/src/share/classes/javax/swing/RepaintManager.java @@ -40,6 +40,8 @@ import sun.awt.SunToolkit; import sun.java2d.SunGraphicsEnvironment; import sun.security.action.GetPropertyAction; +import com.sun.java.swing.SwingUtilities3; + /** * This class manages repaint requests, allowing the number @@ -303,6 +305,11 @@ public class RepaintManager */ public synchronized void addInvalidComponent(JComponent invalidComponent) { + RepaintManager delegate = getDelegate(invalidComponent); + if (delegate != null) { + delegate.addInvalidComponent(invalidComponent); + return; + } Component validateRoot = null; /* Find the first JComponent ancestor of this component whose @@ -373,6 +380,11 @@ public class RepaintManager * @see #addInvalidComponent */ public synchronized void removeInvalidComponent(JComponent component) { + RepaintManager delegate = getDelegate(component); + if (delegate != null) { + delegate.removeInvalidComponent(component); + return; + } if(invalidComponents != null) { int index = invalidComponents.indexOf(component); if(index != -1) { @@ -464,6 +476,11 @@ public class RepaintManager */ public void addDirtyRegion(JComponent c, int x, int y, int w, int h) { + RepaintManager delegate = getDelegate(c); + if (delegate != null) { + delegate.addDirtyRegion(c, x, y, w, h); + return; + } addDirtyRegion0(c, x, y, w, h); } @@ -588,6 +605,10 @@ public class RepaintManager * dirty. */ public Rectangle getDirtyRegion(JComponent aComponent) { + RepaintManager delegate = getDelegate(aComponent); + if (delegate != null) { + return delegate.getDirtyRegion(aComponent); + } Rectangle r = null; synchronized(this) { r = (Rectangle)dirtyComponents.get(aComponent); @@ -603,6 +624,11 @@ public class RepaintManager * completely painted during the next paintDirtyRegions() call. */ public void markCompletelyDirty(JComponent aComponent) { + RepaintManager delegate = getDelegate(aComponent); + if (delegate != null) { + delegate.markCompletelyDirty(aComponent); + return; + } addDirtyRegion(aComponent,0,0,Integer.MAX_VALUE,Integer.MAX_VALUE); } @@ -611,6 +637,11 @@ public class RepaintManager * get painted during the next paintDirtyRegions() call. */ public void markCompletelyClean(JComponent aComponent) { + RepaintManager delegate = getDelegate(aComponent); + if (delegate != null) { + delegate.markCompletelyClean(aComponent); + return; + } synchronized(this) { dirtyComponents.remove(aComponent); } @@ -623,6 +654,10 @@ public class RepaintManager * if it return true. */ public boolean isCompletelyDirty(JComponent aComponent) { + RepaintManager delegate = getDelegate(aComponent); + if (delegate != null) { + return delegate.isCompletelyDirty(aComponent); + } Rectangle r; r = getDirtyRegion(aComponent); @@ -900,6 +935,10 @@ public class RepaintManager * repaint manager. */ public Image getOffscreenBuffer(Component c,int proposedWidth,int proposedHeight) { + RepaintManager delegate = getDelegate(c); + if (delegate != null) { + return delegate.getOffscreenBuffer(c, proposedWidth, proposedHeight); + } return _getOffscreenBuffer(c, proposedWidth, proposedHeight); } @@ -917,6 +956,11 @@ public class RepaintManager */ public Image getVolatileOffscreenBuffer(Component c, int proposedWidth,int proposedHeight) { + RepaintManager delegate = getDelegate(c); + if (delegate != null) { + return delegate.getVolatileOffscreenBuffer(c, proposedWidth, + proposedHeight); + } GraphicsConfiguration config = c.getGraphicsConfiguration(); if (config == null) { config = GraphicsEnvironment.getLocalGraphicsEnvironment(). @@ -1550,4 +1594,11 @@ public class RepaintManager prePaintDirtyRegions(); } } + private RepaintManager getDelegate(Component c) { + RepaintManager delegate = SwingUtilities3.getDelegateRepaintManager(c); + if (this == delegate) { + delegate = null; + } + return delegate; + } } diff --git a/jdk/test/javax/swing/RepaintManager/6608456/bug6608456.java b/jdk/test/javax/swing/RepaintManager/6608456/bug6608456.java new file mode 100644 index 00000000000..1d8a14fcaa2 --- /dev/null +++ b/jdk/test/javax/swing/RepaintManager/6608456/bug6608456.java @@ -0,0 +1,162 @@ +/* + * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * + * @bug 6608456 + * @author Igor Kushnirskiy + * @summary tests if delegate RepaintManager gets invoked. + */ + +import java.awt.*; +import java.lang.reflect.Method; +import java.util.concurrent.Callable; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; + +import javax.swing.JComponent; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.RepaintManager; +import javax.swing.SwingUtilities; + + + +public class bug6608456 { + private static final TestFuture testFuture = new TestFuture(); + public static void main(String[] args) throws Exception { + final JComponent component = invokeAndWait( + new Callable() { + public JComponent call() throws Exception { + RepaintManager.setCurrentManager(new TestRepaintManager()); + JFrame frame = new JFrame("test"); + frame.setLayout(new FlowLayout()); + JButton button = new JButton("default"); + + frame.add(button); + button = new JButton("delegate"); + if ( ! registerDelegate( + button, new TestRepaintManager())) { + return null; + } + frame.add(button); + frame.pack(); + frame.setVisible(true); + return button; + } + }); + if (component == null) { + throw new RuntimeException("failed. can not register delegate"); + } + blockTillDisplayed(component); + // trigger repaint for delegate RepaintManager + invokeAndWait( + new Callable() { + public Void call() { + component.repaint(); + return null; + } + }); + try { + if (testFuture.get(10, TimeUnit.SECONDS)) { + // passed + } + } catch (Exception e) { + throw new RuntimeException("failed", e); + } finally { + JFrame frame = (JFrame) SwingUtilities + .getAncestorOfClass(JFrame.class, component); + if (frame != null) { + frame.dispose(); + } + } + } + static class TestRepaintManager extends RepaintManager { + @Override + public void addDirtyRegion(JComponent c, int x, int y, int w, int h) { + if (RepaintManager.currentManager(c) == this) { + testFuture.defaultCalled(); + } else { + testFuture.delegateCalled(); + } + super.addDirtyRegion(c, x, y, w, h); + } + } + static class TestFuture extends FutureTask { + private volatile boolean defaultCalled = false; + private volatile boolean delegateCalled = false; + public TestFuture() { + super(new Callable() { + public Boolean call() { + return null; + } + }); + } + public void defaultCalled() { + defaultCalled = true; + updateState(); + } + public void delegateCalled() { + delegateCalled = true; + updateState(); + } + private void updateState() { + if (defaultCalled && delegateCalled) { + set(Boolean.TRUE); + } + } + } + + private static boolean registerDelegate(JComponent c, + RepaintManager repaintManager) { + boolean rv = false; + try { + Class clazz = Class.forName("com.sun.java.swing.SwingUtilities3"); + Method method = clazz.getMethod("setDelegateRepaintManager", + JComponent.class, RepaintManager.class); + method.invoke(clazz, c, repaintManager); + rv = true; + } catch (Exception ignore) { + } + return rv; + } + static T invokeAndWait(Callable callable) throws Exception { + FutureTask future = new FutureTask(callable); + SwingUtilities.invokeLater(future); + return future.get(); + } + + public static void blockTillDisplayed(Component comp) { + Point p = null; + while (p == null) { + try { + p = comp.getLocationOnScreen(); + } catch (IllegalStateException e) { + try { + Thread.sleep(100); + } catch (InterruptedException ie) { + } + } + } + } +} From 873a9176c75501f08faca765df10ef6b4f8879a5 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Fri, 25 Jul 2008 21:00:05 +0400 Subject: [PATCH 21/45] 6630275: The spec on VetoableChangeSupport.fireVetoableChange should be updated Reviewed-by: peterz, rupashka --- .../java/beans/PropertyChangeSupport.java | 195 ++++++++-------- .../java/beans/VetoableChangeSupport.java | 215 ++++++++++-------- .../VetoableChangeSupport/Test6630275.java | 81 +++++++ 3 files changed, 293 insertions(+), 198 deletions(-) create mode 100644 jdk/test/java/beans/VetoableChangeSupport/Test6630275.java diff --git a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java index 2d4ed88fdb3..2a3f79ff3f2 100644 --- a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java +++ b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -208,91 +208,91 @@ public class PropertyChangeSupport implements Serializable { } /** - * Report a bound property update to any registered listeners. - * No event is fired if old and new are equal and non-null. - * + * Reports a bound property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if old and new values are equal and non-null. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes {@code - * PropertyChangeEvent} value. + * {@link #firePropertyChange(PropertyChangeEvent)} method. * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property */ - public void firePropertyChange(String propertyName, - Object oldValue, Object newValue) { - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + firePropertyChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue)); } - firePropertyChange(new PropertyChangeEvent(source, propertyName, - oldValue, newValue)); } /** - * Report an int bound property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports an integer bound property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes Object values. + * {@link #firePropertyChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property */ - public void firePropertyChange(String propertyName, - int oldValue, int newValue) { - if (oldValue == newValue) { - return; + public void firePropertyChange(String propertyName, int oldValue, int newValue) { + if (oldValue != newValue) { + firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } - firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } /** - * Report a boolean bound property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports a boolean bound property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes Object values. + * {@link #firePropertyChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property */ - public void firePropertyChange(String propertyName, - boolean oldValue, boolean newValue) { - if (oldValue == newValue) { - return; + public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { + if (oldValue != newValue) { + firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } - firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } /** - * Fire an existing PropertyChangeEvent to any registered listeners. - * No event is fired if the given event's old and new values are - * equal and non-null. - * @param evt The PropertyChangeEvent object. + * Fires a property change event to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if the given event's old and new values are equal and non-null. + * + * @param event the {@code PropertyChangeEvent} to be fired */ - public void firePropertyChange(PropertyChangeEvent evt) { - Object oldValue = evt.getOldValue(); - Object newValue = evt.getNewValue(); - String propertyName = evt.getPropertyName(); - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; - } - PropertyChangeListener[] common = this.map.get(null); - PropertyChangeListener[] named = (propertyName != null) - ? this.map.get(propertyName) - : null; + public void firePropertyChange(PropertyChangeEvent event) { + Object oldValue = event.getOldValue(); + Object newValue = event.getNewValue(); + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + String name = event.getPropertyName(); - fire(common, evt); - fire(named, evt); + PropertyChangeListener[] common = this.map.get(null); + PropertyChangeListener[] named = (name != null) + ? this.map.get(name) + : null; + + fire(common, event); + fire(named, event); + } } - private void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) { + private static void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) { if (listeners != null) { for (PropertyChangeListener listener : listeners) { listener.propertyChange(event); @@ -301,78 +301,69 @@ public class PropertyChangeSupport implements Serializable { } /** - * Report a bound indexed property update to any registered - * listeners. + * Reports a bound indexed property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

- * No event is fired if old and new values are equal - * and non-null. - * + * No event is fired if old and new values are equal and non-null. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes {@code PropertyChangeEvent} value. + * {@link #firePropertyChange(PropertyChangeEvent)} method. * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param index the index of the property element that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property * @since 1.5 */ - public void fireIndexedPropertyChange(String propertyName, int index, - Object oldValue, Object newValue) { - firePropertyChange(new IndexedPropertyChangeEvent - (source, propertyName, oldValue, newValue, index)); + public void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue) { + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + firePropertyChange(new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index)); + } } /** - * Report an int bound indexed property update to any registered - * listeners. + * Reports an integer bound indexed property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

* No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireIndexedPropertyChange method which takes Object values. + * {@link #fireIndexedPropertyChange(String, int, Object, Object)} method. * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param index the index of the property element that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property * @since 1.5 */ - public void fireIndexedPropertyChange(String propertyName, int index, - int oldValue, int newValue) { - if (oldValue == newValue) { - return; + public void fireIndexedPropertyChange(String propertyName, int index, int oldValue, int newValue) { + if (oldValue != newValue) { + fireIndexedPropertyChange(propertyName, index, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } - fireIndexedPropertyChange(propertyName, index, - Integer.valueOf(oldValue), - Integer.valueOf(newValue)); } /** - * Report a boolean bound indexed property update to any - * registered listeners. + * Reports a boolean bound indexed property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

* No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireIndexedPropertyChange method which takes Object values. + * {@link #fireIndexedPropertyChange(String, int, Object, Object)} method. * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param index the index of the property element that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property * @since 1.5 */ - public void fireIndexedPropertyChange(String propertyName, int index, - boolean oldValue, boolean newValue) { - if (oldValue == newValue) { - return; + public void fireIndexedPropertyChange(String propertyName, int index, boolean oldValue, boolean newValue) { + if (oldValue != newValue) { + fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } - fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue), - Boolean.valueOf(newValue)); } /** diff --git a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java index 7d1418e17d2..f6707b49f7f 100644 --- a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java +++ b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -208,126 +208,149 @@ public class VetoableChangeSupport implements Serializable { } /** - * Report a vetoable property update to any registered listeners. If - * anyone vetos the change, then fire a new event reverting everyone to - * the old value and then rethrow the PropertyVetoException. + * Reports a constrained property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

- * No event is fired if old and new are equal and non-null. - * - * @param propertyName The programmatic name of the property - * that is about to change.. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. - * @exception PropertyVetoException if the recipient wishes the property - * change to be rolled back. - */ - public void fireVetoableChange(String propertyName, - Object oldValue, Object newValue) - throws PropertyVetoException { - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; - } - PropertyChangeEvent evt = new PropertyChangeEvent(source, propertyName, - oldValue, newValue); - fireVetoableChange(evt); - } - - /** - * Report a int vetoable property update to any registered listeners. - * No event is fired if old and new are equal. + * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if old and new values are equal and non-null. *

* This is merely a convenience wrapper around the more general - * fireVetoableChange method that takes Object values. + * {@link #fireVetoableChange(PropertyChangeEvent)} method. * - * @param propertyName The programmatic name of the property - * that is about to change. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that is about to change + * @param oldValue the old value of the property + * @param newValue the new value of the property + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(String propertyName, - int oldValue, int newValue) - throws PropertyVetoException { - if (oldValue == newValue) { - return; + public void fireVetoableChange(String propertyName, Object oldValue, Object newValue) + throws PropertyVetoException { + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + fireVetoableChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue)); } - fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } /** - * Report a boolean vetoable property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports an integer constrained property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireVetoableChange method that takes Object values. + * {@link #fireVetoableChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that is about to change. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that is about to change + * @param oldValue the old value of the property + * @param newValue the new value of the property + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(String propertyName, - boolean oldValue, boolean newValue) - throws PropertyVetoException { - if (oldValue == newValue) { - return; + public void fireVetoableChange(String propertyName, int oldValue, int newValue) + throws PropertyVetoException { + if (oldValue != newValue) { + fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } - fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } /** - * Fire a vetoable property update to any registered listeners. If - * anyone vetos the change, then fire a new event reverting everyone to - * the old value and then rethrow the PropertyVetoException. + * Reports a boolean constrained property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

- * No event is fired if old and new are equal and non-null. + * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if old and new values are equal. + *

+ * This is merely a convenience wrapper around the more general + * {@link #fireVetoableChange(String, Object, Object)} method. * - * @param evt The PropertyChangeEvent to be fired. - * @exception PropertyVetoException if the recipient wishes the property - * change to be rolled back. + * @param propertyName the programmatic name of the property that is about to change + * @param oldValue the old value of the property + * @param newValue the new value of the property + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(PropertyChangeEvent evt) - throws PropertyVetoException { - - Object oldValue = evt.getOldValue(); - Object newValue = evt.getNewValue(); - String propertyName = evt.getPropertyName(); - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; + public void fireVetoableChange(String propertyName, boolean oldValue, boolean newValue) + throws PropertyVetoException { + if (oldValue != newValue) { + fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } - VetoableChangeListener[] common = this.map.get(null); - VetoableChangeListener[] named = (propertyName != null) - ? this.map.get(propertyName) - : null; - fire(common, evt); - fire(named, evt); } - private void fire(VetoableChangeListener[] listeners, PropertyChangeEvent event) throws PropertyVetoException { - if (listeners != null) { - VetoableChangeListener current = null; - try { - for (VetoableChangeListener listener : listeners) { - current = listener; - listener.vetoableChange(event); - } - } catch (PropertyVetoException veto) { - // Create an event to revert everyone to the old value. - event = new PropertyChangeEvent( this.source, - event.getPropertyName(), - event.getNewValue(), - event.getOldValue() ); - for (VetoableChangeListener listener : listeners) { - if (current == listener) { - break; - } - try { - listener.vetoableChange(event); - } catch (PropertyVetoException ex) { - // We just ignore exceptions that occur during reversions. + /** + * Fires a property change event to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if the given event's old and new values are equal and non-null. + * + * @param event the {@code PropertyChangeEvent} to be fired + * @throws PropertyVetoException if one of listeners vetoes the property update + */ + public void fireVetoableChange(PropertyChangeEvent event) + throws PropertyVetoException { + Object oldValue = event.getOldValue(); + Object newValue = event.getNewValue(); + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + String name = event.getPropertyName(); + + VetoableChangeListener[] common = this.map.get(null); + VetoableChangeListener[] named = (name != null) + ? this.map.get(name) + : null; + + VetoableChangeListener[] listeners; + if (common == null) { + listeners = named; + } + else if (named == null) { + listeners = common; + } + else { + listeners = new VetoableChangeListener[common.length + named.length]; + System.arraycopy(common, 0, listeners, 0, common.length); + System.arraycopy(named, 0, listeners, common.length, named.length); + } + if (listeners != null) { + int current = 0; + try { + while (current < listeners.length) { + listeners[current].vetoableChange(event); + current++; } } - // And now rethrow the PropertyVetoException. - throw veto; + catch (PropertyVetoException veto) { + event = new PropertyChangeEvent(this.source, name, newValue, oldValue); + for (int i = 0; i < current; i++) { + try { + listeners[i].vetoableChange(event); + } + catch (PropertyVetoException exception) { + // ignore exceptions that occur during rolling back + } + } + throw veto; // rethrow the veto exception + } } } } diff --git a/jdk/test/java/beans/VetoableChangeSupport/Test6630275.java b/jdk/test/java/beans/VetoableChangeSupport/Test6630275.java new file mode 100644 index 00000000000..ce68720d809 --- /dev/null +++ b/jdk/test/java/beans/VetoableChangeSupport/Test6630275.java @@ -0,0 +1,81 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6630275 + * @summary Tests VetoableChangeSupport specification + * @author Sergey Malenkov + */ + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyVetoException; +import java.beans.VetoableChangeListener; +import java.beans.VetoableChangeSupport; + +public class Test6630275 { + private static final String PROPERTY = "property"; // NON-NLS: predefined property name + + public static void main(String[] args) { + CheckListener first = new CheckListener(false); + CheckListener second = new CheckListener(true); + CheckListener third = new CheckListener(false); + + VetoableChangeSupport vcs = new VetoableChangeSupport(Test6630275.class); + vcs.addVetoableChangeListener(first); + vcs.addVetoableChangeListener(PROPERTY, first); + vcs.addVetoableChangeListener(PROPERTY, second); + vcs.addVetoableChangeListener(PROPERTY, third); + try { + vcs.fireVetoableChange(PROPERTY, true, false); + } catch (PropertyVetoException exception) { + first.validate(); + second.validate(); + third.validate(); + return; // expected exception + } + throw new Error("exception should be thrown"); + } + + private static class CheckListener implements VetoableChangeListener { + private final boolean veto; + private boolean odd; // even/odd check for notification + + private CheckListener(boolean veto) { + this.veto = veto; + } + + private void validate() { + if (this.veto != this.odd) + throw new Error(this.odd + ? "undo event expected" + : "unexpected undo event"); + } + + public void vetoableChange(PropertyChangeEvent event) throws PropertyVetoException { + this.odd = !this.odd; + if (this.veto) + throw new PropertyVetoException("disable all changes", event); + } + } +} From b4ae1216b3d0441294a6485c7f36f8df48340b50 Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Fri, 25 Jul 2008 14:13:59 -0400 Subject: [PATCH 22/45] 6638195: need API for EventQueueDelegate Reviewed-by: bchristi --- .../com/sun/java/swing/SwingUtilities3.java | 83 +++++++++++ .../classes/java/awt/EventDispatchThread.java | 20 ++- .../classes/sun/awt/EventQueueDelegate.java | 71 +++++++++ .../awt/EventQueue/6638195/bug6638195.java | 138 ++++++++++++++++++ 4 files changed, 309 insertions(+), 3 deletions(-) create mode 100644 jdk/src/share/classes/sun/awt/EventQueueDelegate.java create mode 100644 jdk/test/java/awt/EventQueue/6638195/bug6638195.java diff --git a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java index 2ace1e4ce77..9268d7370a3 100644 --- a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java +++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java @@ -25,7 +25,12 @@ package com.sun.java.swing; +import sun.awt.EventQueueDelegate; import sun.awt.AppContext; +import java.util.Map; +import java.util.concurrent.Callable; +import java.awt.AWTEvent; +import java.awt.EventQueue; import java.awt.Component; import javax.swing.JComponent; import javax.swing.RepaintManager; @@ -88,4 +93,82 @@ public class SwingUtilities3 { } return delegate; } + + /* + * We use maps to avoid reflection. Hopefully it should perform better + * this way. + */ + public static void setEventQueueDelegate( + Map> map) { + EventQueueDelegate.setDelegate(new EventQueueDelegateFromMap(map)); + } + + private static class EventQueueDelegateFromMap + implements EventQueueDelegate.Delegate { + private final AWTEvent[] afterDispatchEventArgument; + private final Object[] afterDispatchHandleArgument; + private final Callable afterDispatchCallable; + + private final AWTEvent[] beforeDispatchEventArgument; + private final Callable beforeDispatchCallable; + + private final EventQueue[] getNextEventEventQueueArgument; + private final Callable getNextEventCallable; + + @SuppressWarnings("unchecked") + public EventQueueDelegateFromMap(Map> objectMap) { + Map methodMap = objectMap.get("afterDispatch"); + afterDispatchEventArgument = (AWTEvent[]) methodMap.get("event"); + afterDispatchHandleArgument = (Object[]) methodMap.get("handle"); + afterDispatchCallable = (Callable) methodMap.get("method"); + + methodMap = objectMap.get("beforeDispatch"); + beforeDispatchEventArgument = (AWTEvent[]) methodMap.get("event"); + beforeDispatchCallable = (Callable) methodMap.get("method"); + + methodMap = objectMap.get("getNextEvent"); + getNextEventEventQueueArgument = + (EventQueue[]) methodMap.get("eventQueue"); + getNextEventCallable = (Callable) methodMap.get("method"); + } + + @Override + public void afterDispatch(AWTEvent event, Object handle) { + afterDispatchEventArgument[0] = event; + afterDispatchHandleArgument[0] = handle; + try { + afterDispatchCallable.call(); + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + } + } + + @Override + public Object beforeDispatch(AWTEvent event) { + beforeDispatchEventArgument[0] = event; + try { + return beforeDispatchCallable.call(); + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + } + return null; + } + + @Override + public AWTEvent getNextEvent(EventQueue eventQueue) { + getNextEventEventQueueArgument[0] = eventQueue; + try { + return getNextEventCallable.call(); + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + } + return null; + } + } } diff --git a/jdk/src/share/classes/java/awt/EventDispatchThread.java b/jdk/src/share/classes/java/awt/EventDispatchThread.java index f49bacb670a..23d08a0d418 100644 --- a/jdk/src/share/classes/java/awt/EventDispatchThread.java +++ b/jdk/src/share/classes/java/awt/EventDispatchThread.java @@ -39,6 +39,7 @@ import java.util.Vector; import java.util.logging.*; import sun.awt.dnd.SunDragSourceContextPeer; +import sun.awt.EventQueueDelegate; /** * EventDispatchThread is a package-private AWT class which takes @@ -243,10 +244,16 @@ class EventDispatchThread extends Thread { try { AWTEvent event; boolean eventOK; + EventQueueDelegate.Delegate delegate = + EventQueueDelegate.getDelegate(); do { - event = (id == ANY_EVENT) - ? theQueue.getNextEvent() - : theQueue.getNextEvent(id); + if (delegate != null && id == ANY_EVENT) { + event = delegate.getNextEvent(theQueue); + } else { + event = (id == ANY_EVENT) + ? theQueue.getNextEvent() + : theQueue.getNextEvent(id); + } eventOK = true; synchronized (eventFilters) { @@ -272,7 +279,14 @@ class EventDispatchThread extends Thread { eventLog.log(Level.FINEST, "Dispatching: " + event); } + Object handle = null; + if (delegate != null) { + handle = delegate.beforeDispatch(event); + } theQueue.dispatchEvent(event); + if (delegate != null) { + delegate.afterDispatch(event, handle); + } return true; } catch (ThreadDeath death) { diff --git a/jdk/src/share/classes/sun/awt/EventQueueDelegate.java b/jdk/src/share/classes/sun/awt/EventQueueDelegate.java new file mode 100644 index 00000000000..8f8a6f3fe0b --- /dev/null +++ b/jdk/src/share/classes/sun/awt/EventQueueDelegate.java @@ -0,0 +1,71 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package sun.awt; + +import java.awt.AWTEvent; +import java.awt.EventQueue; + + +public class EventQueueDelegate { + private static final Object EVENT_QUEUE_DELEGATE_KEY = + new StringBuilder("EventQueueDelegate.Delegate"); + + public static void setDelegate(Delegate delegate) { + AppContext.getAppContext().put(EVENT_QUEUE_DELEGATE_KEY, delegate); + } + public static Delegate getDelegate() { + return + (Delegate) AppContext.getAppContext().get(EVENT_QUEUE_DELEGATE_KEY); + } + public interface Delegate { + /** + * This method allows for changing {@code EventQueue} events order. + * + * @param eventQueue current {@code EventQueue} + * @return next {@code event} for the {@code EventDispatchThread} + */ + + public AWTEvent getNextEvent(EventQueue eventQueue) throws InterruptedException; + + /** + * Notifies delegate before EventQueue.dispatch method. + * + * Note: this method may mutate the event + * + * @param event to be dispatched by {@code dispatch} method + * @return handle to be passed to {@code afterDispatch} method + */ + public Object beforeDispatch(AWTEvent event); + + /** + * Notifies delegate after EventQueue.dispatch method. + * + * @param event {@code event} dispatched by the {@code dispatch} method + * @param handle object which came from {@code beforeDispatch} method + */ + public void afterDispatch(AWTEvent event, Object handle); + } +} diff --git a/jdk/test/java/awt/EventQueue/6638195/bug6638195.java b/jdk/test/java/awt/EventQueue/6638195/bug6638195.java new file mode 100644 index 00000000000..b1109967071 --- /dev/null +++ b/jdk/test/java/awt/EventQueue/6638195/bug6638195.java @@ -0,0 +1,138 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * + * @bug 6638195 + * @author Igor Kushnirskiy + * @summary tests if EventQueueDelegate.Delegate is invoked. + */ + +import sun.awt.EventQueueDelegate; +import com.sun.java.swing.SwingUtilities3; + +import java.util.*; +import java.util.concurrent.*; +import java.awt.*; + +public class bug6638195 { + public static void main(String[] args) throws Exception { + MyEventQueueDelegate delegate = new MyEventQueueDelegate(); + EventQueueDelegate.setDelegate(delegate); + runTest(delegate); + + delegate = new MyEventQueueDelegate(); + SwingUtilities3.setEventQueueDelegate(getObjectMap(delegate)); + runTest(delegate); + } + + private static void runTest(MyEventQueueDelegate delegate) throws Exception { + EventQueue.invokeLater( + new Runnable() { + public void run() { + } + }); + final CountDownLatch latch = new CountDownLatch(1); + EventQueue.invokeLater( + new Runnable() { + public void run() { + latch.countDown(); + } + }); + latch.await(); + if (! delegate.allInvoked()) { + throw new RuntimeException("failed"); + } + } + + static Map> getObjectMap( + final EventQueueDelegate.Delegate delegate) { + Map> objectMap = + new HashMap>(); + Map methodMap; + + final AWTEvent[] afterDispatchEventArgument = new AWTEvent[1]; + final Object[] afterDispatchHandleArgument = new Object[1]; + Callable afterDispatchCallable = + new Callable() { + public Void call() { + delegate.afterDispatch(afterDispatchEventArgument[0], + afterDispatchHandleArgument[0]); + return null; + } + }; + methodMap = new HashMap(); + methodMap.put("event", afterDispatchEventArgument); + methodMap.put("handle", afterDispatchHandleArgument); + methodMap.put("method", afterDispatchCallable); + objectMap.put("afterDispatch", methodMap); + + final AWTEvent[] beforeDispatchEventArgument = new AWTEvent[1]; + Callable beforeDispatchCallable = + new Callable() { + public Object call() { + return delegate.beforeDispatch( + beforeDispatchEventArgument[0]); + } + }; + methodMap = new HashMap(); + methodMap.put("event", beforeDispatchEventArgument); + methodMap.put("method", beforeDispatchCallable); + objectMap.put("beforeDispatch", methodMap); + + final EventQueue[] getNextEventEventQueueArgument = new EventQueue[1]; + Callable getNextEventCallable = + new Callable() { + public AWTEvent call() throws Exception { + return delegate.getNextEvent( + getNextEventEventQueueArgument[0]); + } + }; + methodMap = new HashMap(); + methodMap.put("eventQueue", getNextEventEventQueueArgument); + methodMap.put("method", getNextEventCallable); + objectMap.put("getNextEvent", methodMap); + + return objectMap; + } + static class MyEventQueueDelegate implements EventQueueDelegate.Delegate { + private volatile boolean getNextEventInvoked = false; + private volatile boolean beforeDispatchInvoked = false; + private volatile boolean afterDispatchInvoked = false; + public AWTEvent getNextEvent(EventQueue eventQueue) + throws InterruptedException { + getNextEventInvoked = true; + return eventQueue.getNextEvent(); + } + public Object beforeDispatch(AWTEvent event) { + beforeDispatchInvoked = true; + return null; + } + public void afterDispatch(AWTEvent event, Object handle) { + afterDispatchInvoked = true; + } + private boolean allInvoked() { + return getNextEventInvoked && beforeDispatchInvoked && afterDispatchInvoked; + } + } +} From 1dce4ceddd3c2e0a986e7e5fcdc46790ef8043fa Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Fri, 25 Jul 2008 14:26:27 -0400 Subject: [PATCH 23/45] 6699328: NullPointerException in EventQueue.dispatchEvent when applet is closed, only reprise/scenario applet Reviewed-by: bchristi --- .../com/sun/java/swing/SwingUtilities3.java | 32 +++++++++++-------- .../classes/sun/awt/EventQueueDelegate.java | 4 +-- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java index 9268d7370a3..28d9e8af6ec 100644 --- a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java +++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java @@ -133,42 +133,46 @@ public class SwingUtilities3 { } @Override - public void afterDispatch(AWTEvent event, Object handle) { + public void afterDispatch(AWTEvent event, Object handle) throws InterruptedException { afterDispatchEventArgument[0] = event; afterDispatchHandleArgument[0] = handle; try { afterDispatchCallable.call(); + } catch (InterruptedException e) { + throw e; + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } + throw new RuntimeException(e); } } @Override - public Object beforeDispatch(AWTEvent event) { + public Object beforeDispatch(AWTEvent event) throws InterruptedException { beforeDispatchEventArgument[0] = event; try { return beforeDispatchCallable.call(); + } catch (InterruptedException e) { + throw e; + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } + throw new RuntimeException(e); } - return null; } @Override - public AWTEvent getNextEvent(EventQueue eventQueue) { + public AWTEvent getNextEvent(EventQueue eventQueue) throws InterruptedException { getNextEventEventQueueArgument[0] = eventQueue; try { return getNextEventCallable.call(); + } catch (InterruptedException e) { + throw e; + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } + throw new RuntimeException(e); } - return null; } } } diff --git a/jdk/src/share/classes/sun/awt/EventQueueDelegate.java b/jdk/src/share/classes/sun/awt/EventQueueDelegate.java index 8f8a6f3fe0b..c9d0a90d2af 100644 --- a/jdk/src/share/classes/sun/awt/EventQueueDelegate.java +++ b/jdk/src/share/classes/sun/awt/EventQueueDelegate.java @@ -58,7 +58,7 @@ public class EventQueueDelegate { * @param event to be dispatched by {@code dispatch} method * @return handle to be passed to {@code afterDispatch} method */ - public Object beforeDispatch(AWTEvent event); + public Object beforeDispatch(AWTEvent event) throws InterruptedException; /** * Notifies delegate after EventQueue.dispatch method. @@ -66,6 +66,6 @@ public class EventQueueDelegate { * @param event {@code event} dispatched by the {@code dispatch} method * @param handle object which came from {@code beforeDispatch} method */ - public void afterDispatch(AWTEvent event, Object handle); + public void afterDispatch(AWTEvent event, Object handle) throws InterruptedException; } } From f092fd7939be299a9c311ab3b774d2045fcdb7a0 Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Fri, 8 Aug 2008 20:49:26 +0400 Subject: [PATCH 24/45] 6584657: GTK Look and Feel: Bugs in menu item layout Reviewed-by: peterz, alexp --- .../classes/javax/swing/SwingUtilities.java | 10 +- .../swing/plaf/basic/BasicMenuItemUI.java | 1052 ++----------- .../swing/plaf/basic/DefaultMenuLayout.java | 16 +- .../swing/plaf/synth/DefaultMenuLayout.java | 27 +- .../swing/plaf/synth/SynthGraphicsUtils.java | 196 ++- .../plaf/synth/SynthMenuItemLayoutHelper.java | 307 ++++ .../swing/plaf/synth/SynthMenuItemUI.java | 559 +------ .../javax/swing/plaf/synth/SynthMenuUI.java | 49 +- .../swing/plaf/synth/SynthPopupMenuUI.java | 114 +- .../sun/swing/MenuItemLayoutHelper.java | 1339 +++++++++++++++++ 10 files changed, 2002 insertions(+), 1667 deletions(-) create mode 100644 jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java create mode 100644 jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java diff --git a/jdk/src/share/classes/javax/swing/SwingUtilities.java b/jdk/src/share/classes/javax/swing/SwingUtilities.java index d8f29e5288c..38f18e78122 100644 --- a/jdk/src/share/classes/javax/swing/SwingUtilities.java +++ b/jdk/src/share/classes/javax/swing/SwingUtilities.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -974,6 +974,7 @@ public class SwingUtilities implements SwingConstants boolean textIsEmpty = (text == null) || text.equals(""); int lsb = 0; + int rsb = 0; /* Unless both text and icon are non-null, we effectively ignore * the value of textIconGap. */ @@ -1015,7 +1016,7 @@ public class SwingUtilities implements SwingConstants if (lsb < 0) { textR.width -= lsb; } - int rsb = SwingUtilities2.getRightSideBearing(c, fm, text); + rsb = SwingUtilities2.getRightSideBearing(c, fm, text); if (rsb > 0) { textR.width += rsb; } @@ -1118,6 +1119,11 @@ public class SwingUtilities implements SwingConstants // lsb is negative. Shift the x location so that the text is // visually drawn at the right location. textR.x -= lsb; + + textR.width += lsb; + } + if (rsb > 0) { + textR.width -= rsb; } return text; diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java index 5e81bfd062e..a58cc467c5f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,6 @@ package javax.swing.plaf.basic; -import sun.swing.MenuItemCheckIconFactory; -import sun.swing.SwingUtilities2; -import static sun.swing.SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; @@ -39,8 +36,7 @@ import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.text.View; -import sun.swing.UIAction; -import sun.swing.StringUIClientPropertyKey; +import sun.swing.*; /** * BasicMenuItem implementation @@ -91,24 +87,6 @@ public class BasicMenuItemUI extends MenuItemUI private static final boolean VERBOSE = false; // show reuse hits/misses private static final boolean DEBUG = false; // show bad params, misc. - // Allows to reuse layoutInfo object. - // Shouldn't be used directly. Use getLayoutInfo() instead. - private final transient LayoutInfo layoutInfo = new LayoutInfo(); - - /* Client Property keys for calculation of maximal widths */ - static final StringUIClientPropertyKey MAX_ARROW_WIDTH = - new StringUIClientPropertyKey("maxArrowWidth"); - static final StringUIClientPropertyKey MAX_CHECK_WIDTH = - new StringUIClientPropertyKey("maxCheckWidth"); - static final StringUIClientPropertyKey MAX_ICON_WIDTH = - new StringUIClientPropertyKey("maxIconWidth"); - static final StringUIClientPropertyKey MAX_TEXT_WIDTH = - new StringUIClientPropertyKey("maxTextWidth"); - static final StringUIClientPropertyKey MAX_ACC_WIDTH = - new StringUIClientPropertyKey("maxAccWidth"); - static final StringUIClientPropertyKey MAX_LABEL_WIDTH = - new StringUIClientPropertyKey("maxLabelWidth"); - static void loadActionMap(LazyActionMap map) { // NOTE: BasicMenuUI also calls into this method. map.put(new Actions(Actions.CLICK)); @@ -199,13 +177,14 @@ public class BasicMenuItemUI extends MenuItemUI //In case of column layout, .checkIconFactory is defined for this UI, //the icon is compatible with it and useCheckAndArrow() is true, //then the icon is handled by the checkIcon. - boolean isColumnLayout = LayoutInfo.isColumnLayout( + boolean isColumnLayout = MenuItemLayoutHelper.isColumnLayout( BasicGraphicsUtils.isLeftToRight(menuItem), menuItem); if (isColumnLayout) { MenuItemCheckIconFactory iconFactory = (MenuItemCheckIconFactory) UIManager.get(prefix + ".checkIconFactory"); - if (iconFactory != null && useCheckAndArrow() + if (iconFactory != null + && MenuItemLayoutHelper.useCheckAndArrow(menuItem) && iconFactory.isCompatible(checkIcon, prefix)) { checkIcon = iconFactory.getIcon(menuItem); } @@ -256,20 +235,7 @@ public class BasicMenuItemUI extends MenuItemUI uninstallComponents(menuItem); uninstallListeners(); uninstallKeyboardActions(); - - - // Remove values from the parent's Client Properties. - JComponent p = getMenuItemParent(menuItem); - if(p != null) { - p.putClientProperty(BasicMenuItemUI.MAX_ARROW_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_CHECK_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_ICON_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_LABEL_WIDTH, null ); - p.putClientProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET, null ); - } - + MenuItemLayoutHelper.clearUsedParentClientProperties(menuItem); menuItem = null; } @@ -405,19 +371,6 @@ public class BasicMenuItemUI extends MenuItemUI return d; } - // Returns parent of this component if it is not a top-level menu - // Otherwise returns null - private static JComponent getMenuItemParent(JMenuItem mi) { - Container parent = mi.getParent(); - if ((parent instanceof JComponent) && - (!(mi instanceof JMenu) || - !((JMenu)mi).isTopLevelMenu())) { - return (JComponent) parent; - } else { - return null; - } - } - protected Dimension getPreferredMenuItemSize(JComponent c, Icon checkIcon, Icon arrowIcon, @@ -447,32 +400,36 @@ public class BasicMenuItemUI extends MenuItemUI // the icon and text when user points a menu item by mouse. JMenuItem mi = (JMenuItem) c; - LayoutInfo li = getLayoutInfo(mi, checkIcon, arrowIcon, - createMaxViewRect(), defaultTextIconGap, acceleratorDelimiter, - BasicGraphicsUtils.isLeftToRight(mi), acceleratorFont, - useCheckAndArrow(), getPropertyPrefix()); + MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon, + arrowIcon, MenuItemLayoutHelper.createMaxRect(), defaultTextIconGap, + acceleratorDelimiter, BasicGraphicsUtils.isLeftToRight(mi), + mi.getFont(), acceleratorFont, + MenuItemLayoutHelper.useCheckAndArrow(menuItem), + getPropertyPrefix()); Dimension result = new Dimension(); // Calculate the result width - result.width = li.leadingGap; - addWidth(li.maxCheckWidth, li.afterCheckIconGap, result); + result.width = lh.getLeadingGap(); + MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(), + lh.getAfterCheckIconGap(), result); // Take into account mimimal text offset. - if ((!li.isTopLevelMenu) - && (li.minTextOffset > 0) - && (result.width < li.minTextOffset)) { - result.width = li.minTextOffset; + if ((!lh.isTopLevelMenu()) + && (lh.getMinTextOffset() > 0) + && (result.width < lh.getMinTextOffset())) { + result.width = lh.getMinTextOffset(); } - addWidth(li.maxLabelWidth, li.gap, result); - addWidth(li.maxAccWidth, li.gap, result); - addWidth(li.maxArrowWidth, li.gap, result); + MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), lh.getGap(), result); + MenuItemLayoutHelper.addMaxWidth(lh.getAccSize(), lh.getGap(), result); + MenuItemLayoutHelper.addMaxWidth(lh.getArrowSize(), lh.getGap(), result); // Calculate the result height - result.height = max(li.checkRect.height, li.labelRect.height, - li.accRect.height, li.arrowRect.height); + result.height = MenuItemLayoutHelper.max(lh.getCheckSize().getHeight(), + lh.getLabelSize().getHeight(), lh.getAccSize().getHeight(), + lh.getArrowSize().getHeight()); // Take into account menu item insets - Insets insets = li.mi.getInsets(); + Insets insets = lh.getMenuItem().getInsets(); if(insets != null) { result.width += insets.left + insets.right; result.height += insets.top + insets.bottom; @@ -492,500 +449,9 @@ public class BasicMenuItemUI extends MenuItemUI result.height++; } - li.clear(); return result; } - private Rectangle createMaxViewRect() { - return new Rectangle(0,0,Short.MAX_VALUE, Short.MAX_VALUE); - } - - private void addWidth(int width, int gap, Dimension result) { - if (width > 0) { - result.width += width + gap; - } - } - - private static int max(int... values) { - int maxValue = Integer.MIN_VALUE; - for (int i : values) { - if (i > maxValue) { - maxValue = i; - } - } - return maxValue; - } - - // LayoutInfo helps to calculate preferred size and to paint a menu item - private static class LayoutInfo { - JMenuItem mi; - JComponent miParent; - - FontMetrics fm; - FontMetrics accFm; - - Icon icon; - Icon checkIcon; - Icon arrowIcon; - String text; - String accText; - - boolean isColumnLayout; - boolean useCheckAndArrow; - boolean isLeftToRight; - boolean isTopLevelMenu; - View htmlView; - - int verticalAlignment; - int horizontalAlignment; - int verticalTextPosition; - int horizontalTextPosition; - int gap; - int leadingGap; - int afterCheckIconGap; - int minTextOffset; - - Rectangle viewRect; - Rectangle iconRect; - Rectangle textRect; - Rectangle accRect; - Rectangle checkRect; - Rectangle arrowRect; - Rectangle labelRect; - - int origIconWidth; - int origTextWidth; - int origAccWidth; - int origCheckWidth; - int origArrowWidth; - - int maxIconWidth; - int maxTextWidth; - int maxAccWidth; - int maxCheckWidth; - int maxArrowWidth; - int maxLabelWidth; - - // Empty constructor helps to create "final" LayoutInfo object - public LayoutInfo() { - } - - public LayoutInfo(JMenuItem mi, Icon checkIcon, Icon arrowIcon, - Rectangle viewRect, int gap, String accDelimiter, - boolean isLeftToRight, Font acceleratorFont, - boolean useCheckAndArrow, String propertyPrefix) { - reset(mi, checkIcon, arrowIcon, viewRect, gap, accDelimiter, - isLeftToRight, acceleratorFont, useCheckAndArrow, - propertyPrefix); - } - - // Allows to reuse a LayoutInfo object - public void reset(JMenuItem mi, Icon checkIcon, Icon arrowIcon, - Rectangle viewRect, int gap, String accDelimiter, - boolean isLeftToRight, Font acceleratorFont, - boolean useCheckAndArrow, String propertyPrefix) { - this.mi = mi; - this.miParent = getMenuItemParent(mi); - this.accText = getAccText(accDelimiter); - this.verticalAlignment = mi.getVerticalAlignment(); - this.horizontalAlignment = mi.getHorizontalAlignment(); - this.verticalTextPosition = mi.getVerticalTextPosition(); - this.horizontalTextPosition = mi.getHorizontalTextPosition(); - this.useCheckAndArrow = useCheckAndArrow; - this.fm = mi.getFontMetrics(mi.getFont()); - this.accFm = mi.getFontMetrics(acceleratorFont); - this.isLeftToRight = isLeftToRight; - this.isColumnLayout = isColumnLayout(); - this.isTopLevelMenu = (this.miParent == null)? true : false; - this.checkIcon = checkIcon; - this.icon = getIcon(propertyPrefix); - this.arrowIcon = arrowIcon; - this.text = mi.getText(); - this.gap = gap; - this.afterCheckIconGap = getAfterCheckIconGap(propertyPrefix); - this.minTextOffset = getMinTextOffset(propertyPrefix); - this.htmlView = (View) mi.getClientProperty(BasicHTML.propertyKey); - - this.viewRect = viewRect; - this.iconRect = new Rectangle(); - this.textRect = new Rectangle(); - this.accRect = new Rectangle(); - this.checkRect = new Rectangle(); - this.arrowRect = new Rectangle(); - this.labelRect = new Rectangle(); - - calcWidthsAndHeights(); - this.origIconWidth = iconRect.width; - this.origTextWidth = textRect.width; - this.origAccWidth = accRect.width; - this.origCheckWidth = checkRect.width; - this.origArrowWidth = arrowRect.width; - - calcMaxWidths(); - this.leadingGap = getLeadingGap(propertyPrefix); - calcMaxTextOffset(); - } - - // Clears fields to remove all links to other objects - // to prevent memory leaks - public void clear() { - mi = null; - miParent = null; - fm = null; - accFm = null; - icon = null; - checkIcon = null; - arrowIcon = null; - text = null; - accText = null; - htmlView = null; - viewRect = null; - iconRect = null; - textRect = null; - accRect = null; - checkRect = null; - arrowRect = null; - labelRect = null; - } - - private String getAccText(String acceleratorDelimiter) { - String accText = ""; - KeyStroke accelerator = mi.getAccelerator(); - if (accelerator != null) { - int modifiers = accelerator.getModifiers(); - if (modifiers > 0) { - accText = KeyEvent.getKeyModifiersText(modifiers); - accText += acceleratorDelimiter; - } - int keyCode = accelerator.getKeyCode(); - if (keyCode != 0) { - accText += KeyEvent.getKeyText(keyCode); - } else { - accText += accelerator.getKeyChar(); - } - } - return accText; - } - - // In case of column layout, .checkIconFactory is defined for this UI, - // the icon is compatible with it and useCheckAndArrow() is true, - // then the icon is handled by the checkIcon. - private Icon getIcon(String propertyPrefix) { - Icon icon = null; - MenuItemCheckIconFactory iconFactory = - (MenuItemCheckIconFactory) UIManager.get(propertyPrefix - + ".checkIconFactory"); - if (!isColumnLayout || !useCheckAndArrow || iconFactory == null - || !iconFactory.isCompatible(checkIcon, propertyPrefix)) { - icon = mi.getIcon(); - } - return icon; - } - - private int getMinTextOffset(String propertyPrefix) { - int minimumTextOffset = 0; - Object minimumTextOffsetObject = - UIManager.get(propertyPrefix + ".minimumTextOffset"); - if (minimumTextOffsetObject instanceof Integer) { - minimumTextOffset = (Integer) minimumTextOffsetObject; - } - return minimumTextOffset; - } - - private int getAfterCheckIconGap(String propertyPrefix) { - int afterCheckIconGap = gap; - Object afterCheckIconGapObject = - UIManager.get(propertyPrefix + ".afterCheckIconGap"); - if (afterCheckIconGapObject instanceof Integer) { - afterCheckIconGap = (Integer) afterCheckIconGapObject; - } - return afterCheckIconGap; - } - - private int getLeadingGap(String propertyPrefix) { - if (maxCheckWidth > 0) { - return getCheckOffset(propertyPrefix); - } else { - return gap; // There is no any check icon - } - } - - private int getCheckOffset(String propertyPrefix) { - int checkIconOffset = gap; - Object checkIconOffsetObject = - UIManager.get(propertyPrefix + ".checkIconOffset"); - if (checkIconOffsetObject instanceof Integer) { - checkIconOffset = (Integer) checkIconOffsetObject; - } - return checkIconOffset; - } - - private void calcWidthsAndHeights() - { - // iconRect - if (icon != null) { - iconRect.width = icon.getIconWidth(); - iconRect.height = icon.getIconHeight(); - } - - // accRect - if (!accText.equals("")) { - accRect.width = SwingUtilities2.stringWidth( - mi, accFm, accText); - accRect.height = accFm.getHeight(); - } - - // textRect - if (text == null) { - text = ""; - } else if (!text.equals("")) { - if (htmlView != null) { - // Text is HTML - textRect.width = - (int) htmlView.getPreferredSpan(View.X_AXIS); - textRect.height = - (int) htmlView.getPreferredSpan(View.Y_AXIS); - } else { - // Text isn't HTML - textRect.width = - SwingUtilities2.stringWidth(mi, fm, text); - textRect.height = fm.getHeight(); - } - } - - if (useCheckAndArrow) { - // checkIcon - if (checkIcon != null) { - checkRect.width = checkIcon.getIconWidth(); - checkRect.height = checkIcon.getIconHeight(); - } - // arrowRect - if (arrowIcon != null) { - arrowRect.width = arrowIcon.getIconWidth(); - arrowRect.height = arrowIcon.getIconHeight(); - } - } - - // labelRect - if (isColumnLayout) { - labelRect.width = iconRect.width + textRect.width + gap; - labelRect.height = max(checkRect.height, iconRect.height, - textRect.height, accRect.height, arrowRect.height); - } else { - textRect = new Rectangle(); - iconRect = new Rectangle(); - SwingUtilities.layoutCompoundLabel(mi, fm, text, icon, - verticalAlignment, horizontalAlignment, - verticalTextPosition, horizontalTextPosition, - viewRect, iconRect, textRect, gap); - labelRect = iconRect.union(textRect); - } - } - - private void calcMaxWidths() { - maxCheckWidth = calcMaxValue(BasicMenuItemUI.MAX_CHECK_WIDTH, - checkRect.width); - maxArrowWidth = calcMaxValue(BasicMenuItemUI.MAX_ARROW_WIDTH, - arrowRect.width); - maxAccWidth = calcMaxValue(BasicMenuItemUI.MAX_ACC_WIDTH, - accRect.width); - - if (isColumnLayout) { - maxIconWidth = calcMaxValue(BasicMenuItemUI.MAX_ICON_WIDTH, - iconRect.width); - maxTextWidth = calcMaxValue(BasicMenuItemUI.MAX_TEXT_WIDTH, - textRect.width); - int curGap = gap; - if ((maxIconWidth == 0) || (maxTextWidth == 0)) { - curGap = 0; - } - maxLabelWidth = - calcMaxValue(BasicMenuItemUI.MAX_LABEL_WIDTH, - maxIconWidth + maxTextWidth + curGap); - } else { - // We shouldn't use current icon and text widths - // in maximal widths calculation for complex layout. - maxIconWidth = getParentIntProperty(BasicMenuItemUI.MAX_ICON_WIDTH); - maxLabelWidth = calcMaxValue(BasicMenuItemUI.MAX_LABEL_WIDTH, - labelRect.width); - // If maxLabelWidth is wider - // than the widest icon + the widest text + gap, - // we should update the maximal text witdh - int candidateTextWidth = maxLabelWidth - maxIconWidth; - if (maxIconWidth > 0) { - candidateTextWidth -= gap; - } - maxTextWidth = calcMaxValue(BasicMenuItemUI.MAX_TEXT_WIDTH, - candidateTextWidth); - } - } - - // Calculates and returns maximal value - // through specified parent component client property. - private int calcMaxValue(Object propertyName, int value) { - // Get maximal value from parent client property - int maxValue = getParentIntProperty(propertyName); - // Store new maximal width in parent client property - if (value > maxValue) { - if (miParent != null) { - miParent.putClientProperty(propertyName, value); - } - return value; - } else { - return maxValue; - } - } - - // Returns parent client property as int - private int getParentIntProperty(Object propertyName) { - Object value = null; - if (miParent != null) { - value = miParent.getClientProperty(propertyName); - } - if ((value == null) || !(value instanceof Integer)){ - value = 0; - } - return (Integer)value; - } - - private boolean isColumnLayout() { - return isColumnLayout(isLeftToRight, horizontalAlignment, - horizontalTextPosition, verticalTextPosition); - } - - public static boolean isColumnLayout(boolean isLeftToRight, - JMenuItem mi) { - assert(mi != null); - return isColumnLayout(isLeftToRight, mi.getHorizontalAlignment(), - mi.getHorizontalTextPosition(), mi.getVerticalTextPosition()); - } - - // Answers should we do column layout for a menu item or not. - // We do it when a user doesn't set any alignments - // and text positions manually, except the vertical alignment. - public static boolean isColumnLayout( boolean isLeftToRight, - int horizontalAlignment, int horizontalTextPosition, - int verticalTextPosition) { - if (verticalTextPosition != SwingConstants.CENTER) { - return false; - } - if (isLeftToRight) { - if (horizontalAlignment != SwingConstants.LEADING - && horizontalAlignment != SwingConstants.LEFT) { - return false; - } - if (horizontalTextPosition != SwingConstants.TRAILING - && horizontalTextPosition != SwingConstants.RIGHT) { - return false; - } - } else { - if (horizontalAlignment != SwingConstants.LEADING - && horizontalAlignment != SwingConstants.RIGHT) { - return false; - } - if (horizontalTextPosition != SwingConstants.TRAILING - && horizontalTextPosition != SwingConstants.LEFT) { - return false; - } - } - return true; - } - - // Calculates maximal text offset. - // It is required for some L&Fs (ex: Vista L&F). - // The offset is meaningful only for L2R column layout. - private void calcMaxTextOffset() { - if (!isColumnLayout || !isLeftToRight) { - return; - } - - // Calculate the current text offset - int offset = viewRect.x + leadingGap + maxCheckWidth - + afterCheckIconGap + maxIconWidth + gap; - if (maxCheckWidth == 0) { - offset -= afterCheckIconGap; - } - if (maxIconWidth == 0) { - offset -= gap; - } - - // maximal text offset shouldn't be less than minimal text offset; - if (offset < minTextOffset) { - offset = minTextOffset; - } - - // Calculate and store the maximal text offset - calcMaxValue(BASICMENUITEMUI_MAX_TEXT_OFFSET, offset); - } - - public String toString() { - StringBuilder result = new StringBuilder(); - result.append(super.toString()).append("\n"); - result.append("accFm = ").append(accFm).append("\n"); - result.append("accRect = ").append(accRect).append("\n"); - result.append("accText = ").append(accText).append("\n"); - result.append("afterCheckIconGap = ").append(afterCheckIconGap) - .append("\n"); - result.append("arrowIcon = ").append(arrowIcon).append("\n"); - result.append("arrowRect = ").append(arrowRect).append("\n"); - result.append("checkIcon = ").append(checkIcon).append("\n"); - result.append("checkRect = ").append(checkRect).append("\n"); - result.append("fm = ").append(fm).append("\n"); - result.append("gap = ").append(gap).append("\n"); - result.append("horizontalAlignment = ").append(horizontalAlignment) - .append("\n"); - result.append("horizontalTextPosition = ") - .append(horizontalTextPosition).append("\n"); - result.append("htmlView = ").append(htmlView).append("\n"); - result.append("icon = ").append(icon).append("\n"); - result.append("iconRect = ").append(iconRect).append("\n"); - result.append("isColumnLayout = ").append(isColumnLayout).append("\n"); - result.append("isLeftToRight = ").append(isLeftToRight).append("\n"); - result.append("isTopLevelMenu = ").append(isTopLevelMenu).append("\n"); - result.append("labelRect = ").append(labelRect).append("\n"); - result.append("leadingGap = ").append(leadingGap).append("\n"); - result.append("maxAccWidth = ").append(maxAccWidth).append("\n"); - result.append("maxArrowWidth = ").append(maxArrowWidth).append("\n"); - result.append("maxCheckWidth = ").append(maxCheckWidth).append("\n"); - result.append("maxIconWidth = ").append(maxIconWidth).append("\n"); - result.append("maxLabelWidth = ").append(maxLabelWidth).append("\n"); - result.append("maxTextWidth = ").append(maxTextWidth).append("\n"); - result.append("maxTextOffset = ") - .append(getParentIntProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET)) - .append("\n"); - result.append("mi = ").append(mi).append("\n"); - result.append("minTextOffset = ").append(minTextOffset).append("\n"); - result.append("miParent = ").append(miParent).append("\n"); - result.append("origAccWidth = ").append(origAccWidth).append("\n"); - result.append("origArrowWidth = ").append(origArrowWidth).append("\n"); - result.append("origCheckWidth = ").append(origCheckWidth).append("\n"); - result.append("origIconWidth = ").append(origIconWidth).append("\n"); - result.append("origTextWidth = ").append(origTextWidth).append("\n"); - result.append("text = ").append(text).append("\n"); - result.append("textRect = ").append(textRect).append("\n"); - result.append("useCheckAndArrow = ").append(useCheckAndArrow) - .append("\n"); - result.append("verticalAlignment = ").append(verticalAlignment) - .append("\n"); - result.append("verticalTextPosition = ") - .append(verticalTextPosition).append("\n"); - result.append("viewRect = ").append(viewRect).append("\n"); - return result.toString(); - } - } // End of LayoutInfo - - // Reuses layoutInfo object to reduce the amount of produced garbage - private LayoutInfo getLayoutInfo(JMenuItem mi, Icon checkIcon, Icon arrowIcon, - Rectangle viewRect, int gap, String accDelimiter, - boolean isLeftToRight, Font acceleratorFont, - boolean useCheckAndArrow, String propertyPrefix) { - // layoutInfo is final and always not null - layoutInfo.reset(mi, checkIcon, arrowIcon, viewRect, - gap, accDelimiter, isLeftToRight, acceleratorFont, - useCheckAndArrow, propertyPrefix); - return layoutInfo; - } - /** * We draw the background in paintMenuItem() * so override update (which fills the background of opaque @@ -1016,122 +482,132 @@ public class BasicMenuItemUI extends MenuItemUI Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight()); applyInsets(viewRect, mi.getInsets()); - LayoutInfo li = getLayoutInfo(mi, checkIcon, arrowIcon, - viewRect, defaultTextIconGap, acceleratorDelimiter, - BasicGraphicsUtils.isLeftToRight(mi), acceleratorFont, - useCheckAndArrow(), getPropertyPrefix()); - layoutMenuItem(li); + MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon, + arrowIcon, viewRect, defaultTextIconGap, acceleratorDelimiter, + BasicGraphicsUtils.isLeftToRight(mi), mi.getFont(), + acceleratorFont, MenuItemLayoutHelper.useCheckAndArrow(menuItem), + getPropertyPrefix()); + MenuItemLayoutHelper.LayoutResult lr = lh.layoutMenuItem(); paintBackground(g, mi, background); - paintCheckIcon(g, li, holdc, foreground); - paintIcon(g, li, holdc); - paintText(g, li); - paintAccText(g, li); - paintArrowIcon(g, li, foreground); + paintCheckIcon(g, lh, lr, holdc, foreground); + paintIcon(g, lh, lr, holdc); + paintText(g, lh, lr); + paintAccText(g, lh, lr); + paintArrowIcon(g, lh, lr, foreground); // Restore original graphics font and color g.setColor(holdc); g.setFont(holdf); - - li.clear(); } - private void paintIcon(Graphics g, LayoutInfo li, Color holdc) { - if (li.icon != null) { + private void paintIcon(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr, Color holdc) { + if (lh.getIcon() != null) { Icon icon; - ButtonModel model = li.mi.getModel(); + ButtonModel model = lh.getMenuItem().getModel(); if (!model.isEnabled()) { - icon = li.mi.getDisabledIcon(); + icon = lh.getMenuItem().getDisabledIcon(); } else if (model.isPressed() && model.isArmed()) { - icon = li.mi.getPressedIcon(); + icon = lh.getMenuItem().getPressedIcon(); if (icon == null) { // Use default icon - icon = li.mi.getIcon(); + icon = lh.getMenuItem().getIcon(); } } else { - icon = li.mi.getIcon(); + icon = lh.getMenuItem().getIcon(); } if (icon != null) { - icon.paintIcon(li.mi, g, li.iconRect.x, li.iconRect.y); + icon.paintIcon(lh.getMenuItem(), g, lr.getIconRect().x, + lr.getIconRect().y); g.setColor(holdc); } } } - private void paintCheckIcon(Graphics g, LayoutInfo li, + private void paintCheckIcon(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr, Color holdc, Color foreground) { - if (li.checkIcon != null) { - ButtonModel model = li.mi.getModel(); - if (model.isArmed() - || (li.mi instanceof JMenu && model.isSelected())) { + if (lh.getCheckIcon() != null) { + ButtonModel model = lh.getMenuItem().getModel(); + if (model.isArmed() || (lh.getMenuItem() instanceof JMenu + && model.isSelected())) { g.setColor(foreground); } else { g.setColor(holdc); } - if (li.useCheckAndArrow) { - li.checkIcon.paintIcon(li.mi, g, li.checkRect.x, - li.checkRect.y); + if (lh.useCheckAndArrow()) { + lh.getCheckIcon().paintIcon(lh.getMenuItem(), g, + lr.getCheckRect().x, lr.getCheckRect().y); } g.setColor(holdc); } } - private void paintAccText(Graphics g, LayoutInfo li) { - if (!li.accText.equals("")) { - ButtonModel model = li.mi.getModel(); - g.setFont(acceleratorFont); + private void paintAccText(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (!lh.getAccText().equals("")) { + ButtonModel model = lh.getMenuItem().getModel(); + g.setFont(lh.getAccFontMetrics().getFont()); if (!model.isEnabled()) { // *** paint the accText disabled if (disabledForeground != null) { g.setColor(disabledForeground); - SwingUtilities2.drawString(li.mi, g, li.accText, - li.accRect.x, - li.accRect.y + li.accFm.getAscent()); + SwingUtilities2.drawString(lh.getMenuItem(), g, + lh.getAccText(), lr.getAccRect().x, + lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); } else { - g.setColor(li.mi.getBackground().brighter()); - SwingUtilities2.drawString(li.mi, g, li.accText, li.accRect.x, - li.accRect.y + li.accFm.getAscent()); - g.setColor(li.mi.getBackground().darker()); - SwingUtilities2.drawString(li.mi, g, li.accText, - li.accRect.x - 1, - li.accRect.y + li.accFm.getAscent() - 1); + g.setColor(lh.getMenuItem().getBackground().brighter()); + SwingUtilities2.drawString(lh.getMenuItem(), g, + lh.getAccText(), lr.getAccRect().x, + lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); + g.setColor(lh.getMenuItem().getBackground().darker()); + SwingUtilities2.drawString(lh.getMenuItem(), g, + lh.getAccText(), lr.getAccRect().x - 1, + lr.getAccRect().y + lh.getFontMetrics().getAscent() - 1); } } else { // *** paint the accText normally - if (model.isArmed() || - (li.mi instanceof JMenu && model.isSelected())) { + if (model.isArmed() + || (lh.getMenuItem() instanceof JMenu + && model.isSelected())) { g.setColor(acceleratorSelectionForeground); } else { g.setColor(acceleratorForeground); } - SwingUtilities2.drawString(li.mi, g, li.accText, li.accRect.x, - li.accRect.y + li.accFm.getAscent()); + SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), + lr.getAccRect().x, lr.getAccRect().y + + lh.getAccFontMetrics().getAscent()); } } } - private void paintText(Graphics g, LayoutInfo li) { - if (!li.text.equals("")) { - if (li.htmlView != null) { + private void paintText(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (!lh.getText().equals("")) { + if (lh.getHtmlView() != null) { // Text is HTML - li.htmlView.paint(g, li.textRect); + lh.getHtmlView().paint(g, lr.getTextRect()); } else { // Text isn't HTML - paintText(g, li.mi, li.textRect, li.text); + paintText(g, lh.getMenuItem(), lr.getTextRect(), lh.getText()); } } } - private void paintArrowIcon(Graphics g, LayoutInfo li, Color foreground) { - if (li.arrowIcon != null) { - ButtonModel model = li.mi.getModel(); - if (model.isArmed() - || (li.mi instanceof JMenu && model.isSelected())) { + private void paintArrowIcon(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr, + Color foreground) { + if (lh.getArrowIcon() != null) { + ButtonModel model = lh.getMenuItem().getModel(); + if (model.isArmed() || (lh.getMenuItem() instanceof JMenu + && model.isSelected())) { g.setColor(foreground); } - if (li.useCheckAndArrow) { - li.arrowIcon.paintIcon(li.mi, g, li.arrowRect.x, li.arrowRect.y); + if (lh.useCheckAndArrow()) { + lh.getArrowIcon().paintIcon(lh.getMenuItem(), g, + lr.getArrowRect().x, lr.getArrowRect().y); } } } @@ -1216,346 +692,6 @@ public class BasicMenuItemUI extends MenuItemUI } } - - /** - * Layout icon, text, check icon, accelerator text and arrow icon - * in the viewRect and return their positions. - * - * If horizontalAlignment, verticalTextPosition and horizontalTextPosition - * are default (user doesn't set any manually) the layouting algorithm is: - * Elements are layouted in the five columns: - * check icon + icon + text + accelerator text + arrow icon - * - * In the other case elements are layouted in the four columns: - * check icon + label + accelerator text + arrow icon - * Label is icon and text rectangles union. - * - * The order of columns can be reversed. - * It depends on the menu item orientation. - */ - private void layoutMenuItem(LayoutInfo li) - { - li.checkRect.width = li.maxCheckWidth; - li.accRect.width = li.maxAccWidth; - li.arrowRect.width = li.maxArrowWidth; - - if (li.isColumnLayout) { - if (li.isLeftToRight) { - doLTRColumnLayout(li); - } else { - doRTLColumnLayout(li); - } - } else { - if (li.isLeftToRight) { - doLTRComplexLayout(li); - } else { - doRTLComplexLayout(li); - } - } - - alignAccCheckAndArrowVertically(li); - } - - // Aligns the accelertor text and the check and arrow icons vertically - // with the center of the label rect. - private void alignAccCheckAndArrowVertically(LayoutInfo li) { - li.accRect.y = (int)(li.labelRect.y + (float)li.labelRect.height/2 - - (float)li.accRect.height/2); - fixVerticalAlignment(li, li.accRect); - if (li.useCheckAndArrow) { - li.arrowRect.y = (int)(li.labelRect.y + (float)li.labelRect.height/2 - - (float)li.arrowRect.height/2); - li.checkRect.y = (int)(li.labelRect.y + (float)li.labelRect.height/2 - - (float)li.checkRect.height/2); - fixVerticalAlignment(li, li.arrowRect); - fixVerticalAlignment(li, li.checkRect); - } - } - - // Fixes vertical alignment of all menu item elements if a rect.y - // or (rect.y + rect.height) is out of viewRect bounds - private void fixVerticalAlignment(LayoutInfo li, Rectangle r) { - int delta = 0; - if (r.y < li.viewRect.y) { - delta = li.viewRect.y - r.y; - } else if (r.y + r.height > li.viewRect.y + li.viewRect.height) { - delta = li.viewRect.y + li.viewRect.height - r.y - r.height; - } - if (delta != 0) { - li.checkRect.y += delta; - li.iconRect.y += delta; - li.textRect.y += delta; - li.accRect.y += delta; - li.arrowRect.y += delta; - } - } - - private void doLTRColumnLayout(LayoutInfo li) { - // Set maximal width for all the five basic rects - // (three other ones are already maximal) - li.iconRect.width = li.maxIconWidth; - li.textRect.width = li.maxTextWidth; - - // Set X coordinates - // All rects will be aligned at the left side - calcXPositionsL2R(li.viewRect.x, li.leadingGap, li.gap, li.checkRect, - li.iconRect, li.textRect); - - // Tune afterCheckIconGap - if (li.checkRect.width > 0) { // there is the afterCheckIconGap - li.iconRect.x += li.afterCheckIconGap - li.gap; - li.textRect.x += li.afterCheckIconGap - li.gap; - } - - calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.gap, - li.arrowRect, li.accRect); - - // Take into account minimal text offset - int textOffset = li.textRect.x - li.viewRect.x; - if (!li.isTopLevelMenu && (textOffset < li.minTextOffset)) { - li.textRect.x += li.minTextOffset - textOffset; - } - - // Take into account the left side bearings for text and accelerator text. - fixTextRects(li); - - // Set Y coordinate for text and icon. - // Y coordinates for other rects - // will be calculated later in layoutMenuItem. - calcTextAndIconYPositions(li); - - // Calculate valid X and Y coordinates for labelRect - li.labelRect = li.textRect.union(li.iconRect); - } - - private void doLTRComplexLayout(LayoutInfo li) { - li.labelRect.width = li.maxLabelWidth; - - // Set X coordinates - calcXPositionsL2R(li.viewRect.x, li.leadingGap, li.gap, li.checkRect, - li.labelRect); - - // Tune afterCheckIconGap - if (li.checkRect.width > 0) { // there is the afterCheckIconGap - li.labelRect.x += li.afterCheckIconGap - li.gap; - } - - calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.gap, - li.arrowRect, li.accRect); - - // Take into account minimal text offset - int labelOffset = li.labelRect.x - li.viewRect.x; - if (!li.isTopLevelMenu && (labelOffset < li.minTextOffset)) { - li.labelRect.x += li.minTextOffset - labelOffset; - } - - // Take into account the left side bearing for accelerator text. - // The LSB for text is taken into account in layoutCompoundLabel() below. - fixAccTextRect(li); - - // Layout icon and text with SwingUtilities.layoutCompoundLabel() - // within the labelRect - li.textRect = new Rectangle(); - li.iconRect = new Rectangle(); - SwingUtilities.layoutCompoundLabel( - li.mi, li.fm, li.text, li.icon, li.verticalAlignment, - li.horizontalAlignment, li.verticalTextPosition, - li.horizontalTextPosition, li.labelRect, - li.iconRect, li.textRect, li.gap); - } - - private void doRTLColumnLayout(LayoutInfo li) { - // Set maximal width for all the five basic rects - // (three other ones are already maximal) - li.iconRect.width = li.maxIconWidth; - li.textRect.width = li.maxTextWidth; - - // Set X coordinates - calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.leadingGap, - li.gap, li.checkRect, li.iconRect, li.textRect); - - // Tune the gap after check icon - if (li.checkRect.width > 0) { // there is the gap after check icon - li.iconRect.x -= li.afterCheckIconGap - li.gap; - li.textRect.x -= li.afterCheckIconGap - li.gap; - } - - calcXPositionsL2R(li.viewRect.x, li.gap, li.arrowRect, - li.accRect); - - // Take into account minimal text offset - int textOffset = (li.viewRect.x + li.viewRect.width) - - (li.textRect.x + li.textRect.width); - if (!li.isTopLevelMenu && (textOffset < li.minTextOffset)) { - li.textRect.x -= li.minTextOffset - textOffset; - } - - // Align icon, text, accelerator text, check icon and arrow icon - // at the right side - rightAlignAllRects(li); - - // Take into account the left side bearings for text and accelerator text. - fixTextRects(li); - - // Set Y coordinates for text and icon. - // Y coordinates for other rects - // will be calculated later in layoutMenuItem. - calcTextAndIconYPositions(li); - - // Calculate valid X and Y coordinate for labelRect - li.labelRect = li.textRect.union(li.iconRect); - } - - private void doRTLComplexLayout(LayoutInfo li) { - li.labelRect.width = li.maxLabelWidth; - - // Set X coordinates - calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.leadingGap, - li.gap, li.checkRect, li.labelRect); - - // Tune the gap after check icon - if (li.checkRect.width > 0) { // there is the gap after check icon - li.labelRect.x -= li.afterCheckIconGap - li.gap; - } - - calcXPositionsL2R(li.viewRect.x, li.gap, li.arrowRect, - li.accRect); - - // Take into account minimal text offset - int labelOffset = (li.viewRect.x + li.viewRect.width) - - (li.labelRect.x + li.labelRect.width); - if (!li.isTopLevelMenu && (labelOffset < li.minTextOffset)) { - li.labelRect.x -= li.minTextOffset - labelOffset; - } - - // Align icon, text, accelerator text, check icon and arrow icon - // at the right side - rightAlignAllRects(li); - - // Take into account the left side bearing for accelerator text. - // The LSB for text is taken into account in layoutCompoundLabel() below. - fixAccTextRect(li); - - // Layout icon and text with SwingUtilities.layoutCompoundLabel() - // within the labelRect - li.textRect = new Rectangle(); - li.iconRect = new Rectangle(); - SwingUtilities.layoutCompoundLabel( - menuItem, li.fm, li.text, li.icon, li.verticalAlignment, - li.horizontalAlignment, li.verticalTextPosition, - li.horizontalTextPosition, li.labelRect, - li.iconRect, li.textRect, li.gap); - } - - private void calcXPositionsL2R(int startXPos, int leadingGap, - int gap, Rectangle... rects) { - int curXPos = startXPos + leadingGap; - for (Rectangle rect : rects) { - rect.x = curXPos; - if (rect.width > 0) { - curXPos += rect.width + gap; - } - } - } - - private void calcXPositionsL2R(int startXPos, int gap, Rectangle... rects) { - calcXPositionsL2R(startXPos, gap, gap, rects); - } - - private void calcXPositionsR2L(int startXPos, int leadingGap, - int gap, Rectangle... rects) { - int curXPos = startXPos - leadingGap; - for (Rectangle rect : rects) { - rect.x = curXPos - rect.width; - if (rect.width > 0) { - curXPos -= rect.width + gap; - } - } - } - - private void calcXPositionsR2L(int startXPos, int gap, Rectangle... rects) { - calcXPositionsR2L(startXPos, gap, gap, rects); - } - - // Takes into account the left side bearings for text and accelerator text - private void fixTextRects(LayoutInfo li) { - if (li.htmlView == null) { // The text isn't a HTML - int lsb = SwingUtilities2.getLeftSideBearing(li.mi, li.fm, li.text); - if (lsb < 0) { - li.textRect.x -= lsb; - } - } - fixAccTextRect(li); - } - - // Takes into account the left side bearing for accelerator text - private void fixAccTextRect(LayoutInfo li) { - int lsb = SwingUtilities2 - .getLeftSideBearing(li.mi, li.accFm, li.accText); - if (lsb < 0) { - li.accRect.x -= lsb; - } - } - - // Sets Y coordinates of text and icon - // taking into account the vertical alignment - private void calcTextAndIconYPositions(LayoutInfo li) { - if (li.verticalAlignment == SwingUtilities.TOP) { - li.textRect.y = (int)(li.viewRect.y - + (float)li.labelRect.height/2 - - (float)li.textRect.height/2); - li.iconRect.y = (int)(li.viewRect.y - + (float)li.labelRect.height/2 - - (float)li.iconRect.height/2); - } else if (li.verticalAlignment == SwingUtilities.CENTER) { - li.textRect.y = (int)(li.viewRect.y - + (float)li.viewRect.height/2 - - (float)li.textRect.height/2); - li.iconRect.y = (int)(li.viewRect.y - + (float)li.viewRect.height/2 - - (float)li.iconRect.height/2); - } - else if (li.verticalAlignment == SwingUtilities.BOTTOM) { - li.textRect.y = (int)(li.viewRect.y + li.viewRect.height - - (float)li.labelRect.height/2 - - (float)li.textRect.height/2); - li.iconRect.y = (int)(li.viewRect.y + li.viewRect.height - - (float)li.labelRect.height/2 - - (float)li.iconRect.height/2); - } - } - - // Aligns icon, text, accelerator text, check icon and arrow icon - // at the right side - private void rightAlignAllRects(LayoutInfo li) { - li.iconRect.x = li.iconRect.x + li.iconRect.width - li.origIconWidth; - li.iconRect.width = li.origIconWidth; - li.textRect.x = li.textRect.x + li.textRect.width - li.origTextWidth; - li.textRect.width = li.origTextWidth; - li.accRect.x = li.accRect.x + li.accRect.width - - li.origAccWidth; - li.accRect.width = li.origAccWidth; - li.checkRect.x = li.checkRect.x + li.checkRect.width - - li.origCheckWidth; - li.checkRect.width = li.origCheckWidth; - li.arrowRect.x = li.arrowRect.x + li.arrowRect.width - - li.origArrowWidth; - li.arrowRect.width = li.origArrowWidth; - } - - /* - * Returns false if the component is a JMenu and it is a top - * level menu (on the menubar). - */ - private boolean useCheckAndArrow(){ - boolean b = true; - if((menuItem instanceof JMenu) && - (((JMenu)menuItem).isTopLevelMenu())) { - b = false; - } - return b; - } - public MenuElement[] getPath() { MenuSelectionManager m = MenuSelectionManager.defaultManager(); MenuElement oldPath[] = m.getSelectedPath(); diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/DefaultMenuLayout.java b/jdk/src/share/classes/javax/swing/plaf/basic/DefaultMenuLayout.java index b29cfaf7aa6..5acae97eded 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/DefaultMenuLayout.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/DefaultMenuLayout.java @@ -1,5 +1,5 @@ /* - * Copyright 1998-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import javax.swing.plaf.UIResource; import java.awt.Container; import java.awt.Dimension; -import static sun.swing.SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET; /** * The default layout manager for Popup menus and menubars. This @@ -49,18 +48,7 @@ public class DefaultMenuLayout extends BoxLayout implements UIResource { public Dimension preferredLayoutSize(Container target) { if (target instanceof JPopupMenu) { JPopupMenu popupMenu = (JPopupMenu) target; - - // Before the calculation of menu preferred size - // clear the previously calculated maximal widths and offsets - // in menu's Client Properties - popupMenu.putClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_ARROW_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_CHECK_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_ICON_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_LABEL_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH, null); - popupMenu.putClientProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET, null); - + sun.swing.MenuItemLayoutHelper.clearUsedClientProperties(popupMenu); if (popupMenu.getComponentCount() == 0) { return new Dimension(0, 0); } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/DefaultMenuLayout.java b/jdk/src/share/classes/javax/swing/plaf/synth/DefaultMenuLayout.java index 678452328d9..1757a2e661a 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/DefaultMenuLayout.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/DefaultMenuLayout.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,19 +47,22 @@ class DefaultMenuLayout extends BoxLayout implements UIResource { super(target, axis); } - public void invalidateLayout(Container target) { - if (target instanceof JPopupMenu) { - SynthPopupMenuUI popupUI = (SynthPopupMenuUI)((JPopupMenu)target). - getUI(); - popupUI.resetAlignmentHints(); - } - super.invalidateLayout(target); - } - public Dimension preferredLayoutSize(Container target) { - if (target instanceof JPopupMenu && target.getComponentCount() == 0) { - return new Dimension(0, 0); + if (target instanceof JPopupMenu) { + JPopupMenu popupMenu = (JPopupMenu) target; + + popupMenu.putClientProperty( + SynthMenuItemLayoutHelper.MAX_ACC_OR_ARROW_WIDTH, null); + sun.swing.MenuItemLayoutHelper.clearUsedClientProperties(popupMenu); + + if (popupMenu.getComponentCount() == 0) { + return new Dimension(0, 0); + } } + + // Make BoxLayout recalculate cached preferred sizes + super.invalidateLayout(target); + return super.preferredLayoutSize(target); } } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java index 62c45ab64d2..a8ec7728a64 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,8 @@ package javax.swing.plaf.synth; import sun.swing.SwingUtilities2; +import sun.swing.MenuItemLayoutHelper; + import java.awt.*; import javax.swing.*; import javax.swing.plaf.basic.BasicHTML; @@ -411,6 +413,198 @@ public class SynthGraphicsUtils { } + /** + * A quick note about how preferred sizes are calculated... Generally + * speaking, SynthPopupMenuUI will run through the list of its children + * (from top to bottom) and ask each for its preferred size. Each menu + * item will add up the max width of each element (icons, text, + * accelerator spacing, accelerator text or arrow icon) encountered thus + * far, so by the time all menu items have been calculated, we will + * know the maximum (preferred) menu item size for that popup menu. + * Later when it comes time to paint each menu item, we can use those + * same accumulated max element sizes in order to layout the item. + */ + static Dimension getPreferredMenuItemSize(SynthContext context, + SynthContext accContext, JComponent c, + Icon checkIcon, Icon arrowIcon, int defaultTextIconGap, + String acceleratorDelimiter, boolean useCheckAndArrow, + String propertyPrefix) { + + JMenuItem mi = (JMenuItem) c; + SynthMenuItemLayoutHelper lh = new SynthMenuItemLayoutHelper( + context, accContext, mi, checkIcon, arrowIcon, + MenuItemLayoutHelper.createMaxRect(), defaultTextIconGap, + acceleratorDelimiter, SynthLookAndFeel.isLeftToRight(mi), + useCheckAndArrow, propertyPrefix); + + Dimension result = new Dimension(); + + // Calculate the result width + int gap = lh.getGap(); + result.width = 0; + MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(), gap, result); + MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), gap, result); + MenuItemLayoutHelper.addWidth(lh.getMaxAccOrArrowWidth(), 5 * gap, result); + // The last gap is unnecessary + result.width -= gap; + + // Calculate the result height + result.height = MenuItemLayoutHelper.max(lh.getCheckSize().getHeight(), + lh.getLabelSize().getHeight(), lh.getAccSize().getHeight(), + lh.getArrowSize().getHeight()); + + // Take into account menu item insets + Insets insets = lh.getMenuItem().getInsets(); + if (insets != null) { + result.width += insets.left + insets.right; + result.height += insets.top + insets.bottom; + } + + // if the width is even, bump it up one. This is critical + // for the focus dash lhne to draw properly + if (result.width % 2 == 0) { + result.width++; + } + + // if the height is even, bump it up one. This is critical + // for the text to center properly + if (result.height % 2 == 0) { + result.height++; + } + + return result; + } + + static void applyInsets(Rectangle rect, Insets insets) { + if (insets != null) { + rect.x += insets.left; + rect.y += insets.top; + rect.width -= (insets.right + rect.x); + rect.height -= (insets.bottom + rect.y); + } + } + + static void paint(SynthContext context, SynthContext accContext, Graphics g, + Icon checkIcon, Icon arrowIcon, String acceleratorDelimiter, + int defaultTextIconGap, String propertyPrefix) { + JMenuItem mi = (JMenuItem) context.getComponent(); + SynthStyle style = context.getStyle(); + g.setFont(style.getFont(context)); + + Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight()); + applyInsets(viewRect, mi.getInsets()); + + SynthMenuItemLayoutHelper lh = new SynthMenuItemLayoutHelper( + context, accContext, mi, checkIcon, + arrowIcon, viewRect, defaultTextIconGap, acceleratorDelimiter, + SynthLookAndFeel.isLeftToRight(mi), + MenuItemLayoutHelper.useCheckAndArrow(mi), propertyPrefix); + MenuItemLayoutHelper.LayoutResult lr = lh.layoutMenuItem(); + + paintMenuItem(g, lh, lr); + } + + static void paintMenuItem(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + // Save original graphics font and color + Font holdf = g.getFont(); + Color holdc = g.getColor(); + + paintBackground(g, lh); + paintCheckIcon(g, lh, lr); + paintIcon(g, lh, lr); + paintText(g, lh, lr); + paintAccText(g, lh, lr); + paintArrowIcon(g, lh, lr); + + // Restore original graphics font and color + g.setColor(holdc); + g.setFont(holdf); + } + + static void paintBackground(Graphics g, SynthMenuItemLayoutHelper lh) { + paintBackground(lh.getContext(), g, lh.getMenuItem()); + } + + static void paintBackground(SynthContext context, Graphics g, JComponent c) { + context.getPainter().paintMenuItemBackground(context, g, 0, 0, + c.getWidth(), c.getHeight()); + } + + static void paintIcon(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (lh.getIcon() != null) { + Icon icon; + JMenuItem mi = lh.getMenuItem(); + ButtonModel model = mi.getModel(); + if (!model.isEnabled()) { + icon = mi.getDisabledIcon(); + } else if (model.isPressed() && model.isArmed()) { + icon = mi.getPressedIcon(); + if (icon == null) { + // Use default icon + icon = mi.getIcon(); + } + } else { + icon = mi.getIcon(); + } + + if (icon != null) { + Rectangle iconRect = lr.getIconRect(); + SynthIcon.paintIcon(icon, lh.getContext(), g, iconRect.x, + iconRect.y, iconRect.width, iconRect.height); + } + } + } + + static void paintCheckIcon(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (lh.getCheckIcon() != null) { + Rectangle checkRect = lr.getCheckRect(); + SynthIcon.paintIcon(lh.getCheckIcon(), lh.getContext(), g, + checkRect.x, checkRect.y, checkRect.width, checkRect.height); + } + } + + static void paintAccText(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + String accText = lh.getAccText(); + if (accText != null && !accText.equals("")) { + g.setColor(lh.getAccStyle().getColor(lh.getAccContext(), + ColorType.TEXT_FOREGROUND)); + g.setFont(lh.getAccStyle().getFont(lh.getAccContext())); + lh.getAccGraphicsUtils().paintText(lh.getAccContext(), g, accText, + lr.getAccRect().x, lr.getAccRect().y, -1); + } + } + + static void paintText(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (!lh.getText().equals("")) { + if (lh.getHtmlView() != null) { + // Text is HTML + lh.getHtmlView().paint(g, lr.getTextRect()); + } else { + // Text isn't HTML + g.setColor(lh.getStyle().getColor( + lh.getContext(), ColorType.TEXT_FOREGROUND)); + g.setFont(lh.getStyle().getFont(lh.getContext())); + lh.getGraphicsUtils().paintText(lh.getContext(), g, lh.getText(), + lr.getTextRect().x, lr.getTextRect().y, + lh.getMenuItem().getDisplayedMnemonicIndex()); + } + } + } + + static void paintArrowIcon(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (lh.getArrowIcon() != null) { + Rectangle arrowRect = lr.getArrowRect(); + SynthIcon.paintIcon(lh.getArrowIcon(), lh.getContext(), g, + arrowRect.x, arrowRect.y, arrowRect.width, arrowRect.height); + } + } + /** * Wraps a SynthIcon around the Icon interface, forwarding calls to * the SynthIcon with a given SynthContext. diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java new file mode 100644 index 00000000000..6b890c786fd --- /dev/null +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java @@ -0,0 +1,307 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.plaf.synth; + +import sun.swing.StringUIClientPropertyKey; +import sun.swing.MenuItemLayoutHelper; +import sun.swing.plaf.synth.SynthIcon; + +import javax.swing.*; +import javax.swing.text.View; +import java.awt.*; + +/** + * Calculates preferred size and layouts synth menu items. + * + * All JMenuItems (and JMenus) include enough space for the insets + * plus one or more elements. When we say "label" below, we mean + * "icon and/or text." + * + * Cases to consider for SynthMenuItemUI (visualized here in a + * LTR orientation; the RTL case would be reversed): + * label + * check icon + label + * check icon + label + accelerator + * label + accelerator + * + * Cases to consider for SynthMenuUI (again visualized here in a + * LTR orientation): + * label + arrow + * + * Note that in the above scenarios, accelerator and arrow icon are + * mutually exclusive. This means that if a popup menu contains a mix + * of JMenus and JMenuItems, we only need to allow enough space for + * max(maxAccelerator, maxArrow), and both accelerators and arrow icons + * can occupy the same "column" of space in the menu. + */ +class SynthMenuItemLayoutHelper extends MenuItemLayoutHelper { + + public static final StringUIClientPropertyKey MAX_ACC_OR_ARROW_WIDTH = + new StringUIClientPropertyKey("maxAccOrArrowWidth"); + + public static final ColumnAlignment LTR_ALIGNMENT_1 = + new ColumnAlignment( + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.RIGHT, + SwingConstants.RIGHT + ); + public static final ColumnAlignment LTR_ALIGNMENT_2 = + new ColumnAlignment( + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.RIGHT + ); + public static final ColumnAlignment RTL_ALIGNMENT_1 = + new ColumnAlignment( + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.LEFT, + SwingConstants.LEFT + ); + public static final ColumnAlignment RTL_ALIGNMENT_2 = + new ColumnAlignment( + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.LEFT + ); + + private SynthContext context; + private SynthContext accContext; + private SynthStyle style; + private SynthStyle accStyle; + private SynthGraphicsUtils gu; + private SynthGraphicsUtils accGu; + private boolean alignAcceleratorText; + private int maxAccOrArrowWidth; + + public SynthMenuItemLayoutHelper(SynthContext context, SynthContext accContext, + JMenuItem mi, Icon checkIcon, Icon arrowIcon, + Rectangle viewRect, int gap, String accDelimiter, + boolean isLeftToRight, boolean useCheckAndArrow, + String propertyPrefix) { + this.context = context; + this.accContext = accContext; + this.style = context.getStyle(); + this.accStyle = accContext.getStyle(); + this.gu = style.getGraphicsUtils(context); + this.accGu = accStyle.getGraphicsUtils(accContext); + this.alignAcceleratorText = getAlignAcceleratorText(propertyPrefix); + reset(mi, checkIcon, arrowIcon, viewRect, gap, accDelimiter, + isLeftToRight, style.getFont(context), accStyle.getFont(accContext), + useCheckAndArrow, propertyPrefix); + setLeadingGap(0); + } + + private boolean getAlignAcceleratorText(String propertyPrefix) { + return style.getBoolean(context, + propertyPrefix + ".alignAcceleratorText", true); + } + + protected void calcWidthsAndHeights() { + // iconRect + if (getIcon() != null) { + getIconSize().setWidth(SynthIcon.getIconWidth(getIcon(), context)); + getIconSize().setHeight(SynthIcon.getIconHeight(getIcon(), context)); + } + + // accRect + if (!getAccText().equals("")) { + getAccSize().setWidth(accGu.computeStringWidth(getAccContext(), + getAccFontMetrics().getFont(), getAccFontMetrics(), + getAccText())); + getAccSize().setHeight(getAccFontMetrics().getHeight()); + } + + // textRect + if (getText() == null) { + setText(""); + } else if (!getText().equals("")) { + if (getHtmlView() != null) { + // Text is HTML + getTextSize().setWidth( + (int) getHtmlView().getPreferredSpan(View.X_AXIS)); + getTextSize().setHeight( + (int) getHtmlView().getPreferredSpan(View.Y_AXIS)); + } else { + // Text isn't HTML + getTextSize().setWidth(gu.computeStringWidth(context, + getFontMetrics().getFont(), getFontMetrics(), + getText())); + getTextSize().setHeight(getFontMetrics().getHeight()); + } + } + + if (useCheckAndArrow()) { + // checkIcon + if (getCheckIcon() != null) { + getCheckSize().setWidth( + SynthIcon.getIconWidth(getCheckIcon(), context)); + getCheckSize().setHeight( + SynthIcon.getIconHeight(getCheckIcon(), context)); + } + // arrowRect + if (getArrowIcon() != null) { + getArrowSize().setWidth( + SynthIcon.getIconWidth(getArrowIcon(), context)); + getArrowSize().setHeight( + SynthIcon.getIconHeight(getArrowIcon(), context)); + } + } + + // labelRect + if (isColumnLayout()) { + getLabelSize().setWidth(getIconSize().getWidth() + + getTextSize().getWidth() + getGap()); + getLabelSize().setHeight(MenuItemLayoutHelper.max( + getCheckSize().getHeight(), + getIconSize().getHeight(), + getTextSize().getHeight(), + getAccSize().getHeight(), + getArrowSize().getHeight())); + } else { + Rectangle textRect = new Rectangle(); + Rectangle iconRect = new Rectangle(); + gu.layoutText(context, getFontMetrics(), getText(), getIcon(), + getHorizontalAlignment(), getVerticalAlignment(), + getHorizontalTextPosition(), getVerticalTextPosition(), + getViewRect(), iconRect, textRect, getGap()); + Rectangle labelRect = iconRect.union(textRect); + getLabelSize().setHeight(labelRect.height); + getLabelSize().setWidth(labelRect.width); + } + } + + protected void calcMaxWidths() { + calcMaxWidth(getCheckSize(), MAX_CHECK_WIDTH); + maxAccOrArrowWidth = + calcMaxValue(MAX_ACC_OR_ARROW_WIDTH, getArrowSize().getWidth()); + maxAccOrArrowWidth = + calcMaxValue(MAX_ACC_OR_ARROW_WIDTH, getAccSize().getWidth()); + + if (isColumnLayout()) { + calcMaxWidth(getIconSize(), MAX_ICON_WIDTH); + calcMaxWidth(getTextSize(), MAX_TEXT_WIDTH); + int curGap = getGap(); + if ((getIconSize().getMaxWidth() == 0) + || (getTextSize().getMaxWidth() == 0)) { + curGap = 0; + } + getLabelSize().setMaxWidth( + calcMaxValue(MAX_LABEL_WIDTH, getIconSize().getMaxWidth() + + getTextSize().getMaxWidth() + curGap)); + } else { + // We shouldn't use current icon and text widths + // in maximal widths calculation for complex layout. + getIconSize().setMaxWidth(getParentIntProperty( + MAX_ICON_WIDTH)); + calcMaxWidth(getLabelSize(), MAX_LABEL_WIDTH); + // If maxLabelWidth is wider + // than the widest icon + the widest text + gap, + // we should update the maximal text witdh + int candidateTextWidth = getLabelSize().getMaxWidth() - + getIconSize().getMaxWidth(); + if (getIconSize().getMaxWidth() > 0) { + candidateTextWidth -= getGap(); + } + getTextSize().setMaxWidth(calcMaxValue( + MAX_TEXT_WIDTH, candidateTextWidth)); + } + } + + public SynthContext getContext() { + return context; + } + + public SynthContext getAccContext() { + return accContext; + } + + public SynthStyle getStyle() { + return style; + } + + public SynthStyle getAccStyle() { + return accStyle; + } + + public SynthGraphicsUtils getGraphicsUtils() { + return gu; + } + + public SynthGraphicsUtils getAccGraphicsUtils() { + return accGu; + } + + public boolean alignAcceleratorText() { + return alignAcceleratorText; + } + + public int getMaxAccOrArrowWidth() { + return maxAccOrArrowWidth; + } + + protected void prepareForLayout(LayoutResult lr) { + lr.getCheckRect().width = getCheckSize().getMaxWidth(); + // An item can have an arrow or a check icon at once + if (useCheckAndArrow() && (!"".equals(getAccText()))) { + lr.getAccRect().width = maxAccOrArrowWidth; + } else { + lr.getArrowRect().width = maxAccOrArrowWidth; + } + } + + public ColumnAlignment getLTRColumnAlignment() { + if (alignAcceleratorText()) { + return LTR_ALIGNMENT_2; + } else { + return LTR_ALIGNMENT_1; + } + } + + public ColumnAlignment getRTLColumnAlignment() { + if (alignAcceleratorText()) { + return RTL_ALIGNMENT_2; + } else { + return RTL_ALIGNMENT_1; + } + } + + protected void layoutIconAndTextInLabelRect(LayoutResult lr) { + lr.setTextRect(new Rectangle()); + lr.setIconRect(new Rectangle()); + gu.layoutText(context, getFontMetrics(), getText(), getIcon(), + getHorizontalAlignment(), getVerticalAlignment(), + getHorizontalTextPosition(), getVerticalTextPosition(), + lr.getLabelRect(), lr.getIconRect(), lr.getTextRect(), getGap()); + } +} diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java index 39fc82c10b5..3bcc044a12e 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,7 +37,7 @@ import javax.swing.plaf.*; import javax.swing.plaf.basic.*; import javax.swing.text.View; import sun.swing.plaf.synth.*; -import sun.swing.SwingUtilities2; +import sun.swing.MenuItemLayoutHelper; /** @@ -59,542 +59,16 @@ class SynthMenuItemUI extends BasicMenuItemUI implements return new SynthMenuItemUI(); } - // - // The next handful of static methods are used by both SynthMenuUI - // and SynthMenuItemUI. This is necessitated by SynthMenuUI not - // extending SynthMenuItemUI. - // - - /* - * All JMenuItems (and JMenus) include enough space for the insets - * plus one or more elements. When we say "icon(s)" below, we mean - * "check/radio indicator and/or user icon." If both are defined for - * a given menu item, then in a LTR orientation the check/radio indicator - * is on the left side followed by the user icon to the right; it is - * just the opposite in a RTL orientation. - * - * Cases to consider for SynthMenuItemUI (visualized here in a - * LTR orientation; the RTL case would be reversed): - * text - * icon(s) + text - * icon(s) + text + accelerator - * text + accelerator - * - * Cases to consider for SynthMenuUI (again visualized here in a - * LTR orientation): - * text + arrow - * (user)icon + text + arrow - * - * Note that in the above scenarios, accelerator and arrow icon are - * mutually exclusive. This means that if a popup menu contains a mix - * of JMenus and JMenuItems, we only need to allow enough space for - * max(maxAccelerator, maxArrow), and both accelerators and arrow icons - * can occupy the same "column" of space in the menu. - * - * A quick note about how preferred sizes are calculated... Generally - * speaking, SynthPopupMenuUI will run through the list of its children - * (from top to bottom) and ask each for its preferred size. Each menu - * item will add up the max width of each element (icons, text, - * accelerator spacing, accelerator text or arrow icon) encountered thus - * far, so by the time all menu items have been calculated, we will - * know the maximum (preferred) menu item size for that popup menu. - * Later when it comes time to paint each menu item, we can use those - * same accumulated max element sizes in order to layout the item. - */ - static Dimension getPreferredMenuItemSize(SynthContext context, - SynthContext accContext, JComponent c, - Icon checkIcon, Icon arrowIcon, int defaultTextIconGap, - String acceleratorDelimiter) { - JMenuItem b = (JMenuItem) c; - Icon icon = b.getIcon(); - String text = b.getText(); - KeyStroke accelerator = b.getAccelerator(); - String acceleratorText = ""; - - if (accelerator != null) { - int modifiers = accelerator.getModifiers(); - if (modifiers > 0) { - acceleratorText = KeyEvent.getKeyModifiersText(modifiers); - acceleratorText += acceleratorDelimiter; - } - int keyCode = accelerator.getKeyCode(); - if (keyCode != 0) { - acceleratorText += KeyEvent.getKeyText(keyCode); - } else { - acceleratorText += accelerator.getKeyChar(); - } - } - - Font font = context.getStyle().getFont(context); - FontMetrics fm = b.getFontMetrics(font); - FontMetrics fmAccel = b.getFontMetrics(accContext.getStyle(). - getFont(accContext)); - - resetRects(); - - layoutMenuItem( - context, fm, accContext, text, fmAccel, acceleratorText, - icon, checkIcon, arrowIcon, b.getVerticalAlignment(), - b.getHorizontalAlignment(), b.getVerticalTextPosition(), - b.getHorizontalTextPosition(), viewRect, iconRect, textRect, - acceleratorRect, checkIconRect, arrowIconRect, - text == null ? 0 : defaultTextIconGap, defaultTextIconGap); - - r.setBounds(textRect); - - int totalIconWidth = 0; - int maxIconHeight = 0; - if (icon != null) { - // Add in the user icon - totalIconWidth += iconRect.width; - if (textRect.width > 0) { - // Allow for some room between the user icon and the text - totalIconWidth += defaultTextIconGap; - } - maxIconHeight = Math.max(iconRect.height, maxIconHeight); - } - if (checkIcon != null) { - // Add in the checkIcon - totalIconWidth += checkIconRect.width; - if (textRect.width > 0 || icon != null) { - // Allow for some room between the check/radio indicator - // and the text (or user icon, if both are specified) - totalIconWidth += defaultTextIconGap; - } - maxIconHeight = Math.max(checkIconRect.height, maxIconHeight); - } - - int arrowWidth = 0; - if (arrowIcon != null) { - // Add in the arrowIcon - arrowWidth += defaultTextIconGap; - arrowWidth += arrowIconRect.width; - maxIconHeight = Math.max(arrowIconRect.height, maxIconHeight); - } - - int accelSpacing = 0; - if (acceleratorRect.width > 0) { - // Allow for some room between the text and the accelerator - accelSpacing += 4*defaultTextIconGap; - } - - // Take text and all icons into account when determining height - r.height = Math.max(r.height, maxIconHeight); - - // To make the accelerator texts appear in a column, - // find the widest MenuItem text and the widest accelerator text. - - // Get the parent, which stores the information. - Container parent = b.getParent(); - - if (parent instanceof JPopupMenu) { - SynthPopupMenuUI popupUI = (SynthPopupMenuUI)SynthLookAndFeel. - getUIOfType(((JPopupMenu)parent).getUI(), - SynthPopupMenuUI.class); - - if (popupUI != null) { - // This gives us the widest MenuItem text encountered thus - // far in the parent JPopupMenu - r.width = popupUI.adjustTextWidth(r.width); - - // Add in the widest icon (includes both user and - // check/radio icons) encountered thus far - r.width += popupUI.adjustIconWidth(totalIconWidth); - - // Add in the widest text/accelerator spacing - // encountered thus far - r.width += popupUI.adjustAccelSpacingWidth(accelSpacing); - - // Add in the widest accelerator text (or arrow) - // encountered thus far (at least one of these values - // will always be zero, so we combine them here to - // avoid double counting) - int totalAccelOrArrow = acceleratorRect.width + arrowWidth; - r.width += popupUI.adjustAcceleratorWidth(totalAccelOrArrow); - } - } - else if (parent != null && !(b instanceof JMenu && - ((JMenu)b).isTopLevelMenu())) { - r.width += - totalIconWidth + accelSpacing + - acceleratorRect.width + arrowWidth; - } - - Insets insets = b.getInsets(); - if(insets != null) { - r.width += insets.left + insets.right; - r.height += insets.top + insets.bottom; - } - - // if the width is even, bump it up one. This is critical - // for the focus dash line to draw properly - if(r.width%2 == 0) { - r.width++; - } - - // if the height is even, bump it up one. This is critical - // for the text to center properly - if(r.height%2 == 0) { - r.height++; - } - return r.getSize(); - } - - static void paint(SynthContext context, SynthContext accContext, - Graphics g, Icon checkIcon, Icon arrowIcon, - String acceleratorDelimiter, - int defaultTextIconGap) { - JComponent c = context.getComponent(); - JMenuItem b = (JMenuItem)c; - ButtonModel model = b.getModel(); - Insets i = b.getInsets(); - - resetRects(); - - viewRect.setBounds(0, 0, b.getWidth(), b.getHeight()); - - viewRect.x += i.left; - viewRect.y += i.top; - viewRect.width -= (i.right + viewRect.x); - viewRect.height -= (i.bottom + viewRect.y); - - SynthStyle style = context.getStyle(); - Font f = style.getFont(context); - g.setFont(f); - FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, f); - FontMetrics accFM = SwingUtilities2.getFontMetrics(c, g, - accContext.getStyle(). - getFont(accContext)); - - // get Accelerator text - KeyStroke accelerator = b.getAccelerator(); - String acceleratorText = ""; - if (accelerator != null) { - int modifiers = accelerator.getModifiers(); - if (modifiers > 0) { - acceleratorText = KeyEvent.getKeyModifiersText(modifiers); - acceleratorText += acceleratorDelimiter; - } - - int keyCode = accelerator.getKeyCode(); - if (keyCode != 0) { - acceleratorText += KeyEvent.getKeyText(keyCode); - } else { - acceleratorText += accelerator.getKeyChar(); - } - } - - // Layout the text and icon - String text = layoutMenuItem(context, fm, accContext, - b.getText(), accFM, acceleratorText, b.getIcon(), - checkIcon, arrowIcon, - b.getVerticalAlignment(), b.getHorizontalAlignment(), - b.getVerticalTextPosition(), b.getHorizontalTextPosition(), - viewRect, iconRect, textRect, acceleratorRect, - checkIconRect, arrowIconRect, - b.getText() == null ? 0 : defaultTextIconGap, - defaultTextIconGap - ); - - // Paint the Check - if (checkIcon != null) { - SynthIcon.paintIcon(checkIcon, context, g, checkIconRect.x, - checkIconRect.y, checkIconRect.width, checkIconRect.height); - } - - // Paint the Icon - if(b.getIcon() != null) { - Icon icon; - if(!model.isEnabled()) { - icon = b.getDisabledIcon(); - } else if(model.isPressed() && model.isArmed()) { - icon = b.getPressedIcon(); - if(icon == null) { - // Use default icon - icon = b.getIcon(); - } - } else { - icon = b.getIcon(); - } - - if (icon!=null) { - SynthIcon.paintIcon(icon, context, g, iconRect.x, - iconRect.y, iconRect.width, iconRect.height); - } - } - - // Draw the Text - if(text != null) { - View v = (View) c.getClientProperty(BasicHTML.propertyKey); - if (v != null) { - v.paint(g, textRect); - } else { - g.setColor(style.getColor(context, ColorType.TEXT_FOREGROUND)); - g.setFont(style.getFont(context)); - style.getGraphicsUtils(context).paintText(context, g, text, - textRect.x, textRect.y, b.getDisplayedMnemonicIndex()); - } - } - - // Draw the Accelerator Text - if(acceleratorText != null && !acceleratorText.equals("")) { - // Get the maxAccWidth from the parent to calculate the offset. - int accOffset = 0; - Container parent = b.getParent(); - if (parent != null && parent instanceof JPopupMenu) { - SynthPopupMenuUI popupUI = (SynthPopupMenuUI) - ((JPopupMenu)parent).getUI(); - - // Note that we can only get here for SynthMenuItemUI - // (not SynthMenuUI) since acceleratorText is defined, - // so this cast should be safe - SynthMenuItemUI miUI = (SynthMenuItemUI) - SynthLookAndFeel.getUIOfType(b.getUI(), - SynthMenuItemUI.class); - - if (popupUI != null && miUI != null) { - String prop = - miUI.getPropertyPrefix() + ".alignAcceleratorText"; - boolean align = style.getBoolean(context, prop, true); - - // Calculate the offset, with which the accelerator texts - // will be drawn. - if (align) { - // When align==true and we're in the LTR case, - // we add an offset here so that all accelerators - // will be left-justified in their own column. - int max = popupUI.getMaxAcceleratorWidth(); - if (max > 0) { - accOffset = max - acceleratorRect.width; - if (!SynthLookAndFeel.isLeftToRight(c)) { - // In the RTL, flip the sign so that all - // accelerators will be right-justified. - accOffset = -accOffset; - } - } - } //else { - // Don't need to do anything special here; in the - // LTR case, the accelerator is already justified - // against the right edge of the menu (and against - // the left edge in the RTL case). - //} - } - } - - SynthStyle accStyle = accContext.getStyle(); - - g.setColor(accStyle.getColor(accContext, - ColorType.TEXT_FOREGROUND)); - g.setFont(accStyle.getFont(accContext)); - accStyle.getGraphicsUtils(accContext).paintText( - accContext, g, acceleratorText, acceleratorRect.x - - accOffset, acceleratorRect.y, -1); - } - - // Paint the Arrow - if (arrowIcon != null) { - SynthIcon.paintIcon(arrowIcon, context, g, arrowIconRect.x, - arrowIconRect.y, arrowIconRect.width, arrowIconRect.height); + public void uninstallUI(JComponent c) { + super.uninstallUI(c); + // Remove values from the parent's Client Properties. + JComponent p = MenuItemLayoutHelper.getMenuItemParent((JMenuItem) c); + if (p != null) { + p.putClientProperty( + SynthMenuItemLayoutHelper.MAX_ACC_OR_ARROW_WIDTH, null); } } - /** - * Compute and return the location of the icons origin, the - * location of origin of the text baseline, and a possibly clipped - * version of the compound labels string. Locations are computed - * relative to the viewRect rectangle. - */ - - private static String layoutMenuItem( - SynthContext context, - FontMetrics fm, - SynthContext accContext, - String text, - FontMetrics fmAccel, - String acceleratorText, - Icon icon, - Icon checkIcon, - Icon arrowIcon, - int verticalAlignment, - int horizontalAlignment, - int verticalTextPosition, - int horizontalTextPosition, - Rectangle viewRect, - Rectangle iconRect, - Rectangle textRect, - Rectangle acceleratorRect, - Rectangle checkIconRect, - Rectangle arrowIconRect, - int textIconGap, - int menuItemGap - ) - { - // If parent is JPopupMenu, get and store it's UI - SynthPopupMenuUI popupUI = null; - JComponent b = context.getComponent(); - Container parent = b.getParent(); - if(parent instanceof JPopupMenu) { - popupUI = (SynthPopupMenuUI)SynthLookAndFeel. - getUIOfType(((JPopupMenu)parent).getUI(), - SynthPopupMenuUI.class); - } - - context.getStyle().getGraphicsUtils(context).layoutText( - context, fm, text, icon,horizontalAlignment, verticalAlignment, - horizontalTextPosition, verticalTextPosition, viewRect, - iconRect, textRect, textIconGap); - - /* Initialize the acceleratorText bounds rectangle textRect. If a null - * or and empty String was specified we substitute "" here - * and use 0,0,0,0 for acceleratorTextRect. - */ - if( (acceleratorText == null) || acceleratorText.equals("") ) { - acceleratorRect.width = acceleratorRect.height = 0; - acceleratorText = ""; - } - else { - SynthStyle style = accContext.getStyle(); - acceleratorRect.width = style.getGraphicsUtils(accContext). - computeStringWidth(accContext, fmAccel.getFont(), fmAccel, - acceleratorText); - acceleratorRect.height = fmAccel.getHeight(); - } - - // Initialize the checkIcon bounds rectangle width & height. - if (checkIcon != null) { - checkIconRect.width = SynthIcon.getIconWidth(checkIcon, - context); - checkIconRect.height = SynthIcon.getIconHeight(checkIcon, - context); - } - else { - checkIconRect.width = checkIconRect.height = 0; - } - - // Initialize the arrowIcon bounds rectangle width & height. - if (arrowIcon != null) { - arrowIconRect.width = SynthIcon.getIconWidth(arrowIcon, - context); - arrowIconRect.height = SynthIcon.getIconHeight(arrowIcon, - context); - } else { - arrowIconRect.width = arrowIconRect.height = 0; - } - - // Note: layoutText() has already left room for - // the user icon, so no need to adjust textRect below - // to account for the user icon. However, we do have to - // reposition textRect when the check icon is visible. - - Rectangle labelRect = iconRect.union(textRect); - if( SynthLookAndFeel.isLeftToRight(context.getComponent()) ) { - // Position the check and user icons - iconRect.x = viewRect.x; - if (checkIcon != null) { - checkIconRect.x = viewRect.x; - iconRect.x += menuItemGap + checkIconRect.width; - textRect.x += menuItemGap + checkIconRect.width; - } - - // Position the arrow icon - arrowIconRect.x = - viewRect.x + viewRect.width - arrowIconRect.width; - - // Position the accelerator text rect - acceleratorRect.x = - viewRect.x + viewRect.width - acceleratorRect.width; - - /* Align icons and text horizontally */ - if(popupUI != null) { - int thisTextOffset = popupUI.adjustTextOffset(textRect.x - - viewRect.x); - textRect.x = thisTextOffset + viewRect.x; - - if(icon != null) { - // REMIND: The following code currently assumes the - // default (TRAILING) horizontalTextPosition, which means - // it will always place the icon to the left of the text. - // Other values of horizontalTextPosition aren't very - // useful for menu items, so we ignore them for now, but - // someday we might want to fix this situation. - int thisIconOffset = - popupUI.adjustIconOffset(iconRect.x - viewRect.x); - iconRect.x = thisIconOffset + viewRect.x; - } - } - } else { - // Position the accelerator text rect - acceleratorRect.x = viewRect.x; - - // Position the arrow icon - arrowIconRect.x = viewRect.x; - - // Position the check and user icons - iconRect.x = - viewRect.x + viewRect.width - iconRect.width; - if (checkIcon != null) { - checkIconRect.x = - viewRect.x + viewRect.width - checkIconRect.width; - textRect.x -= menuItemGap + checkIconRect.width; - iconRect.x -= menuItemGap + checkIconRect.width; - } - - /* Align icons and text horizontally */ - if(popupUI != null) { - int thisTextOffset = viewRect.x + viewRect.width - - textRect.x - textRect.width; - thisTextOffset = popupUI.adjustTextOffset(thisTextOffset); - textRect.x = viewRect.x + viewRect.width - - thisTextOffset - textRect.width; - if(icon != null) { - // REMIND: The following code currently assumes the - // default (TRAILING) horizontalTextPosition, which means - // it will always place the icon to the right of the text. - // Other values of horizontalTextPosition aren't very - // useful for menu items, so we ignore them for now, but - // someday we might want to fix this situation. - int thisIconOffset = viewRect.x + viewRect.width - - iconRect.x - iconRect.width; - thisIconOffset = - popupUI.adjustIconOffset(thisIconOffset); - iconRect.x = viewRect.x + viewRect.width - - thisIconOffset - iconRect.width; - } - } - } - - // Align the accelerator text and all icons vertically - // with the center of the label rect. - int midY = labelRect.y + (labelRect.height/2); - iconRect.y = midY - (iconRect.height/2); - acceleratorRect.y = midY - (acceleratorRect.height/2); - arrowIconRect.y = midY - (arrowIconRect.height/2); - checkIconRect.y = midY - (checkIconRect.height/2); - - return text; - } - - // these rects are used for painting and preferredsize calculations. - // they used to be regenerated constantly. Now they are reused. - static Rectangle iconRect = new Rectangle(); - static Rectangle textRect = new Rectangle(); - static Rectangle acceleratorRect = new Rectangle(); - static Rectangle checkIconRect = new Rectangle(); - static Rectangle arrowIconRect = new Rectangle(); - static Rectangle viewRect = new Rectangle(Short.MAX_VALUE,Short.MAX_VALUE); - static Rectangle r = new Rectangle(); - - private static void resetRects() { - iconRect.setBounds(0, 0, 0, 0); - textRect.setBounds(0, 0, 0, 0); - acceleratorRect.setBounds(0, 0, 0, 0); - checkIconRect.setBounds(0, 0, 0, 0); - arrowIconRect.setBounds(0, 0, 0, 0); - viewRect.setBounds(0,0,Short.MAX_VALUE, Short.MAX_VALUE); - r.setBounds(0, 0, 0, 0); - } - - protected void installDefaults() { updateStyle(menuItem); } @@ -718,9 +192,11 @@ class SynthMenuItemUI extends BasicMenuItemUI implements int defaultTextIconGap) { SynthContext context = getContext(c); SynthContext accContext = getContext(c, Region.MENU_ITEM_ACCELERATOR); - Dimension value = getPreferredMenuItemSize(context, accContext, - c, checkIcon, arrowIcon, defaultTextIconGap, - acceleratorDelimiter); + Dimension value = SynthGraphicsUtils.getPreferredMenuItemSize( + context, accContext, c, checkIcon, arrowIcon, + defaultTextIconGap, acceleratorDelimiter, + MenuItemLayoutHelper.useCheckAndArrow(menuItem), + getPropertyPrefix()); context.dispose(); accContext.dispose(); return value; @@ -751,14 +227,13 @@ class SynthMenuItemUI extends BasicMenuItemUI implements String prefix = getPropertyPrefix(); Icon checkIcon = style.getIcon(context, prefix + ".checkIcon"); Icon arrowIcon = style.getIcon(context, prefix + ".arrowIcon"); - paint(context, accContext, g, checkIcon, arrowIcon, - acceleratorDelimiter, defaultTextIconGap); + SynthGraphicsUtils.paint(context, accContext, g, checkIcon, arrowIcon, + acceleratorDelimiter, defaultTextIconGap, getPropertyPrefix()); accContext.dispose(); } void paintBackground(SynthContext context, Graphics g, JComponent c) { - context.getPainter().paintMenuItemBackground(context, g, 0, 0, - c.getWidth(), c.getHeight()); + SynthGraphicsUtils.paintBackground(context, g, c); } public void paintBorder(SynthContext context, Graphics g, int x, diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java index c59acb09b28..78835abf141 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,7 @@ import javax.swing.border.*; import java.util.Arrays; import java.util.ArrayList; import sun.swing.plaf.synth.SynthUI; - +import sun.swing.MenuItemLayoutHelper; /** * Synth's MenuUI. @@ -86,7 +86,7 @@ class SynthMenuUI extends BasicMenuUI implements PropertyChangeListener, acceleratorDelimiter = style.getString(context, prefix + ".acceleratorDelimiter", "+"); - if (useCheckAndArrow()) { + if (MenuItemLayoutHelper.useCheckAndArrow(menuItem)) { checkIcon = style.getIcon(context, prefix + ".checkIcon"); arrowIcon = style.getIcon(context, prefix + ".arrowIcon"); } else { @@ -111,6 +111,16 @@ class SynthMenuUI extends BasicMenuUI implements PropertyChangeListener, accContext.dispose(); } + public void uninstallUI(JComponent c) { + super.uninstallUI(c); + // Remove values from the parent's Client Properties. + JComponent p = MenuItemLayoutHelper.getMenuItemParent((JMenuItem) c); + if (p != null) { + p.putClientProperty( + SynthMenuItemLayoutHelper.MAX_ACC_OR_ARROW_WIDTH, null); + } + } + protected void uninstallDefaults() { SynthContext context = getContext(menuItem, ENABLED); style.uninstallDefaults(context); @@ -182,9 +192,11 @@ class SynthMenuUI extends BasicMenuUI implements PropertyChangeListener, int defaultTextIconGap) { SynthContext context = getContext(c); SynthContext accContext = getContext(c, Region.MENU_ITEM_ACCELERATOR); - Dimension value = SynthMenuItemUI.getPreferredMenuItemSize( - context, accContext, c, checkIcon, arrowIcon, - defaultTextIconGap, acceleratorDelimiter); + Dimension value = SynthGraphicsUtils.getPreferredMenuItemSize( + context, accContext, c, checkIcon, arrowIcon, + defaultTextIconGap, acceleratorDelimiter, + MenuItemLayoutHelper.useCheckAndArrow(menuItem), + getPropertyPrefix()); context.dispose(); accContext.dispose(); return value; @@ -211,21 +223,12 @@ class SynthMenuUI extends BasicMenuUI implements PropertyChangeListener, protected void paint(SynthContext context, Graphics g) { SynthContext accContext = getContext(menuItem, Region.MENU_ITEM_ACCELERATOR); - SynthStyle style = context.getStyle(); - Icon checkIcon; - Icon arrowIcon; - if (useCheckAndArrow()) { - // Refetch the appropriate icons for the current state - String prefix = getPropertyPrefix(); - checkIcon = style.getIcon(context, prefix + ".checkIcon"); - arrowIcon = style.getIcon(context, prefix + ".arrowIcon"); - } else { - // Not needed in this case - checkIcon = null; - arrowIcon = null; - } - SynthMenuItemUI.paint(context, accContext, g, checkIcon, arrowIcon, - acceleratorDelimiter, defaultTextIconGap); + // Refetch the appropriate check indicator for the current state + String prefix = getPropertyPrefix(); + Icon checkIcon = style.getIcon(context, prefix + ".checkIcon"); + Icon arrowIcon = style.getIcon(context, prefix + ".arrowIcon"); + SynthGraphicsUtils.paint(context, accContext, g, checkIcon, arrowIcon, + acceleratorDelimiter, defaultTextIconGap, getPropertyPrefix()); accContext.dispose(); } @@ -239,8 +242,4 @@ class SynthMenuUI extends BasicMenuUI implements PropertyChangeListener, updateStyle((JMenu)e.getSource()); } } - - private boolean useCheckAndArrow() { - return !((JMenu)menuItem).isTopLevelMenu(); - } } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java index e8fb73bc156..50d1c2781ac 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,34 +58,6 @@ import sun.swing.plaf.synth.SynthUI; */ class SynthPopupMenuUI extends BasicPopupMenuUI implements PropertyChangeListener, SynthUI { - /** - * Maximum size of the text portion of the children menu items. - */ - private int maxTextWidth; - - /** - * Maximum size of the icon portion of the children menu items. - */ - private int maxIconWidth; - - /** - * Maximum size of the spacing between the text and accelerator - * portions of the children menu items. - */ - private int maxAccelSpacingWidth; - - /** - * Maximum size of the text for the accelerator portion of the children - * menu items. - */ - private int maxAcceleratorWidth; - - /* - * Maximum icon and text offsets of the children menu items. - */ - private int maxTextOffset; - private int maxIconOffset; - private SynthStyle style; public static ComponentUI createUI(JComponent x) { @@ -153,90 +125,6 @@ class SynthPopupMenuUI extends BasicPopupMenuUI implements return SynthLookAndFeel.getComponentState(c); } - /** - * Resets the max text and accerator widths, - * text and icon offsets. - */ - void resetAlignmentHints() { - maxTextWidth = maxIconWidth - = maxAccelSpacingWidth = maxAcceleratorWidth - = maxTextOffset = maxIconOffset = 0; - } - - /** - * Adjusts the width needed to display the maximum menu item string. - * - * @param width Text width. - * @return max width - */ - int adjustTextWidth(int width) { - maxTextWidth = Math.max(maxTextWidth, width); - return maxTextWidth; - } - - /** - * Adjusts the width needed to display the maximum menu item icon. - * - * @param width Icon width. - * @return max width - */ - int adjustIconWidth(int width) { - maxIconWidth = Math.max(maxIconWidth, width); - return maxIconWidth; - } - - /** - * Adjusts the width needed to pad between the maximum menu item - * text and accelerator. - * - * @param width Spacing width. - * @return max width - */ - int adjustAccelSpacingWidth(int width) { - maxAccelSpacingWidth = Math.max(maxAccelSpacingWidth, width); - return maxAccelSpacingWidth; - } - - /** - * Adjusts the width needed to display the maximum accelerator. - * - * @param width Text width. - * @return max width - */ - int adjustAcceleratorWidth(int width) { - maxAcceleratorWidth = Math.max(maxAcceleratorWidth, width); - return maxAcceleratorWidth; - } - - /** - * Maximum size needed to display accelerators of children menu items. - */ - int getMaxAcceleratorWidth() { - return maxAcceleratorWidth; - } - - /** - * Adjusts the text offset needed to align text horizontally. - * - * @param offset Text offset - * @return max offset - */ - int adjustTextOffset(int offset) { - maxTextOffset = Math.max(maxTextOffset, offset); - return maxTextOffset; - } - - /** - * Adjusts the icon offset needed to align icons horizontally - * - * @param offset Icon offset - * @return max offset - */ - int adjustIconOffset(int offset) { - maxIconOffset = Math.max(maxIconOffset, offset); - return maxIconOffset; - } - public void update(Graphics g, JComponent c) { SynthContext context = getContext(c); diff --git a/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java b/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java new file mode 100644 index 00000000000..5c4810b8f0e --- /dev/null +++ b/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java @@ -0,0 +1,1339 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package sun.swing; + +import static sun.swing.SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET; + +import javax.swing.*; +import javax.swing.plaf.basic.BasicHTML; +import javax.swing.text.View; +import java.awt.*; +import java.awt.event.KeyEvent; +import java.util.Map; +import java.util.HashMap; + +/** + * Calculates preferred size and layouts menu items. + */ +public class MenuItemLayoutHelper { + + /* Client Property keys for calculation of maximal widths */ + public static final StringUIClientPropertyKey MAX_ARROW_WIDTH = + new StringUIClientPropertyKey("maxArrowWidth"); + public static final StringUIClientPropertyKey MAX_CHECK_WIDTH = + new StringUIClientPropertyKey("maxCheckWidth"); + public static final StringUIClientPropertyKey MAX_ICON_WIDTH = + new StringUIClientPropertyKey("maxIconWidth"); + public static final StringUIClientPropertyKey MAX_TEXT_WIDTH = + new StringUIClientPropertyKey("maxTextWidth"); + public static final StringUIClientPropertyKey MAX_ACC_WIDTH = + new StringUIClientPropertyKey("maxAccWidth"); + public static final StringUIClientPropertyKey MAX_LABEL_WIDTH = + new StringUIClientPropertyKey("maxLabelWidth"); + + private JMenuItem mi; + private JComponent miParent; + + private Font font; + private Font accFont; + private FontMetrics fm; + private FontMetrics accFm; + + private Icon icon; + private Icon checkIcon; + private Icon arrowIcon; + private String text; + private String accText; + + private boolean isColumnLayout; + private boolean useCheckAndArrow; + private boolean isLeftToRight; + private boolean isTopLevelMenu; + private View htmlView; + + private int verticalAlignment; + private int horizontalAlignment; + private int verticalTextPosition; + private int horizontalTextPosition; + private int gap; + private int leadingGap; + private int afterCheckIconGap; + private int minTextOffset; + + private Rectangle viewRect; + + private RectSize iconSize; + private RectSize textSize; + private RectSize accSize; + private RectSize checkSize; + private RectSize arrowSize; + private RectSize labelSize; + + /** + * The empty protected constructor is necessary for derived classes. + */ + protected MenuItemLayoutHelper() { + } + + public MenuItemLayoutHelper(JMenuItem mi, Icon checkIcon, Icon arrowIcon, + Rectangle viewRect, int gap, String accDelimiter, + boolean isLeftToRight, Font font, Font accFont, + boolean useCheckAndArrow, String propertyPrefix) { + reset(mi, checkIcon, arrowIcon, viewRect, gap, accDelimiter, + isLeftToRight, font, accFont, useCheckAndArrow, propertyPrefix); + } + + protected void reset(JMenuItem mi, Icon checkIcon, Icon arrowIcon, + Rectangle viewRect, int gap, String accDelimiter, + boolean isLeftToRight, Font font, Font accFont, + boolean useCheckAndArrow, String propertyPrefix) { + this.mi = mi; + this.miParent = getMenuItemParent(mi); + this.accText = getAccText(accDelimiter); + this.verticalAlignment = mi.getVerticalAlignment(); + this.horizontalAlignment = mi.getHorizontalAlignment(); + this.verticalTextPosition = mi.getVerticalTextPosition(); + this.horizontalTextPosition = mi.getHorizontalTextPosition(); + this.useCheckAndArrow = useCheckAndArrow; + this.font = font; + this.accFont = accFont; + this.fm = mi.getFontMetrics(font); + this.accFm = mi.getFontMetrics(accFont); + this.isLeftToRight = isLeftToRight; + this.isColumnLayout = isColumnLayout(isLeftToRight, + horizontalAlignment, horizontalTextPosition, + verticalTextPosition); + this.isTopLevelMenu = (this.miParent == null) ? true : false; + this.checkIcon = checkIcon; + this.icon = getIcon(propertyPrefix); + this.arrowIcon = arrowIcon; + this.text = mi.getText(); + this.gap = gap; + this.afterCheckIconGap = getAfterCheckIconGap(propertyPrefix); + this.minTextOffset = getMinTextOffset(propertyPrefix); + this.htmlView = (View) mi.getClientProperty(BasicHTML.propertyKey); + this.viewRect = viewRect; + + this.iconSize = new RectSize(); + this.textSize = new RectSize(); + this.accSize = new RectSize(); + this.checkSize = new RectSize(); + this.arrowSize = new RectSize(); + this.labelSize = new RectSize(); + calcWidthsAndHeights(); + setOriginalWidths(); + calcMaxWidths(); + + this.leadingGap = getLeadingGap(propertyPrefix); + calcMaxTextOffset(viewRect); + } + + private void setOriginalWidths() { + iconSize.origWidth = iconSize.width; + textSize.origWidth = textSize.width; + accSize.origWidth = accSize.width; + checkSize.origWidth = checkSize.width; + arrowSize.origWidth = arrowSize.width; + } + + private String getAccText(String acceleratorDelimiter) { + String accText = ""; + KeyStroke accelerator = mi.getAccelerator(); + if (accelerator != null) { + int modifiers = accelerator.getModifiers(); + if (modifiers > 0) { + accText = KeyEvent.getKeyModifiersText(modifiers); + accText += acceleratorDelimiter; + } + int keyCode = accelerator.getKeyCode(); + if (keyCode != 0) { + accText += KeyEvent.getKeyText(keyCode); + } else { + accText += accelerator.getKeyChar(); + } + } + return accText; + } + + private Icon getIcon(String propertyPrefix) { + // In case of column layout, .checkIconFactory is defined for this UI, + // the icon is compatible with it and useCheckAndArrow() is true, + // then the icon is handled by the checkIcon. + Icon icon = null; + MenuItemCheckIconFactory iconFactory = + (MenuItemCheckIconFactory) UIManager.get(propertyPrefix + + ".checkIconFactory"); + if (!isColumnLayout || !useCheckAndArrow || iconFactory == null + || !iconFactory.isCompatible(checkIcon, propertyPrefix)) { + icon = mi.getIcon(); + } + return icon; + } + + private int getMinTextOffset(String propertyPrefix) { + int minimumTextOffset = 0; + Object minimumTextOffsetObject = + UIManager.get(propertyPrefix + ".minimumTextOffset"); + if (minimumTextOffsetObject instanceof Integer) { + minimumTextOffset = (Integer) minimumTextOffsetObject; + } + return minimumTextOffset; + } + + private int getAfterCheckIconGap(String propertyPrefix) { + int afterCheckIconGap = gap; + Object afterCheckIconGapObject = + UIManager.get(propertyPrefix + ".afterCheckIconGap"); + if (afterCheckIconGapObject instanceof Integer) { + afterCheckIconGap = (Integer) afterCheckIconGapObject; + } + return afterCheckIconGap; + } + + private int getLeadingGap(String propertyPrefix) { + if (checkSize.getMaxWidth() > 0) { + return getCheckOffset(propertyPrefix); + } else { + return gap; // There is no any check icon + } + } + + private int getCheckOffset(String propertyPrefix) { + int checkIconOffset = gap; + Object checkIconOffsetObject = + UIManager.get(propertyPrefix + ".checkIconOffset"); + if (checkIconOffsetObject instanceof Integer) { + checkIconOffset = (Integer) checkIconOffsetObject; + } + return checkIconOffset; + } + + protected void calcWidthsAndHeights() { + // iconRect + if (icon != null) { + iconSize.width = icon.getIconWidth(); + iconSize.height = icon.getIconHeight(); + } + + // accRect + if (!accText.equals("")) { + accSize.width = SwingUtilities2.stringWidth(mi, accFm, accText); + accSize.height = accFm.getHeight(); + } + + // textRect + if (text == null) { + text = ""; + } else if (!text.equals("")) { + if (htmlView != null) { + // Text is HTML + textSize.width = + (int) htmlView.getPreferredSpan(View.X_AXIS); + textSize.height = + (int) htmlView.getPreferredSpan(View.Y_AXIS); + } else { + // Text isn't HTML + textSize.width = SwingUtilities2.stringWidth(mi, fm, text); + textSize.height = fm.getHeight(); + } + } + + if (useCheckAndArrow) { + // checkIcon + if (checkIcon != null) { + checkSize.width = checkIcon.getIconWidth(); + checkSize.height = checkIcon.getIconHeight(); + } + // arrowRect + if (arrowIcon != null) { + arrowSize.width = arrowIcon.getIconWidth(); + arrowSize.height = arrowIcon.getIconHeight(); + } + } + + // labelRect + if (isColumnLayout) { + labelSize.width = iconSize.width + textSize.width + gap; + labelSize.height = max(checkSize.height, iconSize.height, + textSize.height, accSize.height, arrowSize.height); + } else { + Rectangle textRect = new Rectangle(); + Rectangle iconRect = new Rectangle(); + SwingUtilities.layoutCompoundLabel(mi, fm, text, icon, + verticalAlignment, horizontalAlignment, + verticalTextPosition, horizontalTextPosition, + viewRect, iconRect, textRect, gap); + Rectangle labelRect = iconRect.union(textRect); + labelSize.height = labelRect.height; + labelSize.width = labelRect.width; + } + } + + protected void calcMaxWidths() { + calcMaxWidth(checkSize, MAX_CHECK_WIDTH); + calcMaxWidth(arrowSize, MAX_ARROW_WIDTH); + calcMaxWidth(accSize, MAX_ACC_WIDTH); + + if (isColumnLayout) { + calcMaxWidth(iconSize, MAX_ICON_WIDTH); + calcMaxWidth(textSize, MAX_TEXT_WIDTH); + int curGap = gap; + if ((iconSize.getMaxWidth() == 0) + || (textSize.getMaxWidth() == 0)) { + curGap = 0; + } + labelSize.maxWidth = + calcMaxValue(MAX_LABEL_WIDTH, iconSize.maxWidth + + textSize.maxWidth + curGap); + } else { + // We shouldn't use current icon and text widths + // in maximal widths calculation for complex layout. + iconSize.maxWidth = getParentIntProperty(MAX_ICON_WIDTH); + calcMaxWidth(labelSize, MAX_LABEL_WIDTH); + // If maxLabelWidth is wider + // than the widest icon + the widest text + gap, + // we should update the maximal text witdh + int candidateTextWidth = labelSize.maxWidth - iconSize.maxWidth; + if (iconSize.maxWidth > 0) { + candidateTextWidth -= gap; + } + textSize.maxWidth = calcMaxValue(MAX_TEXT_WIDTH, candidateTextWidth); + } + } + + protected void calcMaxWidth(RectSize rs, Object key) { + rs.maxWidth = calcMaxValue(key, rs.width); + } + + /** + * Calculates and returns maximal value through specified parent component + * client property. + * + * @param propertyName name of the property, which stores the maximal value. + * @param value a value which pretends to be maximal + * @return maximal value among the parent property and the value. + */ + protected int calcMaxValue(Object propertyName, int value) { + // Get maximal value from parent client property + int maxValue = getParentIntProperty(propertyName); + // Store new maximal width in parent client property + if (value > maxValue) { + if (miParent != null) { + miParent.putClientProperty(propertyName, value); + } + return value; + } else { + return maxValue; + } + } + + /** + * Returns parent client property as int. + * @param propertyName name of the parent property. + * @return value of the property as int. + */ + protected int getParentIntProperty(Object propertyName) { + Object value = null; + if (miParent != null) { + value = miParent.getClientProperty(propertyName); + } + if ((value == null) || !(value instanceof Integer)) { + value = 0; + } + return (Integer) value; + } + + public static boolean isColumnLayout(boolean isLeftToRight, + JMenuItem mi) { + assert(mi != null); + return isColumnLayout(isLeftToRight, mi.getHorizontalAlignment(), + mi.getHorizontalTextPosition(), mi.getVerticalTextPosition()); + } + + /** + * Answers should we do column layout for a menu item or not. + * We do it when a user doesn't set any alignments + * and text positions manually, except the vertical alignment. + */ + public static boolean isColumnLayout(boolean isLeftToRight, + int horizontalAlignment, + int horizontalTextPosition, + int verticalTextPosition) { + if (verticalTextPosition != SwingConstants.CENTER) { + return false; + } + if (isLeftToRight) { + if (horizontalAlignment != SwingConstants.LEADING + && horizontalAlignment != SwingConstants.LEFT) { + return false; + } + if (horizontalTextPosition != SwingConstants.TRAILING + && horizontalTextPosition != SwingConstants.RIGHT) { + return false; + } + } else { + if (horizontalAlignment != SwingConstants.LEADING + && horizontalAlignment != SwingConstants.RIGHT) { + return false; + } + if (horizontalTextPosition != SwingConstants.TRAILING + && horizontalTextPosition != SwingConstants.LEFT) { + return false; + } + } + return true; + } + + /** + * Calculates maximal text offset. + * It is required for some L&Fs (ex: Vista L&F). + * The offset is meaningful only for L2R column layout. + * + * @param viewRect the rectangle, the maximal text offset + * will be calculated for. + */ + private void calcMaxTextOffset(Rectangle viewRect) { + if (!isColumnLayout || !isLeftToRight) { + return; + } + + // Calculate the current text offset + int offset = viewRect.x + leadingGap + checkSize.maxWidth + + afterCheckIconGap + iconSize.maxWidth + gap; + if (checkSize.maxWidth == 0) { + offset -= afterCheckIconGap; + } + if (iconSize.maxWidth == 0) { + offset -= gap; + } + + // maximal text offset shouldn't be less than minimal text offset; + if (offset < minTextOffset) { + offset = minTextOffset; + } + + // Calculate and store the maximal text offset + calcMaxValue(SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET, offset); + } + + /** + * Layout icon, text, check icon, accelerator text and arrow icon + * in the viewRect and return their positions. + * + * If horizontalAlignment, verticalTextPosition and horizontalTextPosition + * are default (user doesn't set any manually) the layouting algorithm is: + * Elements are layouted in the five columns: + * check icon + icon + text + accelerator text + arrow icon + * + * In the other case elements are layouted in the four columns: + * check icon + label + accelerator text + arrow icon + * Label is union of icon and text. + * + * The order of columns can be reversed. + * It depends on the menu item orientation. + */ + public LayoutResult layoutMenuItem() { + LayoutResult lr = createLayoutResult(); + prepareForLayout(lr); + + if (isColumnLayout()) { + if (isLeftToRight()) { + doLTRColumnLayout(lr, getLTRColumnAlignment()); + } else { + doRTLColumnLayout(lr, getRTLColumnAlignment()); + } + } else { + if (isLeftToRight()) { + doLTRComplexLayout(lr, getLTRColumnAlignment()); + } else { + doRTLComplexLayout(lr, getRTLColumnAlignment()); + } + } + + alignAccCheckAndArrowVertically(lr); + return lr; + } + + private LayoutResult createLayoutResult() { + return new LayoutResult( + new Rectangle(iconSize.width, iconSize.height), + new Rectangle(textSize.width, textSize.height), + new Rectangle(accSize.width, accSize.height), + new Rectangle(checkSize.width, checkSize.height), + new Rectangle(arrowSize.width, arrowSize.height), + new Rectangle(labelSize.width, labelSize.height) + ); + } + + public ColumnAlignment getLTRColumnAlignment() { + return ColumnAlignment.LEFT_ALIGNMENT; + } + + public ColumnAlignment getRTLColumnAlignment() { + return ColumnAlignment.RIGHT_ALIGNMENT; + } + + protected void prepareForLayout(LayoutResult lr) { + lr.checkRect.width = checkSize.maxWidth; + lr.accRect.width = accSize.maxWidth; + lr.arrowRect.width = arrowSize.maxWidth; + } + + /** + * Aligns the accelertor text and the check and arrow icons vertically + * with the center of the label rect. + */ + private void alignAccCheckAndArrowVertically(LayoutResult lr) { + lr.accRect.y = (int)(lr.labelRect.y + + (float)lr.labelRect.height/2 + - (float)lr.accRect.height/2); + fixVerticalAlignment(lr, lr.accRect); + if (useCheckAndArrow) { + lr.arrowRect.y = (int)(lr.labelRect.y + + (float)lr.labelRect.height/2 + - (float)lr.arrowRect.height/2); + lr.checkRect.y = (int)(lr.labelRect.y + + (float)lr.labelRect.height/2 + - (float)lr.checkRect.height/2); + fixVerticalAlignment(lr, lr.arrowRect); + fixVerticalAlignment(lr, lr.checkRect); + } + } + + /** + * Fixes vertical alignment of all menu item elements if rect.y + * or (rect.y + rect.height) is out of viewRect bounds + */ + private void fixVerticalAlignment(LayoutResult lr, Rectangle r) { + int delta = 0; + if (r.y < viewRect.y) { + delta = viewRect.y - r.y; + } else if (r.y + r.height > viewRect.y + viewRect.height) { + delta = viewRect.y + viewRect.height - r.y - r.height; + } + if (delta != 0) { + lr.checkRect.y += delta; + lr.iconRect.y += delta; + lr.textRect.y += delta; + lr.accRect.y += delta; + lr.arrowRect.y += delta; + lr.labelRect.y += delta; + } + } + + private void doLTRColumnLayout(LayoutResult lr, ColumnAlignment alignment) { + // Set maximal width for all the five basic rects + // (three other ones are already maximal) + lr.iconRect.width = iconSize.maxWidth; + lr.textRect.width = textSize.maxWidth; + + // Set X coordinates + // All rects will be aligned at the left side + calcXPositionsLTR(viewRect.x, leadingGap, gap, lr.checkRect, + lr.iconRect, lr.textRect); + + // Tune afterCheckIconGap + if (lr.checkRect.width > 0) { // there is the afterCheckIconGap + lr.iconRect.x += afterCheckIconGap - gap; + lr.textRect.x += afterCheckIconGap - gap; + } + + calcXPositionsRTL(viewRect.x + viewRect.width, leadingGap, gap, + lr.arrowRect, lr.accRect); + + // Take into account minimal text offset + int textOffset = lr.textRect.x - viewRect.x; + if (!isTopLevelMenu && (textOffset < minTextOffset)) { + lr.textRect.x += minTextOffset - textOffset; + } + + alignRects(lr, alignment); + + // Take into account the left side bearings for text and accelerator text. + fixTextRects(lr); + + // Set Y coordinate for text and icon. + // Y coordinates for other rects + // will be calculated later in layoutMenuItem. + calcTextAndIconYPositions(lr); + + // Calculate valid X and Y coordinates for labelRect + lr.setLabelRect(lr.textRect.union(lr.iconRect)); + } + + private void doLTRComplexLayout(LayoutResult lr, ColumnAlignment alignment) { + lr.labelRect.width = labelSize.maxWidth; + + // Set X coordinates + calcXPositionsLTR(viewRect.x, leadingGap, gap, lr.checkRect, + lr.labelRect); + + // Tune afterCheckIconGap + if (lr.checkRect.width > 0) { // there is the afterCheckIconGap + lr.labelRect.x += afterCheckIconGap - gap; + } + + calcXPositionsRTL(viewRect.x + viewRect.width, + leadingGap, gap, lr.arrowRect, lr.accRect); + + // Take into account minimal text offset + int labelOffset = lr.labelRect.x - viewRect.x; + if (!isTopLevelMenu && (labelOffset < minTextOffset)) { + lr.labelRect.x += minTextOffset - labelOffset; + } + + alignRects(lr, alignment); + + // Take into account the left side bearing for accelerator text. + // The LSB for text is taken into account in layoutCompoundLabel() below. + fixAccTextRect(lr); + + // Center labelRect vertically + calcLabelYPosition(lr); + + layoutIconAndTextInLabelRect(lr); + } + + private void doRTLColumnLayout(LayoutResult lr, ColumnAlignment alignment) { + // Set maximal width for all the five basic rects + // (three other ones are already maximal) + lr.iconRect.width = iconSize.maxWidth; + lr.textRect.width = textSize.maxWidth; + + // Set X coordinates + calcXPositionsRTL(viewRect.x + viewRect.width, leadingGap, gap, + lr.checkRect, lr.iconRect, lr.textRect); + + // Tune the gap after check icon + if (lr.checkRect.width > 0) { // there is the gap after check icon + lr.iconRect.x -= afterCheckIconGap - gap; + lr.textRect.x -= afterCheckIconGap - gap; + } + + calcXPositionsLTR(viewRect.x, leadingGap, gap, lr.arrowRect, + lr.accRect); + + // Take into account minimal text offset + int textOffset = (viewRect.x + viewRect.width) + - (lr.textRect.x + lr.textRect.width); + if (!isTopLevelMenu && (textOffset < minTextOffset)) { + lr.textRect.x -= minTextOffset - textOffset; + } + + alignRects(lr, alignment); + + // Take into account the left side bearings for text and accelerator text. + fixTextRects(lr); + + // Set Y coordinates for text and icon. + // Y coordinates for other rects + // will be calculated later in layoutMenuItem. + calcTextAndIconYPositions(lr); + + // Calculate valid X and Y coordinate for labelRect + lr.setLabelRect(lr.textRect.union(lr.iconRect)); + } + + private void doRTLComplexLayout(LayoutResult lr, ColumnAlignment alignment) { + lr.labelRect.width = labelSize.maxWidth; + + // Set X coordinates + calcXPositionsRTL(viewRect.x + viewRect.width, leadingGap, gap, + lr.checkRect, lr.labelRect); + + // Tune the gap after check icon + if (lr.checkRect.width > 0) { // there is the gap after check icon + lr.labelRect.x -= afterCheckIconGap - gap; + } + + calcXPositionsLTR(viewRect.x, leadingGap, gap, lr.arrowRect, lr.accRect); + + // Take into account minimal text offset + int labelOffset = (viewRect.x + viewRect.width) + - (lr.labelRect.x + lr.labelRect.width); + if (!isTopLevelMenu && (labelOffset < minTextOffset)) { + lr.labelRect.x -= minTextOffset - labelOffset; + } + + alignRects(lr, alignment); + + // Take into account the left side bearing for accelerator text. + // The LSB for text is taken into account in layoutCompoundLabel() below. + fixAccTextRect(lr); + + // Center labelRect vertically + calcLabelYPosition(lr); + + layoutIconAndTextInLabelRect(lr); + } + + private void alignRects(LayoutResult lr, ColumnAlignment alignment) { + alignRect(lr.checkRect, alignment.getCheckAlignment(), + checkSize.getOrigWidth()); + alignRect(lr.iconRect, alignment.getIconAlignment(), + iconSize.getOrigWidth()); + alignRect(lr.textRect, alignment.getTextAlignment(), + textSize.getOrigWidth()); + alignRect(lr.accRect, alignment.getAccAlignment(), + accSize.getOrigWidth()); + alignRect(lr.arrowRect, alignment.getArrowAlignment(), + arrowSize.getOrigWidth()); + } + + private void alignRect(Rectangle rect, int alignment, int origWidth) { + if (alignment != SwingUtilities.LEFT) { + rect.x = rect.x + rect.width - origWidth; + rect.width = origWidth; + } + } + + protected void layoutIconAndTextInLabelRect(LayoutResult lr) { + lr.setTextRect(new Rectangle()); + lr.setIconRect(new Rectangle()); + SwingUtilities.layoutCompoundLabel( + mi, fm, text,icon, verticalAlignment, horizontalAlignment, + verticalTextPosition, horizontalTextPosition, lr.labelRect, + lr.iconRect, lr.textRect, gap); + } + + private void calcXPositionsLTR(int startXPos, int leadingGap, + int gap, Rectangle... rects) { + int curXPos = startXPos + leadingGap; + for (Rectangle rect : rects) { + rect.x = curXPos; + if (rect.width > 0) { + curXPos += rect.width + gap; + } + } + } + + private void calcXPositionsRTL(int startXPos, int leadingGap, + int gap, Rectangle... rects) { + int curXPos = startXPos - leadingGap; + for (Rectangle rect : rects) { + rect.x = curXPos - rect.width; + if (rect.width > 0) { + curXPos -= rect.width + gap; + } + } + } + + /** + * Takes into account the left side bearings for text and accelerator text + */ + private void fixTextRects(LayoutResult lr) { + if (htmlView == null) { // The text isn't a HTML + int lsb = SwingUtilities2.getLeftSideBearing(mi, fm, text); + if (lsb < 0) { + lr.textRect.x -= lsb; + } + } + fixAccTextRect(lr); + } + + /** + * Takes into account the left side bearing for accelerator text + */ + private void fixAccTextRect(LayoutResult lr) { + int lsb = SwingUtilities2.getLeftSideBearing(mi, accFm, accText); + if (lsb < 0) { + lr.accRect.x -= lsb; + } + } + + /** + * Sets Y coordinates of text and icon + * taking into account the vertical alignment + */ + private void calcTextAndIconYPositions(LayoutResult lr) { + if (verticalAlignment == SwingUtilities.TOP) { + lr.textRect.y = (int)(viewRect.y + + (float)lr.labelRect.height/2 + - (float)lr.textRect.height/2); + lr.iconRect.y = (int)(viewRect.y + + (float)lr.labelRect.height/2 + - (float)lr.iconRect.height/2); + } else if (verticalAlignment == SwingUtilities.CENTER) { + lr.textRect.y = (int)(viewRect.y + + (float)viewRect.height/2 + - (float)lr.textRect.height/2); + lr.iconRect.y = (int)(viewRect.y + + (float)viewRect.height/2 + - (float)lr.iconRect.height/2); + } + else if (verticalAlignment == SwingUtilities.BOTTOM) { + lr.textRect.y = (int)(viewRect.y + + viewRect.height + - (float)lr.labelRect.height/2 + - (float)lr.textRect.height/2); + lr.iconRect.y = (int)(viewRect.y + + viewRect.height + - (float)lr.labelRect.height/2 + - (float)lr.iconRect.height/2); + } + } + + /** + * Sets labelRect Y coordinate + * taking into account the vertical alignment + */ + private void calcLabelYPosition(LayoutResult lr) { + if (verticalAlignment == SwingUtilities.TOP) { + lr.labelRect.y = viewRect.y; + } else if (verticalAlignment == SwingUtilities.CENTER) { + lr.labelRect.y = (int)(viewRect.y + + (float)viewRect.height/2 + - (float)lr.labelRect.height/2); + } else if (verticalAlignment == SwingUtilities.BOTTOM) { + lr.labelRect.y = viewRect.y + viewRect.height + - lr.labelRect.height; + } + } + + /** + * Returns parent of this component if it is not a top-level menu + * Otherwise returns null. + * @param menuItem the menu item whose parent will be returned. + * @return parent of this component if it is not a top-level menu + * Otherwise returns null. + */ + public static JComponent getMenuItemParent(JMenuItem menuItem) { + Container parent = menuItem.getParent(); + if ((parent instanceof JComponent) && + (!(menuItem instanceof JMenu) || + !((JMenu)menuItem).isTopLevelMenu())) { + return (JComponent) parent; + } else { + return null; + } + } + + public static void clearUsedParentClientProperties(JMenuItem menuItem) { + clearUsedClientProperties(getMenuItemParent(menuItem)); + } + + public static void clearUsedClientProperties(JComponent c) { + if (c != null) { + c.putClientProperty(MAX_ARROW_WIDTH, null); + c.putClientProperty(MAX_CHECK_WIDTH, null); + c.putClientProperty(MAX_ACC_WIDTH, null); + c.putClientProperty(MAX_TEXT_WIDTH, null); + c.putClientProperty(MAX_ICON_WIDTH, null); + c.putClientProperty(MAX_LABEL_WIDTH, null); + c.putClientProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET, null); + } + } + + /** + * Finds and returns maximal integer value in the given array. + * @param values array where the search will be performed. + * @return maximal vaule. + */ + public static int max(int... values) { + int maxValue = Integer.MIN_VALUE; + for (int i : values) { + if (i > maxValue) { + maxValue = i; + } + } + return maxValue; + } + + public static Rectangle createMaxRect() { + return new Rectangle(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE); + } + + public static void addMaxWidth(RectSize size, int gap, Dimension result) { + if (size.maxWidth > 0) { + result.width += size.maxWidth + gap; + } + } + + public static void addWidth(int width, int gap, Dimension result) { + if (width > 0) { + result.width += width + gap; + } + } + + public JMenuItem getMenuItem() { + return mi; + } + + public JComponent getMenuItemParent() { + return miParent; + } + + public Font getFont() { + return font; + } + + public Font getAccFont() { + return accFont; + } + + public FontMetrics getFontMetrics() { + return fm; + } + + public FontMetrics getAccFontMetrics() { + return accFm; + } + + public Icon getIcon() { + return icon; + } + + public Icon getCheckIcon() { + return checkIcon; + } + + public Icon getArrowIcon() { + return arrowIcon; + } + + public String getText() { + return text; + } + + public String getAccText() { + return accText; + } + + public boolean isColumnLayout() { + return isColumnLayout; + } + + public boolean useCheckAndArrow() { + return useCheckAndArrow; + } + + public boolean isLeftToRight() { + return isLeftToRight; + } + + public boolean isTopLevelMenu() { + return isTopLevelMenu; + } + + public View getHtmlView() { + return htmlView; + } + + public int getVerticalAlignment() { + return verticalAlignment; + } + + public int getHorizontalAlignment() { + return horizontalAlignment; + } + + public int getVerticalTextPosition() { + return verticalTextPosition; + } + + public int getHorizontalTextPosition() { + return horizontalTextPosition; + } + + public int getGap() { + return gap; + } + + public int getLeadingGap() { + return leadingGap; + } + + public int getAfterCheckIconGap() { + return afterCheckIconGap; + } + + public int getMinTextOffset() { + return minTextOffset; + } + + public Rectangle getViewRect() { + return viewRect; + } + + public RectSize getIconSize() { + return iconSize; + } + + public RectSize getTextSize() { + return textSize; + } + + public RectSize getAccSize() { + return accSize; + } + + public RectSize getCheckSize() { + return checkSize; + } + + public RectSize getArrowSize() { + return arrowSize; + } + + public RectSize getLabelSize() { + return labelSize; + } + + protected void setMenuItem(JMenuItem mi) { + this.mi = mi; + } + + protected void setMenuItemParent(JComponent miParent) { + this.miParent = miParent; + } + + protected void setFont(Font font) { + this.font = font; + } + + protected void setAccFont(Font accFont) { + this.accFont = accFont; + } + + protected void setFontMetrics(FontMetrics fm) { + this.fm = fm; + } + + protected void setAccFontMetrics(FontMetrics accFm) { + this.accFm = accFm; + } + + protected void setIcon(Icon icon) { + this.icon = icon; + } + + protected void setCheckIcon(Icon checkIcon) { + this.checkIcon = checkIcon; + } + + protected void setArrowIcon(Icon arrowIcon) { + this.arrowIcon = arrowIcon; + } + + protected void setText(String text) { + this.text = text; + } + + protected void setAccText(String accText) { + this.accText = accText; + } + + protected void setColumnLayout(boolean columnLayout) { + isColumnLayout = columnLayout; + } + + protected void setUseCheckAndArrow(boolean useCheckAndArrow) { + this.useCheckAndArrow = useCheckAndArrow; + } + + protected void setLeftToRight(boolean leftToRight) { + isLeftToRight = leftToRight; + } + + protected void setTopLevelMenu(boolean topLevelMenu) { + isTopLevelMenu = topLevelMenu; + } + + protected void setHtmlView(View htmlView) { + this.htmlView = htmlView; + } + + protected void setVerticalAlignment(int verticalAlignment) { + this.verticalAlignment = verticalAlignment; + } + + protected void setHorizontalAlignment(int horizontalAlignment) { + this.horizontalAlignment = horizontalAlignment; + } + + protected void setVerticalTextPosition(int verticalTextPosition) { + this.verticalTextPosition = verticalTextPosition; + } + + protected void setHorizontalTextPosition(int horizontalTextPosition) { + this.horizontalTextPosition = horizontalTextPosition; + } + + protected void setGap(int gap) { + this.gap = gap; + } + + protected void setLeadingGap(int leadingGap) { + this.leadingGap = leadingGap; + } + + protected void setAfterCheckIconGap(int afterCheckIconGap) { + this.afterCheckIconGap = afterCheckIconGap; + } + + protected void setMinTextOffset(int minTextOffset) { + this.minTextOffset = minTextOffset; + } + + protected void setViewRect(Rectangle viewRect) { + this.viewRect = viewRect; + } + + protected void setIconSize(RectSize iconSize) { + this.iconSize = iconSize; + } + + protected void setTextSize(RectSize textSize) { + this.textSize = textSize; + } + + protected void setAccSize(RectSize accSize) { + this.accSize = accSize; + } + + protected void setCheckSize(RectSize checkSize) { + this.checkSize = checkSize; + } + + protected void setArrowSize(RectSize arrowSize) { + this.arrowSize = arrowSize; + } + + protected void setLabelSize(RectSize labelSize) { + this.labelSize = labelSize; + } + + /** + * Returns false if the component is a JMenu and it is a top + * level menu (on the menubar). + */ + public static boolean useCheckAndArrow(JMenuItem menuItem) { + boolean b = true; + if ((menuItem instanceof JMenu) && + (((JMenu) menuItem).isTopLevelMenu())) { + b = false; + } + return b; + } + + public static class LayoutResult { + private Rectangle iconRect; + private Rectangle textRect; + private Rectangle accRect; + private Rectangle checkRect; + private Rectangle arrowRect; + private Rectangle labelRect; + + public LayoutResult() { + iconRect = new Rectangle(); + textRect = new Rectangle(); + accRect = new Rectangle(); + checkRect = new Rectangle(); + arrowRect = new Rectangle(); + labelRect = new Rectangle(); + } + + public LayoutResult(Rectangle iconRect, Rectangle textRect, + Rectangle accRect, Rectangle checkRect, + Rectangle arrowRect, Rectangle labelRect) { + this.iconRect = iconRect; + this.textRect = textRect; + this.accRect = accRect; + this.checkRect = checkRect; + this.arrowRect = arrowRect; + this.labelRect = labelRect; + } + + public Rectangle getIconRect() { + return iconRect; + } + + public void setIconRect(Rectangle iconRect) { + this.iconRect = iconRect; + } + + public Rectangle getTextRect() { + return textRect; + } + + public void setTextRect(Rectangle textRect) { + this.textRect = textRect; + } + + public Rectangle getAccRect() { + return accRect; + } + + public void setAccRect(Rectangle accRect) { + this.accRect = accRect; + } + + public Rectangle getCheckRect() { + return checkRect; + } + + public void setCheckRect(Rectangle checkRect) { + this.checkRect = checkRect; + } + + public Rectangle getArrowRect() { + return arrowRect; + } + + public void setArrowRect(Rectangle arrowRect) { + this.arrowRect = arrowRect; + } + + public Rectangle getLabelRect() { + return labelRect; + } + + public void setLabelRect(Rectangle labelRect) { + this.labelRect = labelRect; + } + + public Map getAllRects() { + Map result = new HashMap(); + result.put("checkRect", checkRect); + result.put("iconRect", iconRect); + result.put("textRect", textRect); + result.put("accRect", accRect); + result.put("arrowRect", arrowRect); + result.put("labelRect", labelRect); + return result; + } + } + + public static class ColumnAlignment { + private int checkAlignment; + private int iconAlignment; + private int textAlignment; + private int accAlignment; + private int arrowAlignment; + + public static final ColumnAlignment LEFT_ALIGNMENT = + new ColumnAlignment( + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT + ); + + public static final ColumnAlignment RIGHT_ALIGNMENT = + new ColumnAlignment( + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT + ); + + public ColumnAlignment(int checkAlignment, int iconAlignment, + int textAlignment, int accAlignment, + int arrowAlignment) { + this.checkAlignment = checkAlignment; + this.iconAlignment = iconAlignment; + this.textAlignment = textAlignment; + this.accAlignment = accAlignment; + this.arrowAlignment = arrowAlignment; + } + + public int getCheckAlignment() { + return checkAlignment; + } + + public int getIconAlignment() { + return iconAlignment; + } + + public int getTextAlignment() { + return textAlignment; + } + + public int getAccAlignment() { + return accAlignment; + } + + public int getArrowAlignment() { + return arrowAlignment; + } + } + + public static class RectSize { + private int width; + private int height; + private int origWidth; + private int maxWidth; + + public RectSize() { + } + + public RectSize(int width, int height, int origWidth, int maxWidth) { + this.width = width; + this.height = height; + this.origWidth = origWidth; + this.maxWidth = maxWidth; + } + + public int getWidth() { + return width; + } + + public int getHeight() { + return height; + } + + public int getOrigWidth() { + return origWidth; + } + + public int getMaxWidth() { + return maxWidth; + } + + public void setWidth(int width) { + this.width = width; + } + + public void setHeight(int height) { + this.height = height; + } + + public void setOrigWidth(int origWidth) { + this.origWidth = origWidth; + } + + public void setMaxWidth(int maxWidth) { + this.maxWidth = maxWidth; + } + + public String toString() { + return "[w=" + width + ",h=" + height + ",ow=" + + origWidth + ",mw=" + maxWidth + "]"; + } + } +} From 3b50ea90031e04f1f43b9a960ed532956d5a1b14 Mon Sep 17 00:00:00 2001 From: Pavel Porvatov Date: Mon, 11 Aug 2008 16:39:17 +0400 Subject: [PATCH 25/45] 6604281: NimbusL&F :Regression in Focus traversal in JFileChooser in pit build Fixed calculation of preferred size in SynthButtonUI Reviewed-by: loneid, peterz --- .../javax/swing/plaf/synth/SynthButtonUI.java | 6 +- .../swing/JButton/6604281/bug6604281.java | 76 +++++++++++++++++++ 2 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 jdk/test/javax/swing/JButton/6604281/bug6604281.java diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java index 78dd60bd3e3..e0f057e9037 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java @@ -262,7 +262,7 @@ class SynthButtonUI extends BasicButtonUI implements * Returns the default icon. This should NOT callback * to the JComponent. * - * @param b AbstractButton the iocn is associated with + * @param b AbstractButton the icon is associated with * @return default icon */ @@ -445,9 +445,7 @@ class SynthButtonUI extends BasicButtonUI implements * Returns the Icon used in calculating the pref/min/max size. */ protected Icon getSizingIcon(AbstractButton b) { - // NOTE: this is slightly different than BasicButtonUI, where it - // would just use getIcon, but this should be ok. - Icon icon = (b.isEnabled()) ? b.getIcon() : b.getDisabledIcon(); + Icon icon = getEnabledIcon(b, b.getIcon()); if (icon == null) { icon = getDefaultIcon(b); } diff --git a/jdk/test/javax/swing/JButton/6604281/bug6604281.java b/jdk/test/javax/swing/JButton/6604281/bug6604281.java new file mode 100644 index 00000000000..dec89f778c6 --- /dev/null +++ b/jdk/test/javax/swing/JButton/6604281/bug6604281.java @@ -0,0 +1,76 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + @bug 6604281 + @summary NimbusL&F :Regression in Focus traversal in JFileChooser in pit build + @author Pavel Porvatov + @run main bug6604281 +*/ + +import javax.swing.*; +import javax.swing.plaf.IconUIResource; +import javax.swing.plaf.synth.SynthLookAndFeel; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.lang.reflect.InvocationTargetException; + +public class bug6604281 { + public static void main(String[] args) throws InvocationTargetException, InterruptedException { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + SynthLookAndFeel laf = new SynthLookAndFeel(); + try { + UIManager.setLookAndFeel(laf); + } catch (Exception e) { + fail(e.getMessage()); + } + + // Prepare image + BufferedImage image = new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB); + + Graphics2D graphics = (Graphics2D) image.getGraphics(); + + graphics.setColor(Color.BLUE); + graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); + graphics.setColor(Color.RED); + graphics.drawLine(0, 0, image.getWidth(), image.getHeight()); + + // Use IconUIResource as an icon, because with ImageIcon bug is not reproduced + JButton button1 = new JButton(new IconUIResource(new ImageIcon(image))); + + JButton button2 = new JButton(new IconUIResource(new ImageIcon(image))); + + button2.setEnabled(false); + + if (button1.getPreferredSize().getHeight() != button2.getPreferredSize().getHeight()) { + fail("Two similar buttons have different size"); + } + } + }); + } + + private static void fail(String s) { + throw new RuntimeException("Test failed: " + s); + } +} From aeb1b5f21c490afb0d0a6fbeec7e042965a6fa4f Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Mon, 11 Aug 2008 16:49:46 +0400 Subject: [PATCH 26/45] 6579243: Windows, GTK: Internal frame title is drawn wrong if the frame has RTL orientation Added right-to-left code branches to WindowsInternalFrameTitlePane and Metacity classes Reviewed-by: alexp --- .../com/sun/java/swing/plaf/gtk/Metacity.java | 109 ++++++++++++------ .../WindowsInternalFrameTitlePane.java | 57 ++++++--- .../synth/SynthInternalFrameTitlePane.java | 2 +- 3 files changed, 116 insertions(+), 52 deletions(-) diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java index e6117989134..95de6cad6c5 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java @@ -770,33 +770,56 @@ class Metacity implements SynthConstants { JComponent maximizeButton = findChild(titlePane, "InternalFrameTitlePane.maximizeButton"); JComponent closeButton = findChild(titlePane, "InternalFrameTitlePane.closeButton"); - int buttonGap = 0; - Insets button_border = (Insets)gm.get("button_border"); Dimension buttonDim = calculateButtonSize(titlePane); - int x = getInt("left_titlebar_edge"); int y = (button_border != null) ? button_border.top : 0; + if (titlePaneParent.getComponentOrientation().isLeftToRight()) { + int x = getInt("left_titlebar_edge"); - menuButton.setBounds(x, y, buttonDim.width, buttonDim.height); + menuButton.setBounds(x, y, buttonDim.width, buttonDim.height); - x = w - buttonDim.width - getInt("right_titlebar_edge"); - if (button_border != null) { - x -= button_border.right; - } + x = w - buttonDim.width - getInt("right_titlebar_edge"); + if (button_border != null) { + x -= button_border.right; + } - if (frame.isClosable()) { - closeButton.setBounds(x, y, buttonDim.width, buttonDim.height); - x -= (buttonDim.width + buttonGap); - } + if (frame.isClosable()) { + closeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + x -= buttonDim.width; + } - if (frame.isMaximizable()) { - maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); - x -= (buttonDim.width + buttonGap); - } + if (frame.isMaximizable()) { + maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + x -= buttonDim.width; + } - if (frame.isIconifiable()) { - minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + if (frame.isIconifiable()) { + minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + } + } else { + int x = w - buttonDim.width - getInt("right_titlebar_edge"); + + menuButton.setBounds(x, y, buttonDim.width, buttonDim.height); + + x = getInt("left_titlebar_edge"); + if (button_border != null) { + x += button_border.left; + } + + if (frame.isClosable()) { + closeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + x += buttonDim.width; + } + + if (frame.isMaximizable()) { + maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + x += buttonDim.width; + } + + if (frame.isIconifiable()) { + minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + } } } } // end TitlePaneLayout @@ -973,10 +996,8 @@ class Metacity implements SynthConstants { String title = jif.getTitle(); if (title != null) { FontMetrics fm = SwingUtilities2.getFontMetrics(jif, g); - if (jif.getComponentOrientation().isLeftToRight()) { - title = SwingUtilities2.clipStringIfNecessary(jif, fm, title, - calculateTitleTextWidth(g, jif)); - } + title = SwingUtilities2.clipStringIfNecessary(jif, fm, title, + calculateTitleArea(jif).width); g.setColor(color); SwingUtilities2.drawString(jif, g, title, x, y + fm.getAscent()); } @@ -1010,9 +1031,10 @@ class Metacity implements SynthConstants { JComponent titlePane = findChild(jif, "InternalFrame.northPane"); Dimension buttonDim = calculateButtonSize(titlePane); Insets title_border = (Insets)frameGeometry.get("title_border"); - Rectangle r = new Rectangle(); + Insets button_border = (Insets)getFrameGeometry().get("button_border"); - r.x = getInt("left_titlebar_edge") + buttonDim.width; + Rectangle r = new Rectangle(); + r.x = getInt("left_titlebar_edge"); r.y = 0; r.height = titlePane.getHeight(); if (title_border != null) { @@ -1021,15 +1043,36 @@ class Metacity implements SynthConstants { r.height -= (title_border.top + title_border.bottom); } - r.width = titlePane.getWidth() - r.x - getInt("right_titlebar_edge"); - if (jif.isClosable()) { - r.width -= buttonDim.width; - } - if (jif.isMaximizable()) { - r.width -= buttonDim.width; - } - if (jif.isIconifiable()) { - r.width -= buttonDim.width; + if (titlePane.getParent().getComponentOrientation().isLeftToRight()) { + r.x += buttonDim.width; + if (button_border != null) { + r.x += button_border.left; + } + r.width = titlePane.getWidth() - r.x - getInt("right_titlebar_edge"); + if (jif.isClosable()) { + r.width -= buttonDim.width; + } + if (jif.isMaximizable()) { + r.width -= buttonDim.width; + } + if (jif.isIconifiable()) { + r.width -= buttonDim.width; + } + } else { + if (jif.isClosable()) { + r.x += buttonDim.width; + } + if (jif.isMaximizable()) { + r.x += buttonDim.width; + } + if (jif.isIconifiable()) { + r.x += buttonDim.width; + } + r.width = titlePane.getWidth() - r.x - getInt("right_titlebar_edge") + - buttonDim.width; + if (button_border != null) { + r.x -= button_border.right; + } } if (title_border != null) { r.width -= title_border.right; diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java index 63d853a284d..5222cd5dd08 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java @@ -137,25 +137,46 @@ public class WindowsInternalFrameTitlePane extends BasicInternalFrameTitlePane { int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; - int titleX; - Rectangle r = new Rectangle(0, 0, 0, 0); - if (frame.isIconifiable()) r = iconButton.getBounds(); - else if (frame.isMaximizable()) r = maxButton.getBounds(); - else if (frame.isClosable()) r = closeButton.getBounds(); - int titleW; - - if(WindowsGraphicsUtils.isLeftToRight(frame) ) { - if (r.x == 0) r.x = frame.getWidth()-frame.getInsets().right; - titleX = systemLabel.getX() + systemLabel.getWidth() + 2; - if (xp != null) { - titleX += 2; - } - titleW = r.x - titleX - 3; - title = getTitle(frame.getTitle(), fm, titleW); - } else { - titleX = systemLabel.getX() - 2 - - SwingUtilities2.stringWidth(frame,fm,title); + Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); + if (frame.isIconifiable()) { + lastIconBounds = iconButton.getBounds(); + } else if (frame.isMaximizable()) { + lastIconBounds = maxButton.getBounds(); + } else if (frame.isClosable()) { + lastIconBounds = closeButton.getBounds(); } + + int titleX; + int titleW; + int gap = 2; + if (WindowsGraphicsUtils.isLeftToRight(frame)) { + if (lastIconBounds.x == 0) { // There are no icons + lastIconBounds.x = frame.getWidth() - frame.getInsets().right; + } + titleX = systemLabel.getX() + systemLabel.getWidth() + gap; + if (xp != null) { + titleX += 2; + } + titleW = lastIconBounds.x - titleX - gap; + } else { + if (lastIconBounds.x == 0) { // There are no icons + lastIconBounds.x = frame.getInsets().left; + } + titleW = SwingUtilities2.stringWidth(frame, fm, title); + int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; + if (xp != null) { + minTitleX += 2; + } + int availableWidth = systemLabel.getX() - gap - minTitleX; + if (availableWidth > titleW) { + titleX = systemLabel.getX() - gap - titleW; + } else { + titleX = minTitleX; + titleW = availableWidth; + } + } + title = getTitle(frame.getTitle(), fm, titleW); + if (xp != null) { String shadowType = null; if (isSelected) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java index 353c95c0374..f1c888952a4 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java @@ -215,7 +215,7 @@ class SynthInternalFrameTitlePane extends BasicInternalFrameTitlePane protected void showSystemMenu() { Insets insets = frame.getInsets(); if (!frame.isIcon()) { - systemPopupMenu.show(frame, insets.left, getY() + getHeight()); + systemPopupMenu.show(frame, menuButton.getX(), getY() + getHeight()); } else { systemPopupMenu.show(menuButton, getX() - insets.left - insets.right, From 0e5cf24bb35fe7cb5b66b38873d5f7cfb209b389 Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Tue, 12 Aug 2008 12:52:10 +0400 Subject: [PATCH 27/45] 6735918: test/closed/javax/swing/JMenuItem/6458123/bug6458123.java fails on Linux All the bearings-related code is removed from MenuItemLayoutHelper class Reviewed-by: alexp --- .../sun/swing/MenuItemLayoutHelper.java | 37 ------------------- 1 file changed, 37 deletions(-) diff --git a/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java b/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java index 5c4810b8f0e..b1313e43125 100644 --- a/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java +++ b/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java @@ -572,9 +572,6 @@ public class MenuItemLayoutHelper { alignRects(lr, alignment); - // Take into account the left side bearings for text and accelerator text. - fixTextRects(lr); - // Set Y coordinate for text and icon. // Y coordinates for other rects // will be calculated later in layoutMenuItem. @@ -607,10 +604,6 @@ public class MenuItemLayoutHelper { alignRects(lr, alignment); - // Take into account the left side bearing for accelerator text. - // The LSB for text is taken into account in layoutCompoundLabel() below. - fixAccTextRect(lr); - // Center labelRect vertically calcLabelYPosition(lr); @@ -645,9 +638,6 @@ public class MenuItemLayoutHelper { alignRects(lr, alignment); - // Take into account the left side bearings for text and accelerator text. - fixTextRects(lr); - // Set Y coordinates for text and icon. // Y coordinates for other rects // will be calculated later in layoutMenuItem. @@ -680,10 +670,6 @@ public class MenuItemLayoutHelper { alignRects(lr, alignment); - // Take into account the left side bearing for accelerator text. - // The LSB for text is taken into account in layoutCompoundLabel() below. - fixAccTextRect(lr); - // Center labelRect vertically calcLabelYPosition(lr); @@ -741,29 +727,6 @@ public class MenuItemLayoutHelper { } } - /** - * Takes into account the left side bearings for text and accelerator text - */ - private void fixTextRects(LayoutResult lr) { - if (htmlView == null) { // The text isn't a HTML - int lsb = SwingUtilities2.getLeftSideBearing(mi, fm, text); - if (lsb < 0) { - lr.textRect.x -= lsb; - } - } - fixAccTextRect(lr); - } - - /** - * Takes into account the left side bearing for accelerator text - */ - private void fixAccTextRect(LayoutResult lr) { - int lsb = SwingUtilities2.getLeftSideBearing(mi, accFm, accText); - if (lsb < 0) { - lr.accRect.x -= lsb; - } - } - /** * Sets Y coordinates of text and icon * taking into account the vertical alignment From b6db0aad855291a0a0d2ea483259a91ee9d55990 Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Tue, 26 Aug 2008 12:16:23 +0400 Subject: [PATCH 28/45] 6736649: test/closed/javax/swing/JMenuItem/6458123/ManualBug6458123.java fails on Linux Now text bearings are taken into account when labelRect width is calculated Reviewed-by: alexp --- .../plaf/synth/SynthMenuItemLayoutHelper.java | 3 +- .../sun/swing/MenuItemLayoutHelper.java | 38 ++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java index 6b890c786fd..4ca139a709d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java @@ -136,7 +136,7 @@ class SynthMenuItemLayoutHelper extends MenuItemLayoutHelper { // accRect if (!getAccText().equals("")) { - getAccSize().setWidth(accGu.computeStringWidth(getAccContext(), + getAccSize().setWidth(accGu.computeStringWidth(getAccContext(), getAccFontMetrics().getFont(), getAccFontMetrics(), getAccText())); getAccSize().setHeight(getAccFontMetrics().getHeight()); @@ -195,6 +195,7 @@ class SynthMenuItemLayoutHelper extends MenuItemLayoutHelper { getHorizontalAlignment(), getVerticalAlignment(), getHorizontalTextPosition(), getVerticalTextPosition(), getViewRect(), iconRect, textRect, getGap()); + textRect.width += getLeftTextExtraWidth() + getRightTextExtraWidth(); Rectangle labelRect = iconRect.union(textRect); getLabelSize().setHeight(labelRect.height); getLabelSize().setWidth(labelRect.width); diff --git a/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java b/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java index b1313e43125..109d0c4022c 100644 --- a/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java +++ b/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java @@ -83,6 +83,9 @@ public class MenuItemLayoutHelper { private int afterCheckIconGap; private int minTextOffset; + private int leftTextExtraWidth; + private int rightTextExtraWidth; + private Rectangle viewRect; private RectSize iconSize; @@ -143,6 +146,7 @@ public class MenuItemLayoutHelper { this.checkSize = new RectSize(); this.arrowSize = new RectSize(); this.labelSize = new RectSize(); + calcExtraWidths(); calcWidthsAndHeights(); setOriginalWidths(); calcMaxWidths(); @@ -151,6 +155,29 @@ public class MenuItemLayoutHelper { calcMaxTextOffset(viewRect); } + private void calcExtraWidths() { + leftTextExtraWidth = getLeftExtraWidth(text); + rightTextExtraWidth = getRightExtraWidth(text); + } + + private int getLeftExtraWidth(String str) { + int lsb = SwingUtilities2.getLeftSideBearing(mi, fm, str); + if (lsb < 0) { + return -lsb; + } else { + return 0; + } + } + + private int getRightExtraWidth(String str) { + int rsb = SwingUtilities2.getRightSideBearing(mi, fm, str); + if (rsb > 0) { + return rsb; + } else { + return 0; + } + } + private void setOriginalWidths() { iconSize.origWidth = iconSize.width; textSize.origWidth = textSize.width; @@ -286,6 +313,7 @@ public class MenuItemLayoutHelper { verticalAlignment, horizontalAlignment, verticalTextPosition, horizontalTextPosition, viewRect, iconRect, textRect, gap); + textRect.width += leftTextExtraWidth + rightTextExtraWidth; Rectangle labelRect = iconRect.union(textRect); labelSize.height = labelRect.height; labelSize.width = labelRect.width; @@ -727,7 +755,7 @@ public class MenuItemLayoutHelper { } } - /** + /** * Sets Y coordinates of text and icon * taking into account the vertical alignment */ @@ -1089,6 +1117,14 @@ public class MenuItemLayoutHelper { this.labelSize = labelSize; } + public int getLeftTextExtraWidth() { + return leftTextExtraWidth; + } + + public int getRightTextExtraWidth() { + return rightTextExtraWidth; + } + /** * Returns false if the component is a JMenu and it is a top * level menu (on the menubar). From 8bb4a8ec15651dab1bbebbc8a65976ac0f640352 Mon Sep 17 00:00:00 2001 From: Pavel Porvatov Date: Tue, 26 Aug 2008 15:12:54 +0400 Subject: [PATCH 29/45] 6727662: Code improvement and warnings removing from swing packages Removed unnecessary castings and other warnings Reviewed-by: malenkov --- .../classes/javax/swing/AbstractButton.java | 13 +-- .../javax/swing/AbstractCellEditor.java | 3 +- .../javax/swing/AbstractListModel.java | 3 +- .../javax/swing/AbstractSpinnerModel.java | 3 +- .../share/classes/javax/swing/ActionMap.java | 2 +- .../classes/javax/swing/AncestorNotifier.java | 2 +- .../share/classes/javax/swing/ArrayTable.java | 10 +- .../classes/javax/swing/ButtonGroup.java | 2 +- .../javax/swing/DebugGraphicsInfo.java | 6 +- .../javax/swing/DefaultBoundedRangeModel.java | 3 +- .../javax/swing/DefaultButtonModel.java | 8 +- .../javax/swing/DefaultFocusManager.java | 7 +- .../swing/DefaultListSelectionModel.java | 3 +- .../swing/DefaultSingleSelectionModel.java | 3 +- .../classes/javax/swing/GroupLayout.java | 4 +- .../share/classes/javax/swing/InputMap.java | 4 +- .../share/classes/javax/swing/JComboBox.java | 12 +-- .../share/classes/javax/swing/JComponent.java | 47 +++++----- .../classes/javax/swing/JDesktopPane.java | 24 +++-- .../share/classes/javax/swing/JDialog.java | 4 +- .../classes/javax/swing/JEditorPane.java | 44 +++++---- .../classes/javax/swing/JFileChooser.java | 19 ++-- .../classes/javax/swing/JInternalFrame.java | 11 +-- .../classes/javax/swing/JLayeredPane.java | 12 +-- jdk/src/share/classes/javax/swing/JList.java | 15 ++- jdk/src/share/classes/javax/swing/JMenu.java | 28 +++--- .../share/classes/javax/swing/JMenuBar.java | 15 ++- .../share/classes/javax/swing/JMenuItem.java | 10 +- .../classes/javax/swing/JOptionPane.java | 37 ++++---- .../share/classes/javax/swing/JPopupMenu.java | 27 +++--- .../classes/javax/swing/JProgressBar.java | 3 +- .../share/classes/javax/swing/JScrollBar.java | 7 +- .../share/classes/javax/swing/JSlider.java | 7 +- .../share/classes/javax/swing/JSpinner.java | 7 +- .../classes/javax/swing/JTabbedPane.java | 5 +- jdk/src/share/classes/javax/swing/JTable.java | 40 ++++---- .../share/classes/javax/swing/JTextField.java | 3 +- jdk/src/share/classes/javax/swing/JTree.java | 86 ++++++++---------- .../share/classes/javax/swing/JViewport.java | 20 ++-- .../share/classes/javax/swing/JWindow.java | 6 +- .../classes/javax/swing/KeyboardManager.java | 22 ++--- .../classes/javax/swing/LayoutComparator.java | 21 ++--- .../swing/LayoutFocusTraversalPolicy.java | 2 +- .../swing/LegacyGlueFocusTraversalPolicy.java | 12 +-- .../javax/swing/MenuSelectionManager.java | 25 +++-- .../classes/javax/swing/MultiUIDefaults.java | 21 ++--- .../classes/javax/swing/PopupFactory.java | 91 +++++++++---------- .../classes/javax/swing/RepaintManager.java | 20 ++-- .../swing/SortingFocusTraversalPolicy.java | 18 ++-- .../classes/javax/swing/SpringLayout.java | 18 ++-- .../classes/javax/swing/SwingUtilities.java | 34 +++---- jdk/src/share/classes/javax/swing/Timer.java | 3 +- .../share/classes/javax/swing/TimerQueue.java | 4 +- .../share/classes/javax/swing/UIDefaults.java | 33 ++++--- .../share/classes/javax/swing/UIManager.java | 34 ++++--- .../swing/filechooser/FileSystemView.java | 32 +++---- .../javax/swing/table/AbstractTableModel.java | 3 +- .../javax/swing/table/DefaultTableModel.java | 12 +-- .../swing/tree/DefaultTreeCellEditor.java | 2 +- .../javax/swing/tree/DefaultTreeModel.java | 5 +- .../swing/tree/DefaultTreeSelectionModel.java | 41 ++++----- .../swing/tree/FixedHeightLayoutCache.java | 18 ++-- .../swing/tree/VariableHeightLayoutCache.java | 22 ++--- .../classes/javax/swing/undo/StateEdit.java | 6 +- .../classes/javax/swing/undo/UndoManager.java | 16 ++-- .../javax/swing/undo/UndoableEditSupport.java | 3 +- .../classes/sun/swing/AccessibleMethod.java | 2 +- jdk/src/share/classes/sun/swing/FilePane.java | 21 ++--- .../classes/sun/swing/SwingLazyValue.java | 5 +- .../classes/sun/swing/SwingUtilities2.java | 26 +++--- 70 files changed, 514 insertions(+), 623 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/AbstractButton.java b/jdk/src/share/classes/javax/swing/AbstractButton.java index 4248a7144e0..d4810810128 100644 --- a/jdk/src/share/classes/javax/swing/AbstractButton.java +++ b/jdk/src/share/classes/javax/swing/AbstractButton.java @@ -1315,8 +1315,7 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl // Make sure the change actually took effect if (!selected && isSelected()) { if (getModel() instanceof DefaultButtonModel) { - ButtonGroup group = (ButtonGroup) - ((DefaultButtonModel)getModel()).getGroup(); + ButtonGroup group = ((DefaultButtonModel)getModel()).getGroup(); if (group != null) { group.clearSelection(); } @@ -1886,8 +1885,7 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])(listenerList.getListeners( - ChangeListener.class)); + return listenerList.getListeners(ChangeListener.class); } /** @@ -1944,8 +1942,7 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl * @since 1.4 */ public ActionListener[] getActionListeners() { - return (ActionListener[])(listenerList.getListeners( - ActionListener.class)); + return listenerList.getListeners(ActionListener.class); } /** @@ -2137,7 +2134,7 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl * @since 1.4 */ public ItemListener[] getItemListeners() { - return (ItemListener[])listenerList.getListeners(ItemListener.class); + return listenerList.getListeners(ItemListener.class); } /** @@ -2981,7 +2978,7 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl paintViewR.height = AbstractButton.this.getHeight() - (paintViewInsets.top + paintViewInsets.bottom); String clippedText = SwingUtilities.layoutCompoundLabel( - (JComponent)AbstractButton.this, + AbstractButton.this, getFontMetrics(getFont()), text, icon, diff --git a/jdk/src/share/classes/javax/swing/AbstractCellEditor.java b/jdk/src/share/classes/javax/swing/AbstractCellEditor.java index 5ecdc439003..90b1c8d69b4 100644 --- a/jdk/src/share/classes/javax/swing/AbstractCellEditor.java +++ b/jdk/src/share/classes/javax/swing/AbstractCellEditor.java @@ -118,8 +118,7 @@ public abstract class AbstractCellEditor implements CellEditor, Serializable { * @since 1.4 */ public CellEditorListener[] getCellEditorListeners() { - return (CellEditorListener[])listenerList.getListeners( - CellEditorListener.class); + return listenerList.getListeners(CellEditorListener.class); } /** diff --git a/jdk/src/share/classes/javax/swing/AbstractListModel.java b/jdk/src/share/classes/javax/swing/AbstractListModel.java index 102218bdb7c..00c8841a533 100644 --- a/jdk/src/share/classes/javax/swing/AbstractListModel.java +++ b/jdk/src/share/classes/javax/swing/AbstractListModel.java @@ -85,8 +85,7 @@ public abstract class AbstractListModel implements ListModel, Serializable * @since 1.4 */ public ListDataListener[] getListDataListeners() { - return (ListDataListener[])listenerList.getListeners( - ListDataListener.class); + return listenerList.getListeners(ListDataListener.class); } diff --git a/jdk/src/share/classes/javax/swing/AbstractSpinnerModel.java b/jdk/src/share/classes/javax/swing/AbstractSpinnerModel.java index 2956339124c..9cf16c6db14 100644 --- a/jdk/src/share/classes/javax/swing/AbstractSpinnerModel.java +++ b/jdk/src/share/classes/javax/swing/AbstractSpinnerModel.java @@ -98,8 +98,7 @@ public abstract class AbstractSpinnerModel implements SpinnerModel, Serializable * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } diff --git a/jdk/src/share/classes/javax/swing/ActionMap.java b/jdk/src/share/classes/javax/swing/ActionMap.java index b1d4e4b20fb..3858eabe431 100644 --- a/jdk/src/share/classes/javax/swing/ActionMap.java +++ b/jdk/src/share/classes/javax/swing/ActionMap.java @@ -197,7 +197,7 @@ public class ActionMap implements Serializable { return pKeys; } - HashMap keyMap = new HashMap(); + HashMap keyMap = new HashMap(); int counter; for (counter = keys.length - 1; counter >= 0; counter--) { diff --git a/jdk/src/share/classes/javax/swing/AncestorNotifier.java b/jdk/src/share/classes/javax/swing/AncestorNotifier.java index 694bc5df08d..eb67ed15484 100644 --- a/jdk/src/share/classes/javax/swing/AncestorNotifier.java +++ b/jdk/src/share/classes/javax/swing/AncestorNotifier.java @@ -62,7 +62,7 @@ class AncestorNotifier implements ComponentListener, PropertyChangeListener, Ser } AncestorListener[] getAncestorListeners() { - return (AncestorListener[])listenerList.getListeners(AncestorListener.class); + return listenerList.getListeners(AncestorListener.class); } /** diff --git a/jdk/src/share/classes/javax/swing/ArrayTable.java b/jdk/src/share/classes/javax/swing/ArrayTable.java index b44fc436cdc..1ee5f07d88c 100644 --- a/jdk/src/share/classes/javax/swing/ArrayTable.java +++ b/jdk/src/share/classes/javax/swing/ArrayTable.java @@ -88,10 +88,10 @@ class ArrayTable implements Cloneable { // Write ou the Serializable key/value pairs. s.writeInt(validCount); if (validCount > 0) { - for (int counter = 0; counter < keys.length; counter++) { - if (keys[counter] != null) { - s.writeObject(keys[counter]); - s.writeObject(table.get(keys[counter])); + for (Object key : keys) { + if (key != null) { + s.writeObject(key); + s.writeObject(table.get(key)); if (--validCount == 0) { break; } @@ -315,7 +315,7 @@ class ArrayTable implements Cloneable { */ private void grow() { Object[] array = (Object[])table; - Hashtable tmp = new Hashtable(array.length/2); + Hashtable tmp = new Hashtable(array.length/2); for (int i = 0; i buttons = new Vector(); + protected Vector buttons = new Vector(); /** * The current selection. diff --git a/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java b/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java index f9e6c72a984..75be3e7f800 100644 --- a/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java +++ b/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java @@ -37,7 +37,7 @@ class DebugGraphicsInfo { Color flashColor = Color.red; int flashTime = 100; int flashCount = 2; - Hashtable componentToDebug; + Hashtable componentToDebug; JFrame debugFrame = null; java.io.PrintStream stream = System.out; @@ -46,7 +46,7 @@ class DebugGraphicsInfo { return; } if (componentToDebug == null) { - componentToDebug = new Hashtable(); + componentToDebug = new Hashtable(); } if (debug > 0) { componentToDebug.put(component, Integer.valueOf(debug)); @@ -59,7 +59,7 @@ class DebugGraphicsInfo { if (componentToDebug == null) { return 0; } else { - Integer integer = (Integer)componentToDebug.get(component); + Integer integer = componentToDebug.get(component); return integer == null ? 0 : integer.intValue(); } diff --git a/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java b/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java index d8e4f0f0454..c718ce6027f 100644 --- a/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java @@ -343,8 +343,7 @@ public class DefaultBoundedRangeModel implements BoundedRangeModel, Serializable * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } diff --git a/jdk/src/share/classes/javax/swing/DefaultButtonModel.java b/jdk/src/share/classes/javax/swing/DefaultButtonModel.java index b9c94384426..8ad0acddb46 100644 --- a/jdk/src/share/classes/javax/swing/DefaultButtonModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultButtonModel.java @@ -326,8 +326,7 @@ public class DefaultButtonModel implements ButtonModel, Serializable { * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } /** @@ -380,8 +379,7 @@ public class DefaultButtonModel implements ButtonModel, Serializable { * @since 1.4 */ public ActionListener[] getActionListeners() { - return (ActionListener[])listenerList.getListeners( - ActionListener.class); + return listenerList.getListeners(ActionListener.class); } /** @@ -434,7 +432,7 @@ public class DefaultButtonModel implements ButtonModel, Serializable { * @since 1.4 */ public ItemListener[] getItemListeners() { - return (ItemListener[])listenerList.getListeners(ItemListener.class); + return listenerList.getListeners(ItemListener.class); } /** diff --git a/jdk/src/share/classes/javax/swing/DefaultFocusManager.java b/jdk/src/share/classes/javax/swing/DefaultFocusManager.java index 417b625f95a..021867a5cca 100644 --- a/jdk/src/share/classes/javax/swing/DefaultFocusManager.java +++ b/jdk/src/share/classes/javax/swing/DefaultFocusManager.java @@ -156,18 +156,17 @@ final class LegacyLayoutFocusTraversalPolicy } } -final class CompareTabOrderComparator implements Comparator { +final class CompareTabOrderComparator implements Comparator { private final DefaultFocusManager defaultFocusManager; CompareTabOrderComparator(DefaultFocusManager defaultFocusManager) { this.defaultFocusManager = defaultFocusManager; } - public int compare(Object o1, Object o2) { + public int compare(Component o1, Component o2) { if (o1 == o2) { return 0; } - return (defaultFocusManager.compareTabOrder((Component)o1, - (Component)o2)) ? -1 : 1; + return (defaultFocusManager.compareTabOrder(o1, o2)) ? -1 : 1; } } diff --git a/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java b/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java index 329fa38b44a..2ba0e7b9d25 100644 --- a/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java @@ -133,8 +133,7 @@ public class DefaultListSelectionModel implements ListSelectionModel, Cloneable, * @since 1.4 */ public ListSelectionListener[] getListSelectionListeners() { - return (ListSelectionListener[])listenerList.getListeners( - ListSelectionListener.class); + return listenerList.getListeners(ListSelectionListener.class); } /** diff --git a/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java b/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java index d0270f1c75e..c03b51f16dd 100644 --- a/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java @@ -110,8 +110,7 @@ Serializable { * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } /** diff --git a/jdk/src/share/classes/javax/swing/GroupLayout.java b/jdk/src/share/classes/javax/swing/GroupLayout.java index fd1fd0c65cb..fb59d0c8564 100644 --- a/jdk/src/share/classes/javax/swing/GroupLayout.java +++ b/jdk/src/share/classes/javax/swing/GroupLayout.java @@ -1119,7 +1119,7 @@ public class GroupLayout implements LayoutManager2 { * creating one if necessary. */ private ComponentInfo getComponentInfo(Component component) { - ComponentInfo info = (ComponentInfo)componentInfos.get(component); + ComponentInfo info = componentInfos.get(component); if (info == null) { info = new ComponentInfo(component); componentInfos.put(component, info); @@ -1698,7 +1698,7 @@ public class GroupLayout implements LayoutManager2 { for (int counter = springs.size() - 1; counter >= 0; counter--) { Spring spring = springs.get(counter); if (spring instanceof AutoPreferredGapSpring) { - ((AutoPreferredGapSpring)spring).unset(); + spring.unset(); } else if (spring instanceof Group) { ((Group)spring).unsetAutopadding(); } diff --git a/jdk/src/share/classes/javax/swing/InputMap.java b/jdk/src/share/classes/javax/swing/InputMap.java index cba5a5d8bb3..0992b1188f8 100644 --- a/jdk/src/share/classes/javax/swing/InputMap.java +++ b/jdk/src/share/classes/javax/swing/InputMap.java @@ -200,7 +200,7 @@ public class InputMap implements Serializable { return pKeys; } - HashMap keyMap = new HashMap(); + HashMap keyMap = new HashMap(); int counter; for (counter = keys.length - 1; counter >= 0; counter--) { @@ -212,7 +212,7 @@ public class InputMap implements Serializable { KeyStroke[] allKeys = new KeyStroke[keyMap.size()]; - return (KeyStroke[])keyMap.keySet().toArray(allKeys); + return keyMap.keySet().toArray(allKeys); } private void writeObject(ObjectOutputStream s) throws IOException { diff --git a/jdk/src/share/classes/javax/swing/JComboBox.java b/jdk/src/share/classes/javax/swing/JComboBox.java index 2230147f4a9..42ef6466979 100644 --- a/jdk/src/share/classes/javax/swing/JComboBox.java +++ b/jdk/src/share/classes/javax/swing/JComboBox.java @@ -859,7 +859,7 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible { * @since 1.4 */ public ItemListener[] getItemListeners() { - return (ItemListener[])listenerList.getListeners(ItemListener.class); + return listenerList.getListeners(ItemListener.class); } /** @@ -897,8 +897,7 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible { * @since 1.4 */ public ActionListener[] getActionListeners() { - return (ActionListener[])listenerList.getListeners( - ActionListener.class); + return listenerList.getListeners(ActionListener.class); } /** @@ -937,8 +936,7 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible { * @since 1.4 */ public PopupMenuListener[] getPopupMenuListeners() { - return (PopupMenuListener[])listenerList.getListeners( - PopupMenuListener.class); + return listenerList.getListeners(PopupMenuListener.class); } /** @@ -1668,7 +1666,7 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible { if (editor != null) { Component comp = editor.getEditorComponent(); if (comp instanceof Accessible) { - AccessibleContext ac = ((Accessible)comp).getAccessibleContext(); + AccessibleContext ac = comp.getAccessibleContext(); if (ac != null) { // may be null ac.setAccessibleName(getAccessibleName()); ac.setAccessibleDescription(getAccessibleDescription()); @@ -1741,7 +1739,7 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible { // Fire a FOCUSED lost PropertyChangeEvent for the // previously selected list item. - PropertyChangeEvent pce = null; + PropertyChangeEvent pce; if (previousSelectedAccessible != null) { pce = new PropertyChangeEvent(previousSelectedAccessible, diff --git a/jdk/src/share/classes/javax/swing/JComponent.java b/jdk/src/share/classes/javax/swing/JComponent.java index 7d3881a1c05..831dc717a07 100644 --- a/jdk/src/share/classes/javax/swing/JComponent.java +++ b/jdk/src/share/classes/javax/swing/JComponent.java @@ -192,7 +192,8 @@ public abstract class JComponent extends Container implements Serializable, /** * @see #readObject */ - private static final Hashtable readObjectCallbacks = new Hashtable(1); + private static final Hashtable readObjectCallbacks = + new Hashtable(1); /** * Keys to use for forward focus traversal when the JComponent is @@ -356,7 +357,7 @@ public abstract class JComponent extends Container implements Serializable, /** * Temporary rectangles. */ - private static java.util.List tempRectangles = new java.util.ArrayList(11); + private static java.util.List tempRectangles = new java.util.ArrayList(11); /** Used for WHEN_FOCUSED bindings. */ private InputMap focusInputMap; @@ -451,7 +452,7 @@ public abstract class JComponent extends Container implements Serializable, Rectangle rect; int size = tempRectangles.size(); if (size > 0) { - rect = (Rectangle)tempRectangles.remove(size - 1); + rect = tempRectangles.remove(size - 1); } else { rect = new Rectangle(0, 0, 0, 0); @@ -806,7 +807,7 @@ public abstract class JComponent extends Container implements Serializable, // its index. if (paintingChild != null && (paintingChild instanceof JComponent) && - ((JComponent)paintingChild).isOpaque()) { + paintingChild.isOpaque()) { for (; i >= 0; i--) { if (getComponent(i) == paintingChild){ break; @@ -875,7 +876,7 @@ public abstract class JComponent extends Container implements Serializable, shouldSetFlagBack = true; } if(!printing) { - ((JComponent)comp).paint(cg); + comp.paint(cg); } else { if (!getFlag(IS_PRINTING_ALL)) { @@ -1098,7 +1099,7 @@ public abstract class JComponent extends Container implements Serializable, } private void adjustPaintFlags() { - JComponent jparent = null; + JComponent jparent; Container parent; for(parent = getParent() ; parent != null ; parent = parent.getParent()) { @@ -2096,7 +2097,7 @@ public abstract class JComponent extends Container implements Serializable, private void registerWithKeyboardManager(boolean onlyIfNew) { InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW, false); KeyStroke[] strokes; - Hashtable registered = (Hashtable)getClientProperty + Hashtable registered = (Hashtable)getClientProperty (WHEN_IN_FOCUSED_WINDOW_BINDINGS); if (inputMap != null) { @@ -2120,10 +2121,10 @@ public abstract class JComponent extends Container implements Serializable, } // Remove any old ones. if (registered != null && registered.size() > 0) { - Enumeration keys = registered.keys(); + Enumeration keys = registered.keys(); while (keys.hasMoreElements()) { - KeyStroke ks = (KeyStroke)keys.nextElement(); + KeyStroke ks = keys.nextElement(); unregisterWithKeyboardManager(ks); } registered.clear(); @@ -2131,7 +2132,7 @@ public abstract class JComponent extends Container implements Serializable, // Updated the registered Hashtable. if (strokes != null && strokes.length > 0) { if (registered == null) { - registered = new Hashtable(strokes.length); + registered = new Hashtable(strokes.length); putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, registered); } for (int counter = strokes.length - 1; counter >= 0; counter--) { @@ -2174,7 +2175,7 @@ public abstract class JComponent extends Container implements Serializable, InputMap km = getInputMap(WHEN_IN_FOCUSED_WINDOW, false); while (km != inputMap && km != null) { - km = (ComponentInputMap)km.getParent(); + km = km.getParent(); } if (km != null) { registerWithKeyboardManager(false); @@ -3673,7 +3674,7 @@ public abstract class JComponent extends Container implements Serializable, if (c != null && c instanceof Accessible) { AccessibleJComponent.this.firePropertyChange( AccessibleContext.ACCESSIBLE_CHILD_PROPERTY, - null, ((Accessible) c).getAccessibleContext()); + null, c.getAccessibleContext()); } } public void componentRemoved(ContainerEvent e) { @@ -3681,7 +3682,7 @@ public abstract class JComponent extends Container implements Serializable, if (c != null && c instanceof Accessible) { AccessibleJComponent.this.firePropertyChange( AccessibleContext.ACCESSIBLE_CHILD_PROPERTY, - ((Accessible) c).getAccessibleContext(), null); + c.getAccessibleContext(), null); } } } @@ -4377,7 +4378,7 @@ public abstract class JComponent extends Container implements Serializable, // System.out.println("A) checking opaque: " + ((JComponent)child).isOpaque() + " " + child); // System.out.print("B) "); // Thread.dumpStack(); - return ((JComponent)child).isOpaque(); + return child.isOpaque(); } else { /** Sometimes a heavy weight can have a bound larger than its peer size * so we should always draw under heavy weights @@ -4693,7 +4694,7 @@ public abstract class JComponent extends Container implements Serializable, result = (T[])getPropertyChangeListeners(); } else { - result = (T[])listenerList.getListeners(listenerType); + result = listenerList.getListeners(listenerType); } if (result.length == 0) { @@ -4904,7 +4905,7 @@ public abstract class JComponent extends Container implements Serializable, if(!isShowing()) { return; } - while(!((JComponent)c).isOpaque()) { + while(!c.isOpaque()) { parent = c.getParent(); if(parent != null) { x += c.getX(); @@ -5198,7 +5199,7 @@ public abstract class JComponent extends Container implements Serializable, Rectangle siblingRect; boolean opaque; if (sibling instanceof JComponent) { - opaque = ((JComponent)sibling).isOpaque(); + opaque = sibling.isOpaque(); if (!opaque) { if (retValue == PARTIALLY_OBSCURED) { continue; @@ -5345,7 +5346,7 @@ public abstract class JComponent extends Container implements Serializable, */ private class ReadObjectCallback implements ObjectInputValidation { - private final Vector roots = new Vector(1); + private final Vector roots = new Vector(1); private final ObjectInputStream inputStream; ReadObjectCallback(ObjectInputStream s) throws Exception { @@ -5361,8 +5362,7 @@ public abstract class JComponent extends Container implements Serializable, */ public void validateObject() throws InvalidObjectException { try { - for(int i = 0; i < roots.size(); i++) { - JComponent root = (JComponent)(roots.elementAt(i)); + for (JComponent root : roots) { SwingUtilities.updateComponentTreeUI(root); } } @@ -5382,8 +5382,7 @@ public abstract class JComponent extends Container implements Serializable, /* If the Component c is a descendant of one of the * existing roots (or it IS an existing root), we're done. */ - for(int i = 0; i < roots.size(); i++) { - JComponent root = (JComponent)roots.elementAt(i); + for (JComponent root : roots) { for(Component p = c; p != null; p = p.getParent()) { if (p == root) { return; @@ -5396,7 +5395,7 @@ public abstract class JComponent extends Container implements Serializable, * to the roots vector. */ for(int i = 0; i < roots.size(); i++) { - JComponent root = (JComponent)roots.elementAt(i); + JComponent root = roots.elementAt(i); for(Component p = root.getParent(); p != null; p = p.getParent()) { if (p == c) { roots.removeElementAt(i--); // !! @@ -5428,7 +5427,7 @@ public abstract class JComponent extends Container implements Serializable, * in the readObjectCallbacks table. Note that the ReadObjectCallback * constructor takes care of calling s.registerValidation(). */ - ReadObjectCallback cb = (ReadObjectCallback)(readObjectCallbacks.get(s)); + ReadObjectCallback cb = readObjectCallbacks.get(s); if (cb == null) { try { readObjectCallbacks.put(s, cb = new ReadObjectCallback(s)); diff --git a/jdk/src/share/classes/javax/swing/JDesktopPane.java b/jdk/src/share/classes/javax/swing/JDesktopPane.java index 2c0ab31202f..19cfefd65f9 100644 --- a/jdk/src/share/classes/javax/swing/JDesktopPane.java +++ b/jdk/src/share/classes/javax/swing/JDesktopPane.java @@ -133,8 +133,8 @@ public class JDesktopPane extends JLayeredPane implements Accessible public Component getDefaultComponent(Container c) { JInternalFrame jifArray[] = getAllFrames(); Component comp = null; - for (int i = 0; i < jifArray.length; i++) { - comp = jifArray[i].getFocusTraversalPolicy().getDefaultComponent(jifArray[i]); + for (JInternalFrame jif : jifArray) { + comp = jif.getFocusTraversalPolicy().getDefaultComponent(jif); if (comp != null) { break; } @@ -262,16 +262,15 @@ public class JDesktopPane extends JLayeredPane implements Accessible public JInternalFrame[] getAllFrames() { int i, count; JInternalFrame[] results; - Vector vResults = new Vector(10); - Object next, tmp; + Vector vResults = new Vector(10); count = getComponentCount(); for(i = 0; i < count; i++) { - next = getComponent(i); + Component next = getComponent(i); if(next instanceof JInternalFrame) - vResults.addElement(next); + vResults.addElement((JInternalFrame) next); else if(next instanceof JInternalFrame.JDesktopIcon) { - tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame(); + JInternalFrame tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame(); if(tmp != null) vResults.addElement(tmp); } @@ -324,18 +323,17 @@ public class JDesktopPane extends JLayeredPane implements Accessible public JInternalFrame[] getAllFramesInLayer(int layer) { int i, count; JInternalFrame[] results; - Vector vResults = new Vector(10); - Object next, tmp; + Vector vResults = new Vector(10); count = getComponentCount(); for(i = 0; i < count; i++) { - next = getComponent(i); + Component next = getComponent(i); if(next instanceof JInternalFrame) { if(((JInternalFrame)next).getLayer() == layer) - vResults.addElement(next); + vResults.addElement((JInternalFrame) next); } else if(next instanceof JInternalFrame.JDesktopIcon) { - tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame(); - if(tmp != null && ((JInternalFrame)tmp).getLayer() == layer) + JInternalFrame tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame(); + if(tmp != null && tmp.getLayer() == layer) vResults.addElement(tmp); } } diff --git a/jdk/src/share/classes/javax/swing/JDialog.java b/jdk/src/share/classes/javax/swing/JDialog.java index ac2a24ecc06..79640949084 100644 --- a/jdk/src/share/classes/javax/swing/JDialog.java +++ b/jdk/src/share/classes/javax/swing/JDialog.java @@ -277,7 +277,7 @@ public class JDialog extends Dialog implements WindowConstants, title, modal); if (owner == null) { WindowListener ownerShutdownListener = - (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener(); + SwingUtilities.getSharedOwnerFrameShutdownListener(); addWindowListener(ownerShutdownListener); } dialogInit(); @@ -329,7 +329,7 @@ public class JDialog extends Dialog implements WindowConstants, title, modal, gc); if (owner == null) { WindowListener ownerShutdownListener = - (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener(); + SwingUtilities.getSharedOwnerFrameShutdownListener(); addWindowListener(ownerShutdownListener); } dialogInit(); diff --git a/jdk/src/share/classes/javax/swing/JEditorPane.java b/jdk/src/share/classes/javax/swing/JEditorPane.java index 4d70cacb7b2..21528752fd5 100644 --- a/jdk/src/share/classes/javax/swing/JEditorPane.java +++ b/jdk/src/share/classes/javax/swing/JEditorPane.java @@ -319,8 +319,7 @@ public class JEditorPane extends JTextComponent { * @since 1.4 */ public synchronized HyperlinkListener[] getHyperlinkListeners() { - return (HyperlinkListener[])listenerList.getListeners( - HyperlinkListener.class); + return listenerList.getListeners(javax.swing.event.HyperlinkListener.class); } /** @@ -492,8 +491,8 @@ public class JEditorPane extends JTextComponent { if (pageProperties != null) { // transfer properties discovered in stream to the // document property collection. - for (Enumeration e = pageProperties.keys(); e.hasMoreElements() ;) { - Object key = e.nextElement(); + for (Enumeration e = pageProperties.keys(); e.hasMoreElements() ;) { + String key = e.nextElement(); doc.putProperty(key, pageProperties.get(key)); } pageProperties.clear(); @@ -775,7 +774,7 @@ public class JEditorPane extends JTextComponent { */ private void handleConnectionProperties(URLConnection conn) { if (pageProperties == null) { - pageProperties = new Hashtable(); + pageProperties = new Hashtable(); } String type = conn.getContentType(); if (type != null) { @@ -989,7 +988,7 @@ public class JEditorPane extends JTextComponent { * of the content type in the http header information. */ private void setCharsetFromContentTypeParameters(String paramlist) { - String charset = null; + String charset; try { // paramlist is handed to us with a leading ';', strip it. int semi = paramlist.indexOf(';'); @@ -1080,9 +1079,9 @@ public class JEditorPane extends JTextComponent { */ public EditorKit getEditorKitForContentType(String type) { if (typeHandlers == null) { - typeHandlers = new Hashtable(3); + typeHandlers = new Hashtable(3); } - EditorKit k = (EditorKit) typeHandlers.get(type); + EditorKit k = typeHandlers.get(type); if (k == null) { k = createEditorKitForContentType(type); if (k != null) { @@ -1106,7 +1105,7 @@ public class JEditorPane extends JTextComponent { */ public void setEditorKitForContentType(String type, EditorKit k) { if (typeHandlers == null) { - typeHandlers = new Hashtable(3); + typeHandlers = new Hashtable(3); } typeHandlers.put(type, k); } @@ -1176,13 +1175,12 @@ public class JEditorPane extends JTextComponent { * registered for the given type */ public static EditorKit createEditorKitForContentType(String type) { - EditorKit k = null; - Hashtable kitRegistry = getKitRegisty(); - k = (EditorKit) kitRegistry.get(type); + Hashtable kitRegistry = getKitRegisty(); + EditorKit k = kitRegistry.get(type); if (k == null) { // try to dynamically load the support - String classname = (String) getKitTypeRegistry().get(type); - ClassLoader loader = (ClassLoader) getKitLoaderRegistry().get(type); + String classname = getKitTypeRegistry().get(type); + ClassLoader loader = getKitLoaderRegistry().get(type); try { Class c; if (loader != null) { @@ -1252,20 +1250,20 @@ public class JEditorPane extends JTextComponent { * @since 1.3 */ public static String getEditorKitClassNameForContentType(String type) { - return (String)getKitTypeRegistry().get(type); + return getKitTypeRegistry().get(type); } - private static Hashtable getKitTypeRegistry() { + private static Hashtable getKitTypeRegistry() { loadDefaultKitsIfNecessary(); return (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey); } - private static Hashtable getKitLoaderRegistry() { + private static Hashtable getKitLoaderRegistry() { loadDefaultKitsIfNecessary(); return (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey); } - private static Hashtable getKitRegisty() { + private static Hashtable getKitRegisty() { Hashtable ht = (Hashtable)SwingUtilities.appContextGet(kitRegistryKey); if (ht == null) { ht = new Hashtable(3); @@ -1512,7 +1510,7 @@ public class JEditorPane extends JTextComponent { private EditorKit kit; private boolean isUserSetEditorKit; - private Hashtable pageProperties; + private Hashtable pageProperties; /** Should be kept in sync with javax.swing.text.html.FormView counterpart. */ final static String PostDataProperty = "javax.swing.JEditorPane.postdata"; @@ -1520,7 +1518,7 @@ public class JEditorPane extends JTextComponent { /** * Table of registered type handlers for this editor. */ - private Hashtable typeHandlers; + private Hashtable typeHandlers; /* * Private AppContext keys for this class's static variables. @@ -1913,11 +1911,11 @@ public class JEditorPane extends JTextComponent { } } - private class LinkVector extends Vector { + private class LinkVector extends Vector { public int baseElementIndex(Element e) { HTMLLink l; for (int i = 0; i < elementCount; i++) { - l = (HTMLLink) elementAt(i); + l = elementAt(i); if (l.element == e) { return i; } @@ -2029,7 +2027,7 @@ public class JEditorPane extends JTextComponent { buildLinkTable(); } if (linkIndex >= 0 && linkIndex < hyperlinks.size()) { - return (AccessibleHyperlink) hyperlinks.elementAt(linkIndex); + return hyperlinks.elementAt(linkIndex); } else { return null; } diff --git a/jdk/src/share/classes/javax/swing/JFileChooser.java b/jdk/src/share/classes/javax/swing/JFileChooser.java index 4a213df6273..82c85fe9faa 100644 --- a/jdk/src/share/classes/javax/swing/JFileChooser.java +++ b/jdk/src/share/classes/javax/swing/JFileChooser.java @@ -248,7 +248,7 @@ public class JFileChooser extends JComponent implements Accessible { private String approveButtonToolTipText = null; private int approveButtonMnemonic = 0; - private Vector filters = new Vector(5); + private Vector filters = new Vector(5); private JDialog dialog = null; private int dialogType = OPEN_DIALOG; private int returnValue = ERROR_OPTION; @@ -503,7 +503,7 @@ public class JFileChooser extends JComponent implements Accessible { if(selectedFiles == null) { return new File[0]; } else { - return (File[]) selectedFiles.clone(); + return selectedFiles.clone(); } } @@ -1415,17 +1415,17 @@ public class JFileChooser extends JComponent implements Accessible { fileFilter = filter; if (filter != null) { if (isMultiSelectionEnabled() && selectedFiles != null && selectedFiles.length > 0) { - Vector fList = new Vector(); + Vector fList = new Vector(); boolean failed = false; - for (int i = 0; i < selectedFiles.length; i++) { - if (filter.accept(selectedFiles[i])) { - fList.add(selectedFiles[i]); + for (File file : selectedFiles) { + if (filter.accept(file)) { + fList.add(file); } else { failed = true; } } if (failed) { - setSelectedFiles((fList.size() == 0) ? null : (File[])fList.toArray(new File[fList.size()])); + setSelectedFiles((fList.size() == 0) ? null : fList.toArray(new File[fList.size()])); } } else if (selectedFile != null && !filter.accept(selectedFile)) { setSelectedFile(null); @@ -1702,8 +1702,7 @@ public class JFileChooser extends JComponent implements Accessible { * @since 1.4 */ public ActionListener[] getActionListeners() { - return (ActionListener[])listenerList.getListeners( - ActionListener.class); + return listenerList.getListeners(ActionListener.class); } /** @@ -1744,7 +1743,7 @@ public class JFileChooser extends JComponent implements Accessible { WeakReference jfcRef; public WeakPCL(JFileChooser jfc) { - jfcRef = new WeakReference(jfc); + jfcRef = new WeakReference(jfc); } public void propertyChange(PropertyChangeEvent ev) { assert ev.getPropertyName().equals(SHOW_HIDDEN_PROP); diff --git a/jdk/src/share/classes/javax/swing/JInternalFrame.java b/jdk/src/share/classes/javax/swing/JInternalFrame.java index c3e3cad1c11..837ffe49e4f 100644 --- a/jdk/src/share/classes/javax/swing/JInternalFrame.java +++ b/jdk/src/share/classes/javax/swing/JInternalFrame.java @@ -421,8 +421,8 @@ public class JInternalFrame extends JComponent implements invalidate(); Component[] children = getComponents(); if (children != null) { - for(int i = 0; i < children.length; i++) { - SwingUtilities.updateComponentTreeUI(children[i]); + for (Component child : children) { + SwingUtilities.updateComponentTreeUI(child); } } } @@ -1535,8 +1535,7 @@ public class JInternalFrame extends JComponent implements * @see #addInternalFrameListener */ public InternalFrameListener[] getInternalFrameListeners() { - return (InternalFrameListener[])listenerList.getListeners( - InternalFrameListener.class); + return listenerList.getListeners(InternalFrameListener.class); } // remind: name ok? all one method ok? need to be synchronized? @@ -2258,8 +2257,8 @@ public class JInternalFrame extends JComponent implements invalidate(); Component[] children = getComponents(); if (children != null) { - for(int i = 0; i < children.length; i++) { - SwingUtilities.updateComponentTreeUI(children[i]); + for (Component child : children) { + SwingUtilities.updateComponentTreeUI(child); } } } diff --git a/jdk/src/share/classes/javax/swing/JLayeredPane.java b/jdk/src/share/classes/javax/swing/JLayeredPane.java index b3cedb2d37e..e971fe1d8ef 100644 --- a/jdk/src/share/classes/javax/swing/JLayeredPane.java +++ b/jdk/src/share/classes/javax/swing/JLayeredPane.java @@ -191,7 +191,7 @@ public class JLayeredPane extends JComponent implements Accessible { private void validateOptimizedDrawing() { boolean layeredComponentFound = false; synchronized(getTreeLock()) { - Integer layer = null; + Integer layer; for (Component c : getComponents()) { layer = null; @@ -213,7 +213,7 @@ public class JLayeredPane extends JComponent implements Accessible { } protected void addImpl(Component comp, Object constraints, int index) { - int layer = DEFAULT_LAYER.intValue(); + int layer; int pos; if(constraints instanceof Integer) { @@ -364,7 +364,7 @@ public class JLayeredPane extends JComponent implements Accessible { if(c instanceof JComponent) ((JComponent)c).putClientProperty(LAYER_PROPERTY, layerObj); else - getComponentToLayer().put((Component)c, layerObj); + getComponentToLayer().put(c, layerObj); if(c.getParent() == null || c.getParent() != this) { repaint(c.getBounds()); @@ -388,7 +388,7 @@ public class JLayeredPane extends JComponent implements Accessible { if(c instanceof JComponent) i = (Integer)((JComponent)c).getClientProperty(LAYER_PROPERTY); else - i = (Integer)getComponentToLayer().get((Component)c); + i = getComponentToLayer().get(c); if(i == null) return DEFAULT_LAYER.intValue(); @@ -465,9 +465,9 @@ public class JLayeredPane extends JComponent implements Accessible { * @see #getComponentCountInLayer */ public int getPosition(Component c) { - int i, count, startLayer, curLayer, startLocation, pos = 0; + int i, startLayer, curLayer, startLocation, pos = 0; - count = getComponentCount(); + getComponentCount(); startLocation = getIndexOf(c); if(startLocation == -1) diff --git a/jdk/src/share/classes/javax/swing/JList.java b/jdk/src/share/classes/javax/swing/JList.java index a83a4c94e4c..772c7554056 100644 --- a/jdk/src/share/classes/javax/swing/JList.java +++ b/jdk/src/share/classes/javax/swing/JList.java @@ -1848,8 +1848,7 @@ public class JList extends JComponent implements Scrollable, Accessible * @since 1.4 */ public ListSelectionListener[] getListSelectionListeners() { - return (ListSelectionListener[])listenerList.getListeners( - ListSelectionListener.class); + return listenerList.getListeners(ListSelectionListener.class); } @@ -2220,9 +2219,9 @@ public class JList extends JComponent implements Scrollable, Accessible ListSelectionModel sm = getSelectionModel(); sm.clearSelection(); int size = getModel().getSize(); - for(int i = 0; i < indices.length; i++) { - if (indices[i] < size) { - sm.addSelectionInterval(indices[i], indices[i]); + for (int i : indices) { + if (i < size) { + sm.addSelectionInterval(i, i); } } } @@ -2724,7 +2723,7 @@ public class JList extends JComponent implements Scrollable, Accessible return true; } if (getParent() instanceof JViewport) { - return (((JViewport)getParent()).getWidth() > getPreferredSize().width); + return (getParent().getWidth() > getPreferredSize().width); } return false; } @@ -2749,7 +2748,7 @@ public class JList extends JComponent implements Scrollable, Accessible return true; } if (getParent() instanceof JViewport) { - return (((JViewport)getParent()).getHeight() > getPreferredSize().height); + return (getParent().getHeight() > getPreferredSize().height); } return false; } @@ -3161,7 +3160,7 @@ public class JList extends JComponent implements Scrollable, Accessible private AccessibleContext getCurrentAccessibleContext() { Component c = getComponentAtIndex(indexInParent); if (c instanceof Accessible) { - return ((Accessible) c).getAccessibleContext(); + return c.getAccessibleContext(); } else { return null; } diff --git a/jdk/src/share/classes/javax/swing/JMenu.java b/jdk/src/share/classes/javax/swing/JMenu.java index ed90cb73eec..cf069116c21 100644 --- a/jdk/src/share/classes/javax/swing/JMenu.java +++ b/jdk/src/share/classes/javax/swing/JMenu.java @@ -371,8 +371,8 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement * @since 1.3 */ protected Point getPopupMenuOrigin() { - int x = 0; - int y = 0; + int x; + int y; JPopupMenu pm = getPopupMenu(); // Figure out the sizes needed to caclulate the menu position Dimension s = getSize(); @@ -900,10 +900,8 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement * on another menu */ public boolean isTopLevelMenu() { - if (getParent() instanceof JMenuBar) - return true; + return getParent() instanceof JMenuBar; - return false; } /** @@ -1015,7 +1013,7 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement * @since 1.4 */ public MenuListener[] getMenuListeners() { - return (MenuListener[])listenerList.getListeners(MenuListener.class); + return listenerList.getListeners(MenuListener.class); } /** @@ -1305,7 +1303,7 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement * @return the array of menu items */ private MenuElement[] buildMenuElementArray(JMenu leaf) { - Vector elements = new Vector(); + Vector elements = new Vector(); Component current = leaf.getPopupMenu(); JPopupMenu pop; JMenu menu; @@ -1409,8 +1407,8 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement public int getAccessibleChildrenCount() { Component[] children = getMenuComponents(); int count = 0; - for (int j = 0; j < children.length; j++) { - if (children[j] instanceof Accessible) { + for (Component child : children) { + if (child instanceof Accessible) { count++; } } @@ -1426,18 +1424,18 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement public Accessible getAccessibleChild(int i) { Component[] children = getMenuComponents(); int count = 0; - for (int j = 0; j < children.length; j++) { - if (children[j] instanceof Accessible) { + for (Component child : children) { + if (child instanceof Accessible) { if (count == i) { - if (children[j] instanceof JComponent) { + if (child instanceof JComponent) { // FIXME: [[[WDW - probably should set this when // the component is added to the menu. I tried // to do this in most cases, but the separators // added by addSeparator are hard to get to.]]] - AccessibleContext ac = ((Accessible) children[j]).getAccessibleContext(); + AccessibleContext ac = child.getAccessibleContext(); ac.setAccessibleParent(JMenu.this); } - return (Accessible) children[j]; + return (Accessible) child; } else { count++; } @@ -1581,7 +1579,7 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement } JMenuItem mi = getItem(i); if (mi != null && mi instanceof JMenu) { - if (((JMenu) mi).isSelected()) { + if (mi.isSelected()) { MenuElement old[] = MenuSelectionManager.defaultManager().getSelectedPath(); MenuElement me[] = new MenuElement[old.length-2]; diff --git a/jdk/src/share/classes/javax/swing/JMenuBar.java b/jdk/src/share/classes/javax/swing/JMenuBar.java index d6f04fbb427..724eba6b8ff 100644 --- a/jdk/src/share/classes/javax/swing/JMenuBar.java +++ b/jdk/src/share/classes/javax/swing/JMenuBar.java @@ -414,7 +414,7 @@ public class JMenuBar extends JComponent implements Accessible,MenuElement */ public MenuElement[] getSubElements() { MenuElement result[]; - Vector tmp = new Vector(); + Vector tmp = new Vector(); int c = getComponentCount(); int i; Component m; @@ -422,12 +422,12 @@ public class JMenuBar extends JComponent implements Accessible,MenuElement for(i=0 ; i < c ; i++) { m = getComponent(i); if(m instanceof MenuElement) - tmp.addElement(m); + tmp.addElement((MenuElement) m); } result = new MenuElement[tmp.size()]; for(i=0,c=tmp.size() ; i < c ; i++) - result[i] = (MenuElement) tmp.elementAt(i); + result[i] = tmp.elementAt(i); return result; } @@ -664,9 +664,9 @@ public class JMenuBar extends JComponent implements Accessible,MenuElement boolean retValue = super.processKeyBinding(ks, e, condition, pressed); if (!retValue) { MenuElement[] subElements = getSubElements(); - for (int i=0; i values = new Vector(); s.defaultWriteObject(); // Save the icon, if its Serializable. @@ -2342,7 +2339,7 @@ public class JOptionPane extends JComponent implements Accessible } // Save the treeModel, if its Serializable. if(options != null) { - Vector serOptions = new Vector(); + Vector serOptions = new Vector(); for(int counter = 0, maxCounter = options.length; counter < maxCounter; counter++) @@ -2510,16 +2507,16 @@ public class JOptionPane extends JComponent implements Accessible /** * Retrieves a method from the provided class and makes it accessible. */ - private static class ModalPrivilegedAction implements PrivilegedAction { - private Class clazz; + private static class ModalPrivilegedAction implements PrivilegedAction { + private Class clazz; private String methodName; - public ModalPrivilegedAction(Class clazz, String methodName) { + public ModalPrivilegedAction(Class clazz, String methodName) { this.clazz = clazz; this.methodName = methodName; } - public Object run() { + public Method run() { Method method = null; try { method = clazz.getDeclaredMethod(methodName, (Class[])null); diff --git a/jdk/src/share/classes/javax/swing/JPopupMenu.java b/jdk/src/share/classes/javax/swing/JPopupMenu.java index 83aec9a17b3..8f90a02a2a9 100644 --- a/jdk/src/share/classes/javax/swing/JPopupMenu.java +++ b/jdk/src/share/classes/javax/swing/JPopupMenu.java @@ -584,7 +584,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { int nitems = getComponentCount(); // PENDING(ges): Why not use an array? - Vector tempItems = new Vector(); + Vector tempItems = new Vector(); /* Remove the item at index, nitems-index times storing them in a temporary vector in the @@ -600,8 +600,8 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { /* Add the removed items back to the menu, they are already in the correct order in the temp vector. */ - for (int i = 0; i < tempItems.size() ; i++) { - add((Component)tempItems.elementAt(i)); + for (Component tempItem : tempItems) { + add(tempItem); } } @@ -632,8 +632,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { * @since 1.4 */ public PopupMenuListener[] getPopupMenuListeners() { - return (PopupMenuListener[])listenerList.getListeners( - PopupMenuListener.class); + return listenerList.getListeners(PopupMenuListener.class); } /** @@ -665,8 +664,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { * @since 1.5 */ public MenuKeyListener[] getMenuKeyListeners() { - return (MenuKeyListener[])listenerList.getListeners( - MenuKeyListener.class); + return listenerList.getListeners(MenuKeyListener.class); } /** @@ -781,7 +779,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { // set selection path before popping up! if (isPopupMenu()) { MenuElement me[] = new MenuElement[1]; - me[0] = (MenuElement) this; + me[0] = this; MenuSelectionManager.defaultManager().setSelectedPath(me); } } @@ -848,10 +846,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { * being displayed). */ public boolean isVisible() { - if(popup != null) - return true; - else - return false; + return popup != null; } /** @@ -1311,7 +1306,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { // Serialization support. //////////// private void writeObject(ObjectOutputStream s) throws IOException { - Vector values = new Vector(); + Vector values = new Vector(); s.defaultWriteObject(); // Save the invoker, if its Serializable. @@ -1494,7 +1489,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { */ public MenuElement[] getSubElements() { MenuElement result[]; - Vector tmp = new Vector(); + Vector tmp = new Vector(); int c = getComponentCount(); int i; Component m; @@ -1502,12 +1497,12 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { for(i=0 ; i < c ; i++) { m = getComponent(i); if(m instanceof MenuElement) - tmp.addElement(m); + tmp.addElement((MenuElement) m); } result = new MenuElement[tmp.size()]; for(i=0,c=tmp.size() ; i < c ; i++) - result[i] = (MenuElement) tmp.elementAt(i); + result[i] = tmp.elementAt(i); return result; } diff --git a/jdk/src/share/classes/javax/swing/JProgressBar.java b/jdk/src/share/classes/javax/swing/JProgressBar.java index b1d27c8cd02..9ba25d96cea 100644 --- a/jdk/src/share/classes/javax/swing/JProgressBar.java +++ b/jdk/src/share/classes/javax/swing/JProgressBar.java @@ -699,8 +699,7 @@ public class JProgressBar extends JComponent implements SwingConstants, Accessib * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } /** diff --git a/jdk/src/share/classes/javax/swing/JScrollBar.java b/jdk/src/share/classes/javax/swing/JScrollBar.java index 5897fd6fad8..90e2cc7595f 100644 --- a/jdk/src/share/classes/javax/swing/JScrollBar.java +++ b/jdk/src/share/classes/javax/swing/JScrollBar.java @@ -659,8 +659,7 @@ public class JScrollBar extends JComponent implements Adjustable, Accessible * @since 1.4 */ public AdjustmentListener[] getAdjustmentListeners() { - return (AdjustmentListener[])listenerList.getListeners( - AdjustmentListener.class); + return listenerList.getListeners(AdjustmentListener.class); } @@ -754,8 +753,8 @@ public class JScrollBar extends JComponent implements Adjustable, Accessible public void setEnabled(boolean x) { super.setEnabled(x); Component[] children = getComponents(); - for(int i = 0; i < children.length; i++) { - children[i].setEnabled(x); + for (Component child : children) { + child.setEnabled(x); } } diff --git a/jdk/src/share/classes/javax/swing/JSlider.java b/jdk/src/share/classes/javax/swing/JSlider.java index ea2b510be1d..c2941c64234 100644 --- a/jdk/src/share/classes/javax/swing/JSlider.java +++ b/jdk/src/share/classes/javax/swing/JSlider.java @@ -930,7 +930,7 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { throw new IllegalArgumentException( "Label incremement must be > 0" ); } - class SmartHashtable extends Hashtable implements PropertyChangeListener { + class SmartHashtable extends Hashtable implements PropertyChangeListener { int increment = 0; int start = 0; boolean startAtMin = false; @@ -977,9 +977,8 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { if ( e.getPropertyName().equals( "minimum" ) || e.getPropertyName().equals( "maximum" ) ) { - Dictionary labelTable = getLabelTable(); - Enumeration keys = labelTable.keys(); - Hashtable hashtable = new Hashtable(); + Enumeration keys = getLabelTable().keys(); + Hashtable hashtable = new Hashtable(); // Save the labels that were added by the developer while ( keys.hasMoreElements() ) { diff --git a/jdk/src/share/classes/javax/swing/JSpinner.java b/jdk/src/share/classes/javax/swing/JSpinner.java index dd573e10457..c5cebda03f7 100644 --- a/jdk/src/share/classes/javax/swing/JSpinner.java +++ b/jdk/src/share/classes/javax/swing/JSpinner.java @@ -433,8 +433,7 @@ public class JSpinner extends JComponent implements Accessible * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } @@ -1536,7 +1535,7 @@ public class JSpinner extends JComponent implements Accessible return textField.getAccessibleContext(); } } else if (editor instanceof Accessible) { - return ((Accessible)editor).getAccessibleContext(); + return editor.getAccessibleContext(); } return null; } @@ -1693,7 +1692,7 @@ public class JSpinner extends JComponent implements Accessible if (i < 0 || i > 1) { return false; } - Object o = null; + Object o; if (i == 0) { o = getNextValue(); // AccessibleAction.INCREMENT } else { diff --git a/jdk/src/share/classes/javax/swing/JTabbedPane.java b/jdk/src/share/classes/javax/swing/JTabbedPane.java index 9bcafb1ab32..2c74189fd33 100644 --- a/jdk/src/share/classes/javax/swing/JTabbedPane.java +++ b/jdk/src/share/classes/javax/swing/JTabbedPane.java @@ -313,8 +313,7 @@ public class JTabbedPane extends JComponent * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } /** @@ -2062,7 +2061,7 @@ public class JTabbedPane extends JComponent * Accessibility classes unnecessarily. */ AccessibleContext ac; - ac = ((Accessible) component).getAccessibleContext(); + ac = component.getAccessibleContext(); if (ac != null) { ac.setAccessibleParent(this); } diff --git a/jdk/src/share/classes/javax/swing/JTable.java b/jdk/src/share/classes/javax/swing/JTable.java index 976cb813093..1b770d89153 100644 --- a/jdk/src/share/classes/javax/swing/JTable.java +++ b/jdk/src/share/classes/javax/swing/JTable.java @@ -1677,16 +1677,16 @@ public class JTable extends JComponent implements TableModelListener, Scrollable if (!forDrop && state != null) { clearSelection(); - int[] rows = (int[])((int[][])state)[0]; - int[] cols = (int[])((int[][])state)[1]; - int[] anchleads = (int[])((int[][])state)[2]; + int[] rows = ((int[][])state)[0]; + int[] cols = ((int[][])state)[1]; + int[] anchleads = ((int[][])state)[2]; - for (int i = 0; i < rows.length; i++) { - addRowSelectionInterval(rows[i], rows[i]); + for (int row : rows) { + addRowSelectionInterval(row, row); } - for (int i = 0; i < cols.length; i++) { - addColumnSelectionInterval(cols[i], cols[i]); + for (int col : cols) { + addColumnSelectionInterval(col, col); } SwingUtilities2.setLeadAnchorWithoutSelection( @@ -1776,7 +1776,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable boolean oldValue = this.autoCreateRowSorter; this.autoCreateRowSorter = autoCreateRowSorter; if (autoCreateRowSorter) { - setRowSorter(new TableRowSorter(getModel())); + setRowSorter(new TableRowSorter(getModel())); } firePropertyChange("autoCreateRowSorter", oldValue, autoCreateRowSorter); @@ -3198,7 +3198,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable private void accommodateDelta(int resizingColumnIndex, int delta) { int columnCount = getColumnCount(); int from = resizingColumnIndex; - int to = columnCount; + int to; // Use the mode to determine how to absorb the changes. switch(autoResizeMode) { @@ -3237,8 +3237,6 @@ public class JTable extends JComponent implements TableModelListener, Scrollable } adjustSizes(totalWidth + delta, r, false); - - return; } private interface Resizable2 { @@ -3492,7 +3490,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable * @see #editingRow */ public boolean isEditing() { - return (cellEditor == null)? false : true; + return cellEditor != null; } /** @@ -3642,7 +3640,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable firePropertyChange("model", old, dataModel); if (getAutoCreateRowSorter()) { - setRowSorter(new TableRowSorter(dataModel)); + setRowSorter(new TableRowSorter(dataModel)); } } } @@ -5160,7 +5158,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable public boolean getScrollableTracksViewportHeight() { return getFillsViewportHeight() && getParent() instanceof JViewport - && (((JViewport)getParent()).getHeight() > getPreferredSize().height); + && (getParent().getHeight() > getPreferredSize().height); } /** @@ -5214,7 +5212,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable // by setting the client property JTable.autoStartsEdit to Boolean.FALSE. if (!retValue && condition == WHEN_ANCESTOR_OF_FOCUSED_COMPONENT && isFocusOwner() && - !Boolean.FALSE.equals((Boolean)getClientProperty("JTable.autoStartsEdit"))) { + !Boolean.FALSE.equals(getClientProperty("JTable.autoStartsEdit"))) { // We do not have a binding for the event. Component editorComponent = getEditorComponent(); if (editorComponent == null) { @@ -5436,7 +5434,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable this.value = null; ((JComponent)getComponent()).setBorder(new LineBorder(Color.black)); try { - Class type = table.getColumnClass(column); + Class type = table.getColumnClass(column); // Since our obligation is to produce a value which is // assignable for the required type it is OK to use the // String constructor for columns which are declared @@ -6627,10 +6625,10 @@ public class JTable extends JComponent implements TableModelListener, Scrollable } else if (name.compareTo("tableCellEditor") == 0) { if (oldValue != null && oldValue instanceof TableCellEditor) { - ((TableCellEditor) oldValue).removeCellEditorListener((CellEditorListener) this); + ((TableCellEditor) oldValue).removeCellEditorListener(this); } if (newValue != null && newValue instanceof TableCellEditor) { - ((TableCellEditor) newValue).addCellEditorListener((CellEditorListener) this); + ((TableCellEditor) newValue).addCellEditorListener(this); } } } @@ -7045,7 +7043,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable */ public Accessible getAccessibleSelection(int i) { if (i < 0 || i > getAccessibleSelectionCount()) { - return (Accessible) null; + return null; } int rowsSel = JTable.this.getSelectedRowCount(); @@ -7158,7 +7156,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable return getAccessibleChild((r * ttlCols) + c); } } - return (Accessible) null; + return null; } /** @@ -7906,7 +7904,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable JTable.this, getValueAt(row, column), false, false, row, column); if (component instanceof Accessible) { - return ((Accessible) component).getAccessibleContext(); + return component.getAccessibleContext(); } else { return null; } diff --git a/jdk/src/share/classes/javax/swing/JTextField.java b/jdk/src/share/classes/javax/swing/JTextField.java index b6d3b47f285..56ca320a746 100644 --- a/jdk/src/share/classes/javax/swing/JTextField.java +++ b/jdk/src/share/classes/javax/swing/JTextField.java @@ -475,8 +475,7 @@ public class JTextField extends JTextComponent implements SwingConstants { * @since 1.4 */ public synchronized ActionListener[] getActionListeners() { - return (ActionListener[])listenerList.getListeners( - ActionListener.class); + return listenerList.getListeners(ActionListener.class); } /** diff --git a/jdk/src/share/classes/javax/swing/JTree.java b/jdk/src/share/classes/javax/swing/JTree.java index e6aa08c054e..012db5063dc 100644 --- a/jdk/src/share/classes/javax/swing/JTree.java +++ b/jdk/src/share/classes/javax/swing/JTree.java @@ -187,7 +187,7 @@ public class JTree extends JComponent implements Scrollable, Accessible * information must be determined by visiting all the parent * paths and seeing if they are visible. */ - transient private Hashtable expandedState; + transient private Hashtable expandedState; /** @@ -281,7 +281,7 @@ public class JTree extends JComponent implements Scrollable, Accessible * Used when setExpandedState is invoked, * will be a Stack of Stacks. */ - transient private Stack expandedStack; + transient private Stack> expandedStack; /** * Lead selection path, may not be null. @@ -652,9 +652,9 @@ public class JTree extends JComponent implements Scrollable, Accessible @ConstructorProperties({"model"}) public JTree(TreeModel newModel) { super(); - expandedStack = new Stack(); + expandedStack = new Stack>(); toggleClickCount = 2; - expandedState = new Hashtable(); + expandedState = new Hashtable(); setLayout(null); rowHeight = 16; visibleRowCount = 20; @@ -691,7 +691,7 @@ public class JTree extends JComponent implements Scrollable, Accessible * description: The UI object that implements the Component's LookAndFeel. */ public void setUI(TreeUI ui) { - if ((TreeUI)this.ui != ui) { + if (this.ui != ui) { settingUI = true; uiTreeExpansionListener = null; try { @@ -1298,8 +1298,8 @@ public class JTree extends JComponent implements Scrollable, Accessible Object root = (model == null) ? null : model.getRoot(); TreePath rootPath = (root == null) ? null : new TreePath(root); - TreePath child = null; - TreePath parent = null; + TreePath child; + TreePath parent; boolean outside = row == -1 || p.y < bounds.y || p.y >= bounds.y + bounds.height; @@ -1940,14 +1940,14 @@ public class JTree extends JComponent implements Scrollable, Accessible if(!isExpanded(parent)) return null; - Enumeration toggledPaths = expandedState.keys(); - Vector elements = null; + Enumeration toggledPaths = expandedState.keys(); + Vector elements = null; TreePath path; Object value; if(toggledPaths != null) { while(toggledPaths.hasMoreElements()) { - path = (TreePath)toggledPaths.nextElement(); + path = toggledPaths.nextElement(); value = expandedState.get(path); // Add the path if it is expanded, a descendant of parent, // and it is visible (all parents expanded). This is rather @@ -1956,7 +1956,7 @@ public class JTree extends JComponent implements Scrollable, Accessible ((Boolean)value).booleanValue() && parent.isDescendant(path) && isVisible(path)) { if (elements == null) { - elements = new Vector(); + elements = new Vector(); } elements.addElement(path); } @@ -1990,9 +1990,9 @@ public class JTree extends JComponent implements Scrollable, Accessible return false; // Is this node expanded? - Object value = expandedState.get(path); + Boolean value = expandedState.get(path); - if(value == null || !((Boolean)value).booleanValue()) + if(value == null || !value.booleanValue()) return false; // It is, make sure its parent is also expanded. @@ -2018,7 +2018,7 @@ public class JTree extends JComponent implements Scrollable, Accessible TreePath path = tree.getPathForRow(this, row); if(path != null) { - Boolean value = (Boolean)expandedState.get(path); + Boolean value = expandedState.get(path); return (value != null && value.booleanValue()); } @@ -2704,8 +2704,7 @@ public class JTree extends JComponent implements Scrollable, Accessible * @since 1.4 */ public TreeExpansionListener[] getTreeExpansionListeners() { - return (TreeExpansionListener[])listenerList.getListeners( - TreeExpansionListener.class); + return listenerList.getListeners(TreeExpansionListener.class); } /** @@ -2737,8 +2736,7 @@ public class JTree extends JComponent implements Scrollable, Accessible * @since 1.4 */ public TreeWillExpandListener[] getTreeWillExpandListeners() { - return (TreeWillExpandListener[])listenerList.getListeners( - TreeWillExpandListener.class); + return listenerList.getListeners(TreeWillExpandListener.class); } /** @@ -2895,8 +2893,7 @@ public class JTree extends JComponent implements Scrollable, Accessible * @since 1.4 */ public TreeSelectionListener[] getTreeSelectionListeners() { - return (TreeSelectionListener[])listenerList.getListeners( - TreeSelectionListener.class); + return listenerList.getListeners(TreeSelectionListener.class); } /** @@ -3030,7 +3027,7 @@ public class JTree extends JComponent implements Scrollable, Accessible // Serialization support. private void writeObject(ObjectOutputStream s) throws IOException { - Vector values = new Vector(); + Vector values = new Vector(); s.defaultWriteObject(); // Save the cellRenderer, if its Serializable. @@ -3077,9 +3074,9 @@ public class JTree extends JComponent implements Scrollable, Accessible // Create an instance of expanded state. - expandedState = new Hashtable(); + expandedState = new Hashtable(); - expandedStack = new Stack(); + expandedStack = new Stack>(); Vector values = (Vector)s.readObject(); int indexCounter = 0; @@ -3132,13 +3129,13 @@ public class JTree extends JComponent implements Scrollable, Accessible TreeModel model = getModel(); if(model != null) { - Enumeration paths = expandedState.keys(); + Enumeration paths = expandedState.keys(); if(paths != null) { - Vector state = new Vector(); + Vector state = new Vector(); while(paths.hasMoreElements()) { - TreePath path = (TreePath)paths.nextElement(); + TreePath path = paths.nextElement(); Object archivePath; try { @@ -3502,7 +3499,7 @@ public class JTree extends JComponent implements Scrollable, Accessible */ public boolean getScrollableTracksViewportWidth() { if (getParent() instanceof JViewport) { - return (((JViewport)getParent()).getWidth() > getPreferredSize().width); + return getParent().getWidth() > getPreferredSize().width; } return false; } @@ -3518,7 +3515,7 @@ public class JTree extends JComponent implements Scrollable, Accessible */ public boolean getScrollableTracksViewportHeight() { if (getParent() instanceof JViewport) { - return (((JViewport)getParent()).getHeight() > getPreferredSize().height); + return getParent().getHeight() > getPreferredSize().height; } return false; } @@ -3535,14 +3532,14 @@ public class JTree extends JComponent implements Scrollable, Accessible protected void setExpandedState(TreePath path, boolean state) { if(path != null) { // Make sure all parents of path are expanded. - Stack stack; - TreePath parentPath = path.getParentPath(); + Stack stack; + TreePath parentPath = path.getParentPath(); if (expandedStack.size() == 0) { - stack = new Stack(); + stack = new Stack(); } else { - stack = (Stack)expandedStack.pop(); + stack = expandedStack.pop(); } try { @@ -3556,7 +3553,7 @@ public class JTree extends JComponent implements Scrollable, Accessible } } for(int counter = stack.size() - 1; counter >= 0; counter--) { - parentPath = (TreePath)stack.pop(); + parentPath = stack.pop(); if(!isExpanded(parentPath)) { try { fireTreeWillExpand(parentPath); @@ -3636,12 +3633,11 @@ public class JTree extends JComponent implements Scrollable, Accessible if(parent == null) return null; - Vector descendants = new Vector(); - Enumeration nodes = expandedState.keys(); - TreePath path; + Vector descendants = new Vector(); + Enumeration nodes = expandedState.keys(); while(nodes.hasMoreElements()) { - path = (TreePath)nodes.nextElement(); + TreePath path = nodes.nextElement(); if(parent.isDescendant(path)) descendants.addElement(path); } @@ -3664,8 +3660,8 @@ public class JTree extends JComponent implements Scrollable, Accessible { if(toRemove != null) { while(toRemove.hasMoreElements()) { - Enumeration descendants = getDescendantToggledPaths - ((TreePath)toRemove.nextElement()); + Enumeration descendants = getDescendantToggledPaths + (toRemove.nextElement()); if(descendants != null) { while(descendants.hasMoreElements()) { @@ -4250,7 +4246,7 @@ public class JTree extends JComponent implements Scrollable, Accessible private AccessibleContext getCurrentAccessibleContext() { Component c = getCurrentComponent(); if (c instanceof Accessible) { - return (((Accessible) c).getAccessibleContext()); + return c.getAccessibleContext(); } else { return null; } @@ -4573,7 +4569,7 @@ public class JTree extends JComponent implements Scrollable, Accessible private AccessibleContext getCurrentAccessibleContext() { Component c = getCurrentComponent(); if (c instanceof Accessible) { - return (((Accessible) c).getAccessibleContext()); + return c.getAccessibleContext(); } else { return null; } @@ -5117,12 +5113,8 @@ public class JTree extends JComponent implements Scrollable, Accessible public boolean isVisible() { Rectangle pathBounds = tree.getPathBounds(path); Rectangle parentBounds = tree.getVisibleRect(); - if (pathBounds != null && parentBounds != null && - parentBounds.intersects(pathBounds)) { - return true; - } else { - return false; - } + return pathBounds != null && parentBounds != null && + parentBounds.intersects(pathBounds); } public void setVisible(boolean b) { diff --git a/jdk/src/share/classes/javax/swing/JViewport.java b/jdk/src/share/classes/javax/swing/JViewport.java index f5a16bbd2c6..734e80a0557 100644 --- a/jdk/src/share/classes/javax/swing/JViewport.java +++ b/jdk/src/share/classes/javax/swing/JViewport.java @@ -389,7 +389,7 @@ public class JViewport extends JComponent implements Accessible // could be bigger than invalid size. validateView(); } - int dx = 0, dy = 0; + int dx, dy; dx = positionAdjustment(getWidth(), contentRect.width, contentRect.x); dy = positionAdjustment(getHeight(), contentRect.height, contentRect.y); @@ -682,10 +682,7 @@ public class JViewport extends JComponent implements Accessible * @see JComponent#isPaintingOrigin() */ boolean isPaintingOrigin() { - if (scrollMode == BACKINGSTORE_SCROLL_MODE) { - return true; - } - return false; + return scrollMode == BACKINGSTORE_SCROLL_MODE; } @@ -903,11 +900,7 @@ public class JViewport extends JComponent implements Accessible */ public void setScrollMode(int mode) { scrollMode = mode; - if (mode == BACKINGSTORE_SCROLL_MODE) { - backingStore = true; - } else { - backingStore = false; - } + backingStore = mode == BACKINGSTORE_SCROLL_MODE; } /** @@ -958,10 +951,10 @@ public class JViewport extends JComponent implements Accessible } } - private final boolean isBlitting() { + private boolean isBlitting() { Component view = getView(); return (scrollMode == BLIT_SCROLL_MODE) && - (view instanceof JComponent) && ((JComponent)view).isOpaque(); + (view instanceof JComponent) && view.isOpaque(); } @@ -1380,8 +1373,7 @@ public class JViewport extends JComponent implements Accessible * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } /** diff --git a/jdk/src/share/classes/javax/swing/JWindow.java b/jdk/src/share/classes/javax/swing/JWindow.java index c94803c4c4d..d805838b0e0 100644 --- a/jdk/src/share/classes/javax/swing/JWindow.java +++ b/jdk/src/share/classes/javax/swing/JWindow.java @@ -185,7 +185,7 @@ public class JWindow extends Window implements Accessible, super(owner == null? SwingUtilities.getSharedOwnerFrame() : owner); if (owner == null) { WindowListener ownerShutdownListener = - (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener(); + SwingUtilities.getSharedOwnerFrameShutdownListener(); addWindowListener(ownerShutdownListener); } windowInit(); @@ -212,7 +212,7 @@ public class JWindow extends Window implements Accessible, owner); if (owner == null) { WindowListener ownerShutdownListener = - (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener(); + SwingUtilities.getSharedOwnerFrameShutdownListener(); addWindowListener(ownerShutdownListener); } windowInit(); @@ -250,7 +250,7 @@ public class JWindow extends Window implements Accessible, owner, gc); if (owner == null) { WindowListener ownerShutdownListener = - (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener(); + SwingUtilities.getSharedOwnerFrameShutdownListener(); addWindowListener(ownerShutdownListener); } windowInit(); diff --git a/jdk/src/share/classes/javax/swing/KeyboardManager.java b/jdk/src/share/classes/javax/swing/KeyboardManager.java index e27a72f3d32..d5ed58ba003 100644 --- a/jdk/src/share/classes/javax/swing/KeyboardManager.java +++ b/jdk/src/share/classes/javax/swing/KeyboardManager.java @@ -68,13 +68,13 @@ class KeyboardManager { /** * maps top-level containers to a sub-hashtable full of keystrokes */ - Hashtable containerMap = new Hashtable(); + Hashtable containerMap = new Hashtable(); /** * Maps component/keystroke pairs to a topLevel container * This is mainly used for fast unregister operations */ - Hashtable componentKeyStrokeMap = new Hashtable(); + Hashtable componentKeyStrokeMap = new Hashtable(); public static KeyboardManager getCurrentManager() { return currentManager; @@ -95,7 +95,7 @@ class KeyboardManager { if (topContainer == null) { return; } - Hashtable keyMap = (Hashtable)containerMap.get(topContainer); + Hashtable keyMap = containerMap.get(topContainer); if (keyMap == null) { // lazy evaluate one keyMap = registerNewTopContainer(topContainer); @@ -114,8 +114,8 @@ class KeyboardManager { // Then add the old compoennt and the new compoent to the vector // then insert the vector in the table if (tmp != c) { // this means this is already registered for this component, no need to dup - Vector v = new Vector(); - v.addElement(tmp); + Vector v = new Vector(); + v.addElement((JComponent) tmp); v.addElement(c); keyMap.put(k, v); } @@ -154,13 +154,13 @@ class KeyboardManager { ComponentKeyStrokePair ckp = new ComponentKeyStrokePair(c,ks); - Object topContainer = componentKeyStrokeMap.get(ckp); + Container topContainer = componentKeyStrokeMap.get(ckp); if (topContainer == null) { // never heard of this pairing, so bail return; } - Hashtable keyMap = (Hashtable)containerMap.get(topContainer); + Hashtable keyMap = containerMap.get(topContainer); if (keyMap == null) { // this should never happen, but I'm being safe Thread.dumpStack(); return; @@ -221,7 +221,7 @@ class KeyboardManager { ks=KeyStroke.getKeyStroke(e.getKeyCode(), e.getModifiers(), !pressed); } - Hashtable keyMap = (Hashtable)containerMap.get(topAncestor); + Hashtable keyMap = containerMap.get(topAncestor); if (keyMap != null) { // this container isn't registered, so bail Object tmp = keyMap.get(ks); @@ -293,7 +293,7 @@ class KeyboardManager { if (top == null) { return; } - Hashtable keyMap = (Hashtable)containerMap.get(top); + Hashtable keyMap = containerMap.get(top); if (keyMap == null) { // lazy evaluate one keyMap = registerNewTopContainer(top); @@ -314,11 +314,11 @@ class KeyboardManager { public void unregisterMenuBar(JMenuBar mb) { - Object topContainer = getTopAncestor(mb); + Container topContainer = getTopAncestor(mb); if (topContainer == null) { return; } - Hashtable keyMap = (Hashtable)containerMap.get(topContainer); + Hashtable keyMap = containerMap.get(topContainer); if (keyMap!=null) { Vector v = (Vector)keyMap.get(JMenuBar.class); if (v != null) { diff --git a/jdk/src/share/classes/javax/swing/LayoutComparator.java b/jdk/src/share/classes/javax/swing/LayoutComparator.java index 42d85c70cb5..01ba6e54df0 100644 --- a/jdk/src/share/classes/javax/swing/LayoutComparator.java +++ b/jdk/src/share/classes/javax/swing/LayoutComparator.java @@ -39,7 +39,7 @@ import java.awt.Window; * * @author David Mendenhall */ -final class LayoutComparator implements Comparator, java.io.Serializable { +final class LayoutComparator implements Comparator, java.io.Serializable { private static final int ROW_TOLERANCE = 10; @@ -51,10 +51,7 @@ final class LayoutComparator implements Comparator, java.io.Serializable { leftToRight = orientation.isLeftToRight(); } - public int compare(Object o1, Object o2) { - Component a = (Component)o1; - Component b = (Component)o2; - + public int compare(Component a, Component b) { if (a == b) { return 0; } @@ -65,9 +62,9 @@ final class LayoutComparator implements Comparator, java.io.Serializable { // each Component and then search from the Window down until the // hierarchy branches. if (a.getParent() != b.getParent()) { - LinkedList aAncestory, bAncestory; + LinkedList aAncestory = new LinkedList(); - for(aAncestory = new LinkedList(); a != null; a = a.getParent()) { + for(; a != null; a = a.getParent()) { aAncestory.add(a); if (a instanceof Window) { break; @@ -78,7 +75,9 @@ final class LayoutComparator implements Comparator, java.io.Serializable { throw new ClassCastException(); } - for(bAncestory = new LinkedList(); b != null; b = b.getParent()) { + LinkedList bAncestory = new LinkedList(); + + for(; b != null; b = b.getParent()) { bAncestory.add(b); if (b instanceof Window) { break; @@ -89,18 +88,18 @@ final class LayoutComparator implements Comparator, java.io.Serializable { throw new ClassCastException(); } - for (ListIterator + for (ListIterator aIter = aAncestory.listIterator(aAncestory.size()), bIter = bAncestory.listIterator(bAncestory.size()); ;) { if (aIter.hasPrevious()) { - a = (Component)aIter.previous(); + a = aIter.previous(); } else { // a is an ancestor of b return -1; } if (bIter.hasPrevious()) { - b = (Component)bIter.previous(); + b = bIter.previous(); } else { // b is an ancestor of a return 1; diff --git a/jdk/src/share/classes/javax/swing/LayoutFocusTraversalPolicy.java b/jdk/src/share/classes/javax/swing/LayoutFocusTraversalPolicy.java index 7e200e02eaf..33d81a91a48 100644 --- a/jdk/src/share/classes/javax/swing/LayoutFocusTraversalPolicy.java +++ b/jdk/src/share/classes/javax/swing/LayoutFocusTraversalPolicy.java @@ -65,7 +65,7 @@ public class LayoutFocusTraversalPolicy extends SortingFocusTraversalPolicy * Constructs a LayoutFocusTraversalPolicy with the passed in * Comparator. */ - LayoutFocusTraversalPolicy(Comparator c) { + LayoutFocusTraversalPolicy(Comparator c) { super(c); } diff --git a/jdk/src/share/classes/javax/swing/LegacyGlueFocusTraversalPolicy.java b/jdk/src/share/classes/javax/swing/LegacyGlueFocusTraversalPolicy.java index f8a37fe7a2b..fe73a08957f 100644 --- a/jdk/src/share/classes/javax/swing/LegacyGlueFocusTraversalPolicy.java +++ b/jdk/src/share/classes/javax/swing/LegacyGlueFocusTraversalPolicy.java @@ -48,8 +48,8 @@ final class LegacyGlueFocusTraversalPolicy extends FocusTraversalPolicy private transient FocusTraversalPolicy delegatePolicy; private transient DefaultFocusManager delegateManager; - private HashMap forwardMap = new HashMap(), - backwardMap = new HashMap(); + private HashMap forwardMap = new HashMap(), + backwardMap = new HashMap(); LegacyGlueFocusTraversalPolicy(FocusTraversalPolicy delegatePolicy) { this.delegatePolicy = delegatePolicy; @@ -70,11 +70,11 @@ final class LegacyGlueFocusTraversalPolicy extends FocusTraversalPolicy public Component getComponentAfter(Container focusCycleRoot, Component aComponent) { Component hardCoded = aComponent, prevHardCoded; - HashSet sanity = new HashSet(); + HashSet sanity = new HashSet(); do { prevHardCoded = hardCoded; - hardCoded = (Component)forwardMap.get(hardCoded); + hardCoded = forwardMap.get(hardCoded); if (hardCoded == null) { if (delegatePolicy != null && prevHardCoded.isFocusCycleRoot(focusCycleRoot)) { @@ -99,11 +99,11 @@ final class LegacyGlueFocusTraversalPolicy extends FocusTraversalPolicy public Component getComponentBefore(Container focusCycleRoot, Component aComponent) { Component hardCoded = aComponent, prevHardCoded; - HashSet sanity = new HashSet(); + HashSet sanity = new HashSet(); do { prevHardCoded = hardCoded; - hardCoded = (Component)backwardMap.get(hardCoded); + hardCoded = backwardMap.get(hardCoded); if (hardCoded == null) { if (delegatePolicy != null && prevHardCoded.isFocusCycleRoot(focusCycleRoot)) { diff --git a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java index 8e1f36a3aa0..e1234c69aa6 100644 --- a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java +++ b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java @@ -37,7 +37,7 @@ import sun.awt.AppContext; * @author Arnaud Weber */ public class MenuSelectionManager { - private Vector selection = new Vector(); + private Vector selection = new Vector(); /* diagnostic aids -- should be false for production builds. */ private static final boolean TRACE = false; // trace creates and disposes @@ -100,14 +100,14 @@ public class MenuSelectionManager { } for(i=0,c=path.length;i= firstDifference ; i--) { - MenuElement me = (MenuElement)selection.elementAt(i); + MenuElement me = selection.elementAt(i); selection.removeElementAt(i); me.menuSelectionChanged(false); } @@ -131,7 +131,7 @@ public class MenuSelectionManager { MenuElement res[] = new MenuElement[selection.size()]; int i,c; for(i=0,c=selection.size();i 0) { - MenuElement me = (MenuElement)selection.elementAt(0); + MenuElement me = selection.elementAt(0); return isComponentPartOfCurrentMenu(me,c); } else return false; diff --git a/jdk/src/share/classes/javax/swing/MultiUIDefaults.java b/jdk/src/share/classes/javax/swing/MultiUIDefaults.java index 30867e22804..d7d435ef15f 100644 --- a/jdk/src/share/classes/javax/swing/MultiUIDefaults.java +++ b/jdk/src/share/classes/javax/swing/MultiUIDefaults.java @@ -56,8 +56,7 @@ class MultiUIDefaults extends UIDefaults return value; } - for(int i = 0; i < tables.length; i++) { - UIDefaults table = tables[i]; + for (UIDefaults table : tables) { value = (table != null) ? table.get(key) : null; if (value != null) { return value; @@ -75,8 +74,7 @@ class MultiUIDefaults extends UIDefaults return value; } - for(int i = 0; i < tables.length; i++) { - UIDefaults table = tables[i]; + for (UIDefaults table : tables) { value = (table != null) ? table.get(key,l) : null; if (value != null) { return value; @@ -89,8 +87,7 @@ class MultiUIDefaults extends UIDefaults public int size() { int n = super.size(); - for(int i = 0; i < tables.length; i++) { - UIDefaults table = tables[i]; + for (UIDefaults table : tables) { n += (table != null) ? table.size() : 0; } return n; @@ -102,7 +99,7 @@ class MultiUIDefaults extends UIDefaults } - public Enumeration keys() + public Enumeration keys() { Enumeration[] enums = new Enumeration[1 + tables.length]; enums[0] = super.keys(); @@ -116,7 +113,7 @@ class MultiUIDefaults extends UIDefaults } - public Enumeration elements() + public Enumeration elements() { Enumeration[] enums = new Enumeration[1 + tables.length]; enums[0] = super.elements(); @@ -137,7 +134,7 @@ class MultiUIDefaults extends UIDefaults } } - private static class MultiUIDefaultsEnumerator implements Enumeration + private static class MultiUIDefaultsEnumerator implements Enumeration { Enumeration[] enums; int n = 0; @@ -175,8 +172,7 @@ class MultiUIDefaults extends UIDefaults return value; } - for(int i = 0; i < tables.length; i++) { - UIDefaults table = tables[i]; + for (UIDefaults table : tables) { value = (table != null) ? table.remove(key) : null; if (value != null) { return value; @@ -189,8 +185,7 @@ class MultiUIDefaults extends UIDefaults public void clear() { super.clear(); - for(int i = 0; i < tables.length; i++) { - UIDefaults table = tables[i]; + for (UIDefaults table : tables) { if (table != null) { table.clear(); } diff --git a/jdk/src/share/classes/javax/swing/PopupFactory.java b/jdk/src/share/classes/javax/swing/PopupFactory.java index f9c3c0dd5d7..753959cea1f 100644 --- a/jdk/src/share/classes/javax/swing/PopupFactory.java +++ b/jdk/src/share/classes/javax/swing/PopupFactory.java @@ -313,9 +313,9 @@ public class PopupFactory { if(contents instanceof JPopupMenu) { JPopupMenu jpm = (JPopupMenu) contents; Component popComps[] = jpm.getComponents(); - for(int i=0;i cache; + Map> heavyPopupCache = getHeavyWeightPopupCache(); if (heavyPopupCache.containsKey(w)) { - cache = (List)heavyPopupCache.get(w); + cache = heavyPopupCache.get(w); } else { return null; } - int c; - if ((c = cache.size()) > 0) { - HeavyWeightPopup r = (HeavyWeightPopup)cache.get(0); + if (cache.size() > 0) { + HeavyWeightPopup r = cache.get(0); cache.remove(0); return r; } @@ -380,13 +379,13 @@ public class PopupFactory { * Window to a List of * HeavyWeightPopups. */ - private static Map getHeavyWeightPopupCache() { + private static Map> getHeavyWeightPopupCache() { synchronized (HeavyWeightPopup.class) { - Map cache = (Map)SwingUtilities.appContextGet( + Map> cache = (Map>)SwingUtilities.appContextGet( heavyWeightPopupCacheKey); if (cache == null) { - cache = new HashMap(2); + cache = new HashMap>(2); SwingUtilities.appContextPut(heavyWeightPopupCacheKey, cache); } @@ -399,13 +398,13 @@ public class PopupFactory { */ private static void recycleHeavyWeightPopup(HeavyWeightPopup popup) { synchronized (HeavyWeightPopup.class) { - List cache; - Object window = SwingUtilities.getWindowAncestor( + List cache; + Window window = SwingUtilities.getWindowAncestor( popup.getComponent()); - Map heavyPopupCache = getHeavyWeightPopupCache(); + Map> heavyPopupCache = getHeavyWeightPopupCache(); if (window instanceof Popup.DefaultFrame || - !((Window)window).isVisible()) { + !window.isVisible()) { // If the Window isn't visible, we don't cache it as we // likely won't ever get a windowClosed event to clean up. // We also don't cache DefaultFrames as this indicates @@ -414,28 +413,27 @@ public class PopupFactory { popup._dispose(); return; } else if (heavyPopupCache.containsKey(window)) { - cache = (List)heavyPopupCache.get(window); + cache = heavyPopupCache.get(window); } else { - cache = new ArrayList(); + cache = new ArrayList(); heavyPopupCache.put(window, cache); // Clean up if the Window is closed - final Window w = (Window)window; + final Window w = window; w.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { - List popups; + List popups; synchronized(HeavyWeightPopup.class) { - Map heavyPopupCache2 = + Map> heavyPopupCache2 = getHeavyWeightPopupCache(); - popups = (List)heavyPopupCache2.remove(w); + popups = heavyPopupCache2.remove(w); } if (popups != null) { for (int counter = popups.size() - 1; counter >= 0; counter--) { - ((HeavyWeightPopup)popups.get(counter)). - _dispose(); + popups.get(counter)._dispose(); } } } @@ -534,10 +532,9 @@ public class PopupFactory { Window[] ownedWindows = w.getOwnedWindows(); if(ownedWindows != null) { Rectangle bnd = component.getBounds(); - for(int i=0; i getLightWeightPopupCache() { + List cache = (List)SwingUtilities.appContextGet( lightWeightPopupCacheKey); if (cache == null) { - cache = new ArrayList(); + cache = new ArrayList(); SwingUtilities.appContextPut(lightWeightPopupCacheKey, cache); } return cache; @@ -682,7 +679,7 @@ public class PopupFactory { */ private static void recycleLightWeightPopup(LightWeightPopup popup) { synchronized (LightWeightPopup.class) { - List lightPopupCache = getLightWeightPopupCache(); + List lightPopupCache = getLightWeightPopupCache(); if (lightPopupCache.size() < MAX_CACHE_SIZE) { lightPopupCache.add(popup); } @@ -695,11 +692,9 @@ public class PopupFactory { */ private static LightWeightPopup getRecycledLightWeightPopup() { synchronized (LightWeightPopup.class) { - List lightPopupCache = getLightWeightPopupCache(); - int c; - if((c = lightPopupCache.size()) > 0) { - LightWeightPopup r = (LightWeightPopup)lightPopupCache. - get(0); + List lightPopupCache = getLightWeightPopupCache(); + if (lightPopupCache.size() > 0) { + LightWeightPopup r = lightPopupCache.get(0); lightPopupCache.remove(0); return r; } @@ -755,8 +750,7 @@ public class PopupFactory { component.setLocation(p.x, p.y); if (parent instanceof JLayeredPane) { - ((JLayeredPane)parent).add(component, - JLayeredPane.POPUP_LAYER, 0); + parent.add(component, JLayeredPane.POPUP_LAYER, 0); } else { parent.add(component); } @@ -826,12 +820,12 @@ public class PopupFactory { /** * Returns the cache to use for medium weight popups. */ - private static List getMediumWeightPopupCache() { - List cache = (List)SwingUtilities.appContextGet( + private static List getMediumWeightPopupCache() { + List cache = (List)SwingUtilities.appContextGet( mediumWeightPopupCacheKey); if (cache == null) { - cache = new ArrayList(); + cache = new ArrayList(); SwingUtilities.appContextPut(mediumWeightPopupCacheKey, cache); } return cache; @@ -842,7 +836,7 @@ public class PopupFactory { */ private static void recycleMediumWeightPopup(MediumWeightPopup popup) { synchronized (MediumWeightPopup.class) { - List mediumPopupCache = getMediumWeightPopupCache(); + List mediumPopupCache = getMediumWeightPopupCache(); if (mediumPopupCache.size() < MAX_CACHE_SIZE) { mediumPopupCache.add(popup); } @@ -855,12 +849,9 @@ public class PopupFactory { */ private static MediumWeightPopup getRecycledMediumWeightPopup() { synchronized (MediumWeightPopup.class) { - java.util.List mediumPopupCache = - getMediumWeightPopupCache(); - int c; - if ((c=mediumPopupCache.size()) > 0) { - MediumWeightPopup r = (MediumWeightPopup)mediumPopupCache. - get(0); + List mediumPopupCache = getMediumWeightPopupCache(); + if (mediumPopupCache.size() > 0) { + MediumWeightPopup r = mediumPopupCache.get(0); mediumPopupCache.remove(0); return r; } @@ -904,7 +895,7 @@ public class PopupFactory { x, y); component.setVisible(false); component.setLocation(p.x, p.y); - ((JLayeredPane)parent).add(component, JLayeredPane.POPUP_LAYER, + parent.add(component, JLayeredPane.POPUP_LAYER, 0); } else { Point p = SwingUtilities.convertScreenLocationToParent(parent, diff --git a/jdk/src/share/classes/javax/swing/RepaintManager.java b/jdk/src/share/classes/javax/swing/RepaintManager.java index 81c81602255..b0e6c048f62 100644 --- a/jdk/src/share/classes/javax/swing/RepaintManager.java +++ b/jdk/src/share/classes/javax/swing/RepaintManager.java @@ -589,7 +589,7 @@ public class RepaintManager */ private synchronized boolean extendDirtyRegion( Component c, int x, int y, int w, int h) { - Rectangle r = (Rectangle)dirtyComponents.get(c); + Rectangle r = dirtyComponents.get(c); if (r != null) { // A non-null r implies c is already marked as dirty, // and that the parent is valid. Therefore we can @@ -609,9 +609,9 @@ public class RepaintManager if (delegate != null) { return delegate.getDirtyRegion(aComponent); } - Rectangle r = null; + Rectangle r; synchronized(this) { - r = (Rectangle)dirtyComponents.get(aComponent); + r = dirtyComponents.get(aComponent); } if(r == null) return new Rectangle(0,0,0,0); @@ -745,8 +745,8 @@ public class RepaintManager Rectangle rect; int localBoundsX = 0; int localBoundsY = 0; - int localBoundsH = 0; - int localBoundsW = 0; + int localBoundsH; + int localBoundsW; Enumeration keys; roots = new ArrayList(count); @@ -853,7 +853,7 @@ public class RepaintManager dx = rootDx = 0; dy = rootDy = 0; - tmp.setBounds((Rectangle) dirtyComponents.get(dirtyComponent)); + tmp.setBounds(dirtyComponents.get(dirtyComponent)); // System.out.println("Collect dirty component for bound " + tmp + // "component bounds is " + cBounds);; @@ -900,7 +900,7 @@ public class RepaintManager Rectangle r; tmp.setLocation(tmp.x + rootDx - dx, tmp.y + rootDy - dy); - r = (Rectangle)dirtyComponents.get(rootDirtyComponent); + r = dirtyComponents.get(rootDirtyComponent); SwingUtilities.computeUnion(tmp.x,tmp.y,tmp.width,tmp.height,r); } @@ -985,7 +985,7 @@ public class RepaintManager private Image _getOffscreenBuffer(Component c, int proposedWidth, int proposedHeight) { Dimension maxSize = getDoubleBufferMaximumSize(); - DoubleBufferInfo doubleBuffer = null; + DoubleBufferInfo doubleBuffer; int width, height; if (standardDoubleBuffer == null) { @@ -1054,7 +1054,7 @@ public class RepaintManager Iterator gcs = volatileMap.keySet().iterator(); while (gcs.hasNext()) { GraphicsConfiguration gc = (GraphicsConfiguration)gcs.next(); - VolatileImage image = (VolatileImage)volatileMap.get(gc); + VolatileImage image = volatileMap.get(gc); if (image.getWidth() > width || image.getHeight() > height) { image.flush(); gcs.remove(); @@ -1222,7 +1222,7 @@ public class RepaintManager */ void beginPaint() { boolean multiThreadedPaint = false; - int paintDepth = 0; + int paintDepth; Thread currentThread = Thread.currentThread(); synchronized(this) { paintDepth = this.paintDepth; diff --git a/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java b/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java index e920acccba2..85a2bb96a25 100644 --- a/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java +++ b/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java @@ -79,7 +79,7 @@ public class SortingFocusTraversalPolicy * sorted list should be reused if possible. */ transient private Container cachedRoot; - transient private List cachedCycle; + transient private List cachedCycle; // Delegate our fitness test to ContainerOrder so that we only have to // code the algorithm once. @@ -111,7 +111,7 @@ public class SortingFocusTraversalPolicy return cycle; } private int getComponentIndex(List cycle, Component aComponent) { - int index = 0; + int index; try { index = Collections.binarySearch(cycle, aComponent, comparator); } catch (ClassCastException e) { @@ -130,14 +130,14 @@ public class SortingFocusTraversalPolicy return index; } - private void enumerateAndSortCycle(Container focusCycleRoot, List cycle) { + private void enumerateAndSortCycle(Container focusCycleRoot, List cycle) { if (focusCycleRoot.isShowing()) { enumerateCycle(focusCycleRoot, cycle); Collections.sort(cycle, comparator); } } - private void enumerateCycle(Container container, List cycle) { + private void enumerateCycle(Container container, List cycle) { if (!(container.isVisible() && container.isDisplayable())) { return; } @@ -145,8 +145,7 @@ public class SortingFocusTraversalPolicy cycle.add(container); Component[] components = container.getComponents(); - for (int i = 0; i < components.length; i++) { - Component comp = components[i]; + for (Component comp : components) { if (comp instanceof Container) { Container cont = (Container)comp; @@ -385,8 +384,8 @@ public class SortingFocusTraversalPolicy return getLastComponent(aContainer); } - Component comp = null; - Component tryComp = null; + Component comp; + Component tryComp; for (index--; index>=0; index--) { comp = cycle.get(index); @@ -442,8 +441,7 @@ public class SortingFocusTraversalPolicy } if (log.isLoggable(Level.FINE)) log.fine("### Cycle is " + cycle); - for (int i = 0; i < cycle.size(); i++) { - Component comp = cycle.get(i); + for (Component comp : cycle) { if (accept(comp)) { return comp; } else if (comp instanceof Container && comp != aContainer) { diff --git a/jdk/src/share/classes/javax/swing/SpringLayout.java b/jdk/src/share/classes/javax/swing/SpringLayout.java index 34847944219..e825f4c6104 100644 --- a/jdk/src/share/classes/javax/swing/SpringLayout.java +++ b/jdk/src/share/classes/javax/swing/SpringLayout.java @@ -185,11 +185,11 @@ import java.util.*; * @since 1.4 */ public class SpringLayout implements LayoutManager2 { - private Map componentConstraints = new HashMap(); + private Map componentConstraints = new HashMap(); private Spring cyclicReference = Spring.constant(Spring.UNSET); - private Set cyclicSprings; - private Set acyclicSprings; + private Set cyclicSprings; + private Set acyclicSprings; /** @@ -415,8 +415,7 @@ public class SpringLayout implements LayoutManager2 { } if (!valid) { String[] all = horizontal ? ALL_HORIZONTAL : ALL_VERTICAL; - for (int i = 0; i < all.length; i++) { - String s = all[i]; + for (String s : all) { if (!history.contains(s)) { setConstraint(s, null); } @@ -822,8 +821,7 @@ public class SpringLayout implements LayoutManager2 { /*pp*/ void reset() { Spring[] allSprings = {x, y, width, height, east, south, horizontalCenter, verticalCenter, baseline}; - for (int i = 0; i < allSprings.length; i++) { - Spring s = allSprings[i]; + for (Spring s : allSprings) { if (s != null) { s.setValue(Spring.UNSET); } @@ -881,8 +879,8 @@ public class SpringLayout implements LayoutManager2 { public SpringLayout() {} private void resetCyclicStatuses() { - cyclicSprings = new HashSet(); - acyclicSprings = new HashSet(); + cyclicSprings = new HashSet(); + acyclicSprings = new HashSet(); } private void setParent(Container p) { @@ -1145,7 +1143,7 @@ public class SpringLayout implements LayoutManager2 { * @return the constraints for the specified component */ public Constraints getConstraints(Component c) { - Constraints result = (Constraints)componentConstraints.get(c); + Constraints result = componentConstraints.get(c); if (result == null) { if (c instanceof javax.swing.JComponent) { Object cp = ((javax.swing.JComponent)c).getClientProperty(SpringLayout.class); diff --git a/jdk/src/share/classes/javax/swing/SwingUtilities.java b/jdk/src/share/classes/javax/swing/SwingUtilities.java index 38f18e78122..0493510a7bb 100644 --- a/jdk/src/share/classes/javax/swing/SwingUtilities.java +++ b/jdk/src/share/classes/javax/swing/SwingUtilities.java @@ -108,11 +108,8 @@ public class SwingUtilities implements SwingConstants * Return true if a contains b */ public static final boolean isRectangleContainingRectangle(Rectangle a,Rectangle b) { - if (b.x >= a.x && (b.x + b.width) <= (a.x + a.width) && - b.y >= a.y && (b.y + b.height) <= (a.y + a.height)) { - return true; - } - return false; + return b.x >= a.x && (b.x + b.width) <= (a.x + a.width) && + b.y >= a.y && (b.y + b.height) <= (a.y + a.height); } /** @@ -272,8 +269,7 @@ public class SwingUtilities implements SwingConstants } if (parent instanceof Container) { Component components[] = ((Container)parent).getComponents(); - for (int i = 0 ; i < components.length ; i++) { - Component comp = components[i]; + for (Component comp : components) { if (comp != null && comp.isVisible()) { Point loc = comp.getLocation(); if (comp instanceof Container) { @@ -376,8 +372,8 @@ public class SwingUtilities implements SwingConstants do { if(c instanceof JComponent) { - x = ((JComponent)c).getX(); - y = ((JComponent)c).getY(); + x = c.getX(); + y = c.getY(); } else if(c instanceof java.applet.Applet || c instanceof java.awt.Window) { try { @@ -415,8 +411,8 @@ public class SwingUtilities implements SwingConstants do { if(c instanceof JComponent) { - x = ((JComponent)c).getX(); - y = ((JComponent)c).getY(); + x = c.getX(); + y = c.getY(); } else if(c instanceof java.applet.Applet || c instanceof java.awt.Window) { try { @@ -980,7 +976,7 @@ public class SwingUtilities implements SwingConstants */ int gap; - View v = null; + View v; if (textIsEmpty) { textR.width = textR.height = 0; text = ""; @@ -1248,8 +1244,8 @@ public class SwingUtilities implements SwingConstants children = ((Container)c).getComponents(); } if (children != null) { - for(int i = 0; i < children.length; i++) { - updateComponentTreeUI0(children[i]); + for (Component child : children) { + updateComponentTreeUI0(child); } } } @@ -1702,7 +1698,7 @@ public class SwingUtilities implements SwingConstants */ public static void replaceUIActionMap(JComponent component, ActionMap uiActionMap) { - ActionMap map = component.getActionMap((uiActionMap != null));; + ActionMap map = component.getActionMap((uiActionMap != null)); while (map != null) { ActionMap parent = map.getParent(); @@ -1770,8 +1766,7 @@ public class SwingUtilities implements SwingConstants */ void installListeners() { Window[] windows = getOwnedWindows(); - for (int ind = 0; ind < windows.length; ind++){ - Window window = windows[ind]; + for (Window window : windows) { if (window != null) { window.removeWindowListener(this); window.addWindowListener(this); @@ -1786,8 +1781,7 @@ public class SwingUtilities implements SwingConstants public void windowClosed(WindowEvent e) { synchronized(getTreeLock()) { Window[] windows = getOwnedWindows(); - for (int ind = 0; ind < windows.length; ind++) { - Window window = windows[ind]; + for (Window window : windows) { if (window != null) { if (window.isDisplayable()) { return; @@ -1875,7 +1869,7 @@ public class SwingUtilities implements SwingConstants } - static Class loadSystemClass(String className) throws ClassNotFoundException { + static Class loadSystemClass(String className) throws ClassNotFoundException { return Class.forName(className, true, Thread.currentThread(). getContextClassLoader()); } diff --git a/jdk/src/share/classes/javax/swing/Timer.java b/jdk/src/share/classes/javax/swing/Timer.java index a96d2ce8dc9..4f339158efc 100644 --- a/jdk/src/share/classes/javax/swing/Timer.java +++ b/jdk/src/share/classes/javax/swing/Timer.java @@ -270,8 +270,7 @@ public class Timer implements Serializable * @since 1.4 */ public ActionListener[] getActionListeners() { - return (ActionListener[])listenerList.getListeners( - ActionListener.class); + return listenerList.getListeners(ActionListener.class); } diff --git a/jdk/src/share/classes/javax/swing/TimerQueue.java b/jdk/src/share/classes/javax/swing/TimerQueue.java index 1f694d1c820..f68f4e99688 100644 --- a/jdk/src/share/classes/javax/swing/TimerQueue.java +++ b/jdk/src/share/classes/javax/swing/TimerQueue.java @@ -97,7 +97,7 @@ class TimerQueue implements Runnable final ThreadGroup threadGroup = AppContext.getAppContext().getThreadGroup(); java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction() { public Object run() { Thread timerThread = new Thread(threadGroup, TimerQueue.this, "TimerQueue"); @@ -226,7 +226,7 @@ class TimerQueue implements Runnable /** * Returns nanosecond time offset by origin */ - private final static long now() { + private static long now() { return System.nanoTime() - NANO_ORIGIN; } diff --git a/jdk/src/share/classes/javax/swing/UIDefaults.java b/jdk/src/share/classes/javax/swing/UIDefaults.java index 302dc00b0dd..7a372e79753 100644 --- a/jdk/src/share/classes/javax/swing/UIDefaults.java +++ b/jdk/src/share/classes/javax/swing/UIDefaults.java @@ -72,11 +72,11 @@ import sun.util.CoreResourceBundleControl; */ public class UIDefaults extends Hashtable { - private static final Object PENDING = new String("Pending"); + private static final Object PENDING = "Pending"; private SwingPropertyChangeSupport changeSupport; - private Vector resourceBundles; + private Vector resourceBundles; private Locale defaultLocale = Locale.getDefault(); @@ -86,7 +86,7 @@ public class UIDefaults extends Hashtable * Access to this should be done while holding a lock on the * UIDefaults, eg synchronized(this). */ - private Map resourceCache; + private Map> resourceCache; /** * Creates an empty defaults table. @@ -106,7 +106,7 @@ public class UIDefaults extends Hashtable */ public UIDefaults(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); - resourceCache = new HashMap(); + resourceCache = new HashMap>(); } @@ -281,24 +281,24 @@ public class UIDefaults extends Hashtable if( defaultLocale == null ) return null; else - l = (Locale)defaultLocale; + l = defaultLocale; } synchronized(this) { - return getResourceCache(l).get((String)key); + return getResourceCache(l).get(key); } } /** * Returns a Map of the known resources for the given locale. */ - private Map getResourceCache(Locale l) { - Map values = (Map)resourceCache.get(l); + private Map getResourceCache(Locale l) { + Map values = resourceCache.get(l); if (values == null) { - values = new HashMap(); + values = new HashMap(); for (int i=resourceBundles.size()-1; i >= 0; i--) { - String bundleName = (String)resourceBundles.get(i); + String bundleName = resourceBundles.get(i); try { Control c = CoreResourceBundleControl.getRBControlInstance(bundleName); ResourceBundle b; @@ -751,7 +751,7 @@ public class UIDefaults extends Hashtable Object cl = get("ClassLoader"); ClassLoader uiClassLoader = (cl != null) ? (ClassLoader)cl : target.getClass().getClassLoader(); - Class uiClass = getUIClass(target.getUIClassID(), uiClassLoader); + Class uiClass = getUIClass(target.getUIClassID(), uiClassLoader); Object uiObject = null; if (uiClass == null) { @@ -761,8 +761,7 @@ public class UIDefaults extends Hashtable try { Method m = (Method)get(uiClass); if (m == null) { - Class acClass = javax.swing.JComponent.class; - m = uiClass.getMethod("createUI", new Class[]{acClass}); + m = uiClass.getMethod("createUI", new Class[]{JComponent.class}); put(uiClass, m); } uiObject = MethodUtil.invoke(m, null, new Object[]{target}); @@ -862,7 +861,7 @@ public class UIDefaults extends Hashtable return; } if( resourceBundles == null ) { - resourceBundles = new Vector(5); + resourceBundles = new Vector(5); } if (!resourceBundles.contains(bundleName)) { resourceBundles.add( bundleName ); @@ -1064,7 +1063,7 @@ public class UIDefaults extends Hashtable className = c; methodName = m; if (o != null) { - args = (Object[])o.clone(); + args = o.clone(); } } @@ -1079,10 +1078,10 @@ public class UIDefaults extends Hashtable // In order to pick up the security policy in effect at the // time of creation we use a doPrivileged with the // AccessControlContext that was in place when this was created. - return AccessController.doPrivileged(new PrivilegedAction() { + return AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { - Class c; + Class c; Object cl; // See if we should use a separate ClassLoader if (table == null || !((cl = table.get("ClassLoader")) diff --git a/jdk/src/share/classes/javax/swing/UIManager.java b/jdk/src/share/classes/javax/swing/UIManager.java index 6fb543d3374..a4a62f0096c 100644 --- a/jdk/src/share/classes/javax/swing/UIManager.java +++ b/jdk/src/share/classes/javax/swing/UIManager.java @@ -191,7 +191,7 @@ public class UIManager implements Serializable MultiUIDefaults multiUIDefaults = new MultiUIDefaults(tables); LookAndFeel lookAndFeel; LookAndFeel multiLookAndFeel = null; - Vector auxLookAndFeels = null; + Vector auxLookAndFeels = null; SwingPropertyChangeSupport changeSupport; UIDefaults getLookAndFeelDefaults() { return tables[0]; } @@ -378,7 +378,7 @@ public class UIManager implements Serializable private static LookAndFeelInfo[] installedLAFs; static { - ArrayList iLAFs = new ArrayList(4); + ArrayList iLAFs = new ArrayList(4); iLAFs.add(new LookAndFeelInfo( "Metal", "javax.swing.plaf.metal.MetalLookAndFeel")); iLAFs.add(new LookAndFeelInfo("CDE/Motif", @@ -400,8 +400,7 @@ public class UIManager implements Serializable iLAFs.add(new LookAndFeelInfo("GTK+", "com.sun.java.swing.plaf.gtk.GTKLookAndFeel")); } - installedLAFs = (LookAndFeelInfo[])iLAFs.toArray( - new LookAndFeelInfo[iLAFs.size()]); + installedLAFs = iLAFs.toArray(new LookAndFeelInfo[iLAFs.size()]); } @@ -640,7 +639,7 @@ public class UIManager implements Serializable * @see #getSystemLookAndFeelClassName */ public static String getCrossPlatformLookAndFeelClassName() { - String laf = (String)AccessController.doPrivileged( + String laf = AccessController.doPrivileged( new GetPropertyAction("swing.crossplatformlaf")); if (laf != null) { return laf; @@ -1079,9 +1078,9 @@ public class UIManager implements Serializable // for that. return; } - Vector v = getLAFState().auxLookAndFeels; + Vector v = getLAFState().auxLookAndFeels; if (v == null) { - v = new Vector(); + v = new Vector(); } if (!v.contains(laf)) { @@ -1115,7 +1114,7 @@ public class UIManager implements Serializable boolean result; - Vector v = getLAFState().auxLookAndFeels; + Vector v = getLAFState().auxLookAndFeels; if ((v == null) || (v.size() == 0)) { return false; } @@ -1151,14 +1150,14 @@ public class UIManager implements Serializable static public LookAndFeel[] getAuxiliaryLookAndFeels() { maybeInitialize(); - Vector v = getLAFState().auxLookAndFeels; + Vector v = getLAFState().auxLookAndFeels; if ((v == null) || (v.size() == 0)) { return null; } else { LookAndFeel[] rv = new LookAndFeel[v.size()]; for (int i = 0; i < rv.length; i++) { - rv[i] = (LookAndFeel)v.elementAt(i); + rv[i] = v.elementAt(i); } return rv; } @@ -1225,7 +1224,7 @@ public class UIManager implements Serializable final Properties props = new Properties(); java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction() { public Object run() { try { File file = new File(makeSwingPropertiesFilename()); @@ -1284,7 +1283,7 @@ public class UIManager implements Serializable * property. For example given "swing.installedlafs=motif,windows" * lafs = {"motif", "windows"}. */ - Vector lafs = new Vector(); + Vector lafs = new Vector(); StringTokenizer st = new StringTokenizer(ilafsString, ",", false); while (st.hasMoreTokens()) { lafs.addElement(st.nextToken()); @@ -1294,9 +1293,8 @@ public class UIManager implements Serializable * list. If they both exist then add a LookAndFeelInfo to * the installedLafs array. */ - Vector ilafs = new Vector(lafs.size()); - for(int i = 0; i < lafs.size(); i++) { - String laf = (String)lafs.elementAt(i); + Vector ilafs = new Vector(lafs.size()); + for (String laf : lafs) { String name = swingProps.getProperty(makeInstalledLAFKey(laf, "name"), laf); String cls = swingProps.getProperty(makeInstalledLAFKey(laf, "class")); if (cls != null) { @@ -1306,7 +1304,7 @@ public class UIManager implements Serializable installedLAFs = new LookAndFeelInfo[ilafs.size()]; for(int i = 0; i < ilafs.size(); i++) { - installedLAFs[i] = (LookAndFeelInfo)(ilafs.elementAt(i)); + installedLAFs[i] = ilafs.elementAt(i); } } @@ -1350,7 +1348,7 @@ public class UIManager implements Serializable return; } - Vector auxLookAndFeels = new Vector(); + Vector auxLookAndFeels = new Vector(); StringTokenizer p = new StringTokenizer(auxLookAndFeelNames,","); String factoryName; @@ -1451,7 +1449,7 @@ public class UIManager implements Serializable Component c = e.getComponent(); if ((!(c instanceof JComponent) || - (c != null && !((JComponent)c).isEnabled())) && + (c != null && !c.isEnabled())) && JComponent.KeyboardState.shouldProcess(e) && SwingUtilities.processKeyBindings(e)) { e.consume(); diff --git a/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java b/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java index 855a357575e..c2ff7bb8df8 100644 --- a/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java +++ b/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java @@ -136,8 +136,8 @@ public abstract class FileSystemView { } File[] roots = getRoots(); - for (int i = 0; i < roots.length; i++) { - if (roots[i].equals(f)) { + for (File root : roots) { + if (root.equals(f)) { return true; } } @@ -252,8 +252,8 @@ public abstract class FileSystemView { return true; } File[] children = getFiles(folder, false); - for (int i = 0; i < children.length; i++) { - if (file.equals(children[i])) { + for (File child : children) { + if (file.equals(child)) { return true; } } @@ -276,9 +276,9 @@ public abstract class FileSystemView { public File getChild(File parent, String fileName) { if (parent instanceof ShellFolder) { File[] children = getFiles(parent, false); - for (int i = 0; i < children.length; i++) { - if (children[i].getName().equals(fileName)) { - return children[i]; + for (File child : children) { + if (child.getName().equals(fileName)) { + return child; } } } @@ -444,7 +444,7 @@ public abstract class FileSystemView { * Gets the list of shown (i.e. not hidden) files. */ public File[] getFiles(File dir, boolean useFileHiding) { - Vector files = new Vector(); + Vector files = new Vector(); // add all files in dir @@ -483,7 +483,7 @@ public abstract class FileSystemView { } } - return (File[])files.toArray(new File[files.size()]); + return files.toArray(new File[files.size()]); } @@ -590,7 +590,7 @@ class UnixFileSystemView extends FileSystemView { if(containingDir == null) { throw new IOException("Containing directory is null:"); } - File newFolder = null; + File newFolder; // Unix - using OpenWindows' default folder name. Can't find one for Motif/CDE. newFolder = createFileObject(containingDir, newFolderString); int i = 1; @@ -614,11 +614,7 @@ class UnixFileSystemView extends FileSystemView { } public boolean isDrive(File dir) { - if (isFloppyDrive(dir)) { - return true; - } else { - return false; - } + return isFloppyDrive(dir); } public boolean isFloppyDrive(File dir) { @@ -700,9 +696,8 @@ class WindowsFileSystemView extends FileSystemView { if(containingDir == null) { throw new IOException("Containing directory is null:"); } - File newFolder = null; // Using NT's default folder name - newFolder = createFileObject(containingDir, newFolderString); + File newFolder = createFileObject(containingDir, newFolderString); int i = 2; while (newFolder.exists() && (i < 100)) { newFolder = createFileObject(containingDir, MessageFormat.format( @@ -770,9 +765,8 @@ class GenericFileSystemView extends FileSystemView { if(containingDir == null) { throw new IOException("Containing directory is null:"); } - File newFolder = null; // Using NT's default folder name - newFolder = createFileObject(containingDir, newFolderString); + File newFolder = createFileObject(containingDir, newFolderString); if(newFolder.exists()) { throw new IOException("Directory already exists:" + newFolder.getAbsolutePath()); diff --git a/jdk/src/share/classes/javax/swing/table/AbstractTableModel.java b/jdk/src/share/classes/javax/swing/table/AbstractTableModel.java index 4a9474cb258..9d6f4cafdcb 100644 --- a/jdk/src/share/classes/javax/swing/table/AbstractTableModel.java +++ b/jdk/src/share/classes/javax/swing/table/AbstractTableModel.java @@ -176,8 +176,7 @@ public abstract class AbstractTableModel implements TableModel, Serializable * @since 1.4 */ public TableModelListener[] getTableModelListeners() { - return (TableModelListener[])listenerList.getListeners( - TableModelListener.class); + return listenerList.getListeners(TableModelListener.class); } // diff --git a/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java b/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java index c2e97a9a2dd..0a63bfa73cd 100644 --- a/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java +++ b/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java @@ -681,9 +681,9 @@ public class DefaultTableModel extends AbstractTableModel implements Serializabl if (anArray == null) { return null; } - Vector v = new Vector(anArray.length); - for (int i=0; i < anArray.length; i++) { - v.addElement(anArray[i]); + Vector v = new Vector(anArray.length); + for (Object o : anArray) { + v.addElement(o); } return v; } @@ -698,9 +698,9 @@ public class DefaultTableModel extends AbstractTableModel implements Serializabl if (anArray == null) { return null; } - Vector v = new Vector(anArray.length); - for (int i=0; i < anArray.length; i++) { - v.addElement(convertToVector(anArray[i])); + Vector v = new Vector(anArray.length); + for (Object[] o : anArray) { + v.addElement(convertToVector(o)); } return v; } diff --git a/jdk/src/share/classes/javax/swing/tree/DefaultTreeCellEditor.java b/jdk/src/share/classes/javax/swing/tree/DefaultTreeCellEditor.java index de8df158f35..b0acd9be7e9 100644 --- a/jdk/src/share/classes/javax/swing/tree/DefaultTreeCellEditor.java +++ b/jdk/src/share/classes/javax/swing/tree/DefaultTreeCellEditor.java @@ -551,7 +551,7 @@ public class DefaultTreeCellEditor implements ActionListener, TreeCellEditor, // Serialization support. private void writeObject(ObjectOutputStream s) throws IOException { - Vector values = new Vector(); + Vector values = new Vector(); s.defaultWriteObject(); // Save the realEditor, if its Serializable. diff --git a/jdk/src/share/classes/javax/swing/tree/DefaultTreeModel.java b/jdk/src/share/classes/javax/swing/tree/DefaultTreeModel.java index a74444677c1..f4e8b14f290 100644 --- a/jdk/src/share/classes/javax/swing/tree/DefaultTreeModel.java +++ b/jdk/src/share/classes/javax/swing/tree/DefaultTreeModel.java @@ -453,8 +453,7 @@ public class DefaultTreeModel implements Serializable, TreeModel { * @since 1.4 */ public TreeModelListener[] getTreeModelListeners() { - return (TreeModelListener[])listenerList.getListeners( - TreeModelListener.class); + return listenerList.getListeners(TreeModelListener.class); } /** @@ -652,7 +651,7 @@ public class DefaultTreeModel implements Serializable, TreeModel { // Serialization support. private void writeObject(ObjectOutputStream s) throws IOException { - Vector values = new Vector(); + Vector values = new Vector(); s.defaultWriteObject(); // Save the root, if its Serializable. diff --git a/jdk/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java b/jdk/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java index 6f84e169f50..2eb24e84616 100644 --- a/jdk/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java +++ b/jdk/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java @@ -61,7 +61,7 @@ import javax.swing.DefaultListSelectionModel; * * @author Scott Violet */ -public class DefaultTreeSelectionModel extends Object implements Cloneable, Serializable, TreeSelectionModel +public class DefaultTreeSelectionModel implements Cloneable, Serializable, TreeSelectionModel { /** Property name for selectionMode. */ public static final String SELECTION_MODE_PROPERTY = "selectionMode"; @@ -98,8 +98,8 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri /** Used to make sure the paths are unique, will contain all the paths * in selection. */ - private Hashtable uniquePaths; - private Hashtable lastPaths; + private Hashtable uniquePaths; + private Hashtable lastPaths; private TreePath[] tempPaths; @@ -111,8 +111,8 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri listSelectionModel = new DefaultListSelectionModel(); selectionMode = DISCONTIGUOUS_TREE_SELECTION; leadIndex = leadRow = -1; - uniquePaths = new Hashtable(); - lastPaths = new Hashtable(); + uniquePaths = new Hashtable(); + lastPaths = new Hashtable(); tempPaths = new TreePath[1]; } @@ -245,7 +245,7 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri } TreePath beginLeadPath = leadPath; - Vector cPaths = new Vector(newCount + oldCount); + Vector cPaths = new Vector(newCount + oldCount); List newSelectionAsList = new ArrayList(newCount); @@ -276,7 +276,7 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri selection = newSelection; - Hashtable tempHT = uniquePaths; + Hashtable tempHT = uniquePaths; uniquePaths = lastPaths; lastPaths = tempHT; @@ -348,7 +348,7 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri int counter, validCount; int oldCount; TreePath beginLeadPath = leadPath; - Vector cPaths = null; + Vector cPaths = null; if(selection == null) oldCount = 0; @@ -363,7 +363,7 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri if (uniquePaths.get(paths[counter]) == null) { validCount++; if(cPaths == null) - cPaths = new Vector(); + cPaths = new Vector(); cPaths.addElement(new PathPlaceHolder (paths[counter], true)); uniquePaths.put(paths[counter], Boolean.TRUE); @@ -388,12 +388,11 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri if(validCount != paths.length) { /* Some of the paths in paths are already in the selection. */ - Enumeration newPaths = lastPaths.keys(); + Enumeration newPaths = lastPaths.keys(); counter = oldCount; while (newPaths.hasMoreElements()) { - newSelection[counter++] = (TreePath)newPaths. - nextElement(); + newSelection[counter++] = newPaths.nextElement(); } } else { @@ -448,7 +447,7 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri clearSelection(); } else { - Vector pathsToRemove = null; + Vector pathsToRemove = null; /* Find the paths that can be removed. */ for (int removeCounter = paths.length - 1; removeCounter >= 0; @@ -456,7 +455,7 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri if(paths[removeCounter] != null) { if (uniquePaths.get(paths[removeCounter]) != null) { if(pathsToRemove == null) - pathsToRemove = new Vector(paths.length); + pathsToRemove = new Vector(paths.length); uniquePaths.remove(paths[removeCounter]); pathsToRemove.addElement(new PathPlaceHolder (paths[removeCounter], false)); @@ -471,14 +470,13 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri selection = null; } else { - Enumeration pEnum = uniquePaths.keys(); + Enumeration pEnum = uniquePaths.keys(); int validCount = 0; selection = new TreePath[selection.length - removeCount]; while (pEnum.hasMoreElements()) { - selection[validCount++] = (TreePath)pEnum. - nextElement(); + selection[validCount++] = pEnum.nextElement(); } } if (leadPath != null && @@ -613,8 +611,7 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri * @since 1.4 */ public TreeSelectionListener[] getTreeSelectionListeners() { - return (TreeSelectionListener[])listenerList.getListeners( - TreeSelectionListener.class); + return listenerList.getListeners(TreeSelectionListener.class); } /** @@ -1081,7 +1078,7 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri PathPlaceHolder placeholder; for(int counter = 0; counter < cPathCount; counter++) { - placeholder = (PathPlaceHolder)changedPaths.elementAt(counter); + placeholder = changedPaths.elementAt(counter); newness[counter] = placeholder.isNew; paths[counter] = placeholder.path; } @@ -1177,8 +1174,8 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri clone.listenerList = new EventListenerList(); clone.listSelectionModel = (DefaultListSelectionModel) listSelectionModel.clone(); - clone.uniquePaths = new Hashtable(); - clone.lastPaths = new Hashtable(); + clone.uniquePaths = new Hashtable(); + clone.lastPaths = new Hashtable(); clone.tempPaths = new TreePath[1]; return clone; } diff --git a/jdk/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java b/jdk/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java index 37f805ae029..57b813bc72c 100644 --- a/jdk/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java +++ b/jdk/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java @@ -64,21 +64,21 @@ public class FixedHeightLayoutCache extends AbstractLayoutCache { /** * Maps from TreePath to a FHTreeStateNode. */ - private Hashtable treePathMapping; + private Hashtable treePathMapping; /** * Used for getting path/row information. */ private SearchInfo info; - private Stack tempStacks; + private Stack> tempStacks; public FixedHeightLayoutCache() { super(); - tempStacks = new Stack(); + tempStacks = new Stack>(); boundsBuffer = new Rectangle(); - treePathMapping = new Hashtable(); + treePathMapping = new Hashtable(); info = new SearchInfo(); setRowHeight(1); } @@ -592,7 +592,7 @@ public class FixedHeightLayoutCache extends AbstractLayoutCache { * return null, if you to create a node use getNodeForPath. */ private FHTreeStateNode getMapping(TreePath path) { - return (FHTreeStateNode)treePathMapping.get(path); + return treePathMapping.get(path); } /** @@ -695,13 +695,13 @@ public class FixedHeightLayoutCache extends AbstractLayoutCache { return null; // Check all the parent paths, until a match is found. - Stack paths; + Stack paths; if(tempStacks.size() == 0) { - paths = new Stack(); + paths = new Stack(); } else { - paths = (Stack)tempStacks.pop(); + paths = tempStacks.pop(); } try { @@ -714,7 +714,7 @@ public class FixedHeightLayoutCache extends AbstractLayoutCache { // Found a match, create entries for all paths in // paths. while(node != null && paths.size() > 0) { - path = (TreePath)paths.pop(); + path = paths.pop(); node = node.createChildFor(path. getLastPathComponent()); } diff --git a/jdk/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java b/jdk/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java index 5861dd95b1c..cdf0a1a7355 100644 --- a/jdk/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java +++ b/jdk/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java @@ -56,7 +56,7 @@ public class VariableHeightLayoutCache extends AbstractLayoutCache { * The array of nodes that are currently visible, in the order they * are displayed. */ - private Vector visibleNodes; + private Vector visibleNodes; /** * This is set to true if one of the entries has an invalid size. @@ -79,20 +79,20 @@ public class VariableHeightLayoutCache extends AbstractLayoutCache { /** * Maps from TreePath to a TreeStateNode. */ - private Hashtable treePathMapping; + private Hashtable treePathMapping; /** * A stack of stacks. */ - private Stack tempStacks; + private Stack> tempStacks; public VariableHeightLayoutCache() { super(); - tempStacks = new Stack(); - visibleNodes = new Vector(); + tempStacks = new Stack>(); + visibleNodes = new Vector(); boundsBuffer = new Rectangle(); - treePathMapping = new Hashtable(); + treePathMapping = new Hashtable(); } /** @@ -704,7 +704,7 @@ public class VariableHeightLayoutCache extends AbstractLayoutCache { * return null, if you to create a node use getNodeForPath. */ private TreeStateNode getMapping(TreePath path) { - return (TreeStateNode)treePathMapping.get(path); + return treePathMapping.get(path); } /** @@ -824,13 +824,13 @@ public class VariableHeightLayoutCache extends AbstractLayoutCache { } // Check all the parent paths, until a match is found. - Stack paths; + Stack paths; if(tempStacks.size() == 0) { - paths = new Stack(); + paths = new Stack(); } else { - paths = (Stack)tempStacks.pop(); + paths = tempStacks.pop(); } try { @@ -843,7 +843,7 @@ public class VariableHeightLayoutCache extends AbstractLayoutCache { // Found a match, create entries for all paths in // paths. while(node != null && paths.size() > 0) { - path = (TreePath)paths.pop(); + path = paths.pop(); node.getLoadedChildren(shouldCreate); int childIndex = treeModel. diff --git a/jdk/src/share/classes/javax/swing/undo/StateEdit.java b/jdk/src/share/classes/javax/swing/undo/StateEdit.java index 675afb39717..554ed053736 100644 --- a/jdk/src/share/classes/javax/swing/undo/StateEdit.java +++ b/jdk/src/share/classes/javax/swing/undo/StateEdit.java @@ -116,7 +116,7 @@ public class StateEdit protected void init (StateEditable anObject, String name) { this.object = anObject; - this.preState = new Hashtable(11); + this.preState = new Hashtable(11); this.object.storeState(this.preState); this.postState = null; this.undoRedoName = name; @@ -133,7 +133,7 @@ public class StateEdit * ends the edit. */ public void end() { - this.postState = new Hashtable(11); + this.postState = new Hashtable(11); this.object.storeState(this.postState); this.removeRedundantState(); } @@ -170,7 +170,7 @@ public class StateEdit * Remove redundant key/values in state hashtables. */ protected void removeRedundantState() { - Vector uselessKeys = new Vector(); + Vector uselessKeys = new Vector(); Enumeration myKeys = preState.keys(); // Locate redundant state diff --git a/jdk/src/share/classes/javax/swing/undo/UndoManager.java b/jdk/src/share/classes/javax/swing/undo/UndoManager.java index 88c300c942a..fb1dcaf8ee3 100644 --- a/jdk/src/share/classes/javax/swing/undo/UndoManager.java +++ b/jdk/src/share/classes/javax/swing/undo/UndoManager.java @@ -166,12 +166,10 @@ public class UndoManager extends CompoundEdit implements UndoableEditListener { * @see AbstractUndoableEdit#die */ public synchronized void discardAllEdits() { - Enumeration cursor = edits.elements(); - while (cursor.hasMoreElements()) { - UndoableEdit e = (UndoableEdit)cursor.nextElement(); + for (UndoableEdit e : edits) { e.die(); } - edits = new Vector(); + edits = new Vector(); indexOfNextAdd = 0; // PENDING(rjrjr) when vector grows a removeRange() method // (expected in JDK 1.2), trimEdits() will be nice and @@ -240,7 +238,7 @@ public class UndoManager extends CompoundEdit implements UndoableEditListener { // System.out.println("Trimming " + from + " " + to + " with index " + // indexOfNextAdd); for (int i = to; from <= i; i--) { - UndoableEdit e = (UndoableEdit)edits.elementAt(i); + UndoableEdit e = edits.elementAt(i); // System.out.println("JUM: Discarding " + // e.getUndoPresentationName()); e.die(); @@ -293,7 +291,7 @@ public class UndoManager extends CompoundEdit implements UndoableEditListener { protected UndoableEdit editToBeUndone() { int i = indexOfNextAdd; while (i > 0) { - UndoableEdit edit = (UndoableEdit)edits.elementAt(--i); + UndoableEdit edit = edits.elementAt(--i); if (edit.isSignificant()) { return edit; } @@ -314,7 +312,7 @@ public class UndoManager extends CompoundEdit implements UndoableEditListener { int i = indexOfNextAdd; while (i < count) { - UndoableEdit edit = (UndoableEdit)edits.elementAt(i++); + UndoableEdit edit = edits.elementAt(i++); if (edit.isSignificant()) { return edit; } @@ -333,7 +331,7 @@ public class UndoManager extends CompoundEdit implements UndoableEditListener { protected void undoTo(UndoableEdit edit) throws CannotUndoException { boolean done = false; while (!done) { - UndoableEdit next = (UndoableEdit)edits.elementAt(--indexOfNextAdd); + UndoableEdit next = edits.elementAt(--indexOfNextAdd); next.undo(); done = next == edit; } @@ -349,7 +347,7 @@ public class UndoManager extends CompoundEdit implements UndoableEditListener { protected void redoTo(UndoableEdit edit) throws CannotRedoException { boolean done = false; while (!done) { - UndoableEdit next = (UndoableEdit)edits.elementAt(indexOfNextAdd++); + UndoableEdit next = edits.elementAt(indexOfNextAdd++); next.redo(); done = next == edit; } diff --git a/jdk/src/share/classes/javax/swing/undo/UndoableEditSupport.java b/jdk/src/share/classes/javax/swing/undo/UndoableEditSupport.java index 0d1d7b9f04d..7b791bf677b 100644 --- a/jdk/src/share/classes/javax/swing/undo/UndoableEditSupport.java +++ b/jdk/src/share/classes/javax/swing/undo/UndoableEditSupport.java @@ -89,8 +89,7 @@ public class UndoableEditSupport { * @since 1.4 */ public synchronized UndoableEditListener[] getUndoableEditListeners() { - return (UndoableEditListener[])(listeners.toArray( - new UndoableEditListener[0])); + return listeners.toArray(new UndoableEditListener[0]); } /** diff --git a/jdk/src/share/classes/sun/swing/AccessibleMethod.java b/jdk/src/share/classes/sun/swing/AccessibleMethod.java index 420ca321feb..97b02ea7a71 100644 --- a/jdk/src/share/classes/sun/swing/AccessibleMethod.java +++ b/jdk/src/share/classes/sun/swing/AccessibleMethod.java @@ -114,7 +114,7 @@ public class AccessibleMethod { /** The action used to fetch the method and make it accessible */ private static class AccessMethodAction implements PrivilegedExceptionAction { - private final Class klass; + private final Class klass; private final String methodName; private final Class[] paramTypes; diff --git a/jdk/src/share/classes/sun/swing/FilePane.java b/jdk/src/share/classes/sun/swing/FilePane.java index 7c862cb78fa..fd5a430864c 100644 --- a/jdk/src/share/classes/sun/swing/FilePane.java +++ b/jdk/src/share/classes/sun/swing/FilePane.java @@ -546,8 +546,7 @@ public class FilePane extends JPanel implements PropertyChangeListener { public static void addActionsToMap(ActionMap map, Action[] actions) { if (map != null && actions != null) { - for (int i = 0; i < actions.length; i++) { - Action a = actions[i]; + for (Action a : actions) { String cmd = (String)a.getValue(Action.ACTION_COMMAND_KEY); if (cmd == null) { cmd = (String)a.getValue(Action.NAME); @@ -715,13 +714,13 @@ public class FilePane extends JPanel implements PropertyChangeListener { visibleColumns.toArray(columns); columnMap = Arrays.copyOf(columnMap, columns.length); - List sortKeys = + List sortKeys = (rowSorter == null) ? null : rowSorter.getSortKeys(); fireTableStructureChanged(); restoreSortKeys(sortKeys); } - private void restoreSortKeys(List sortKeys) { + private void restoreSortKeys(List sortKeys) { if (sortKeys != null) { // check if preserved sortKeys are valid for this folder for (int i = 0; i < sortKeys.size(); i++) { @@ -886,7 +885,7 @@ public class FilePane extends JPanel implements PropertyChangeListener { return rowSorter; } - private class DetailsTableRowSorter extends TableRowSorter { + private class DetailsTableRowSorter extends TableRowSorter { public DetailsTableRowSorter() { setModelWrapper(new SorterModelWrapper()); } @@ -906,8 +905,8 @@ public class FilePane extends JPanel implements PropertyChangeListener { updateComparators(detailsTableModel.getColumns()); } - private class SorterModelWrapper extends ModelWrapper { - public Object getModel() { + private class SorterModelWrapper extends ModelWrapper { + public TableModel getModel() { return getDetailsTableModel(); } @@ -923,7 +922,7 @@ public class FilePane extends JPanel implements PropertyChangeListener { return FilePane.this.getModel().getElementAt(row); } - public Object getIdentifier(int row) { + public Integer getIdentifier(int row) { return row; } } @@ -1718,9 +1717,9 @@ public class FilePane extends JPanel implements PropertyChangeListener { private void updateViewMenu() { if (viewMenu != null) { Component[] comps = viewMenu.getMenuComponents(); - for (int i = 0; i < comps.length; i++) { - if (comps[i] instanceof JRadioButtonMenuItem) { - JRadioButtonMenuItem mi = (JRadioButtonMenuItem)comps[i]; + for (Component comp : comps) { + if (comp instanceof JRadioButtonMenuItem) { + JRadioButtonMenuItem mi = (JRadioButtonMenuItem) comp; if (((ViewTypeAction)mi.getAction()).viewType == viewType) { mi.setSelected(true); } diff --git a/jdk/src/share/classes/sun/swing/SwingLazyValue.java b/jdk/src/share/classes/sun/swing/SwingLazyValue.java index 6aabcf66e2a..f3b6b9e884f 100644 --- a/jdk/src/share/classes/sun/swing/SwingLazyValue.java +++ b/jdk/src/share/classes/sun/swing/SwingLazyValue.java @@ -54,15 +54,14 @@ public class SwingLazyValue implements UIDefaults.LazyValue { className = c; methodName = m; if (o != null) { - args = (Object[])o.clone(); + args = o.clone(); } } public Object createValue(final UIDefaults table) { try { - Class c; Object cl; - c = Class.forName(className, true, null); + Class c = Class.forName(className, true, null); if (methodName != null) { Class[] types = getClassArray(args); Method m = c.getMethod(methodName, types); diff --git a/jdk/src/share/classes/sun/swing/SwingUtilities2.java b/jdk/src/share/classes/sun/swing/SwingUtilities2.java index f0165be3ea9..0603e55b5d3 100644 --- a/jdk/src/share/classes/sun/swing/SwingUtilities2.java +++ b/jdk/src/share/classes/sun/swing/SwingUtilities2.java @@ -460,7 +460,7 @@ public class SwingUtilities2 { return clipString; } - boolean needsTextLayout = false; + boolean needsTextLayout; synchronized (charsBufferLock) { if (charsBuffer == null || charsBuffer.length < stringLength) { @@ -715,11 +715,8 @@ public class SwingUtilities2 { // See if coords are inside // ASSUME: mouse x,y will never be < cell's x,y assert (p.x >= cellBounds.x && p.y >= cellBounds.y); - if (p.x > cellBounds.x + cellBounds.width || - p.y > cellBounds.y + cellBounds.height) { - return true; - } - return false; + return p.x > cellBounds.x + cellBounds.width || + p.y > cellBounds.y + cellBounds.height; } /** @@ -1239,12 +1236,11 @@ public class SwingUtilities2 { private static synchronized boolean inputEvent_canAccessSystemClipboard(InputEvent ie) { if (inputEvent_CanAccessSystemClipboard_Field == null) { inputEvent_CanAccessSystemClipboard_Field = - (Field)AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - Field field = null; + AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Field run() { try { - field = InputEvent.class. + Field field = InputEvent.class. getDeclaredField("canAccessSystemClipboard"); field.setAccessible(true); return field; @@ -1419,10 +1415,10 @@ public class SwingUtilities2 { * Class.getResourceAsStream just returns raw * bytes, which we can convert to an image. */ - byte[] buffer = (byte[]) + byte[] buffer = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + new java.security.PrivilegedAction() { + public byte[] run() { try { InputStream resource = null; Class srchClass = baseClass; @@ -1489,7 +1485,7 @@ public class SwingUtilities2 { return true; } // Else probably Solaris or Linux in which case may be remote X11 - Class x11Class = Class.forName("sun.awt.X11GraphicsEnvironment"); + Class x11Class = Class.forName("sun.awt.X11GraphicsEnvironment"); Method isDisplayLocalMethod = x11Class.getMethod( "isDisplayLocal", new Class[0]); return (Boolean)isDisplayLocalMethod.invoke(null, (Object[])null); From 168e2b0ff2b28ccf5796ff9c8938fd91d7688216 Mon Sep 17 00:00:00 2001 From: Pavel Porvatov Date: Wed, 27 Aug 2008 20:49:35 +0400 Subject: [PATCH 30/45] 6351074: JFileChooser removes leading space in filename Removed trimming of leading spaces in filename Reviewed-by: alexp --- .../swing/plaf/basic/BasicFileChooserUI.java | 190 +++++++++--------- 1 file changed, 95 insertions(+), 95 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java index 4016435c793..13d13cdcefe 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java @@ -36,6 +36,7 @@ import java.awt.datatransfer.*; import java.beans.*; import java.io.*; import java.util.*; +import java.util.List; import java.util.regex.*; import sun.awt.shell.ShellFolder; import sun.swing.*; @@ -829,11 +830,17 @@ public class BasicFileChooserUI extends FileChooserUI { File dir = chooser.getCurrentDirectory(); if (filename != null) { - // Remove whitespace from beginning and end of filename - filename = filename.trim(); + // Remove whitespaces from end of filename + int i = filename.length() - 1; + + while (i >=0 && filename.charAt(i) <= ' ') { + i--; + } + + filename = filename.substring(0, i + 1); } - if (filename == null || filename.equals("")) { + if (filename == null || filename.length() == 0) { // no file selected, multiple selection off, therefore cancel the approve action resetGlobFilter(); return; @@ -842,100 +849,93 @@ public class BasicFileChooserUI extends FileChooserUI { File selectedFile = null; File[] selectedFiles = null; - if (filename != null && !filename.equals("")) { - // Unix: Resolve '~' to user's home directory - if (File.separatorChar == '/') { - if (filename.startsWith("~/")) { - filename = System.getProperty("user.home") + filename.substring(1); - } else if (filename.equals("~")) { - filename = System.getProperty("user.home"); - } - } - - if (chooser.isMultiSelectionEnabled() && filename.startsWith("\"")) { - ArrayList fList = new ArrayList(); - - filename = filename.substring(1); - if (filename.endsWith("\"")) { - filename = filename.substring(0, filename.length()-1); - } - File[] children = null; - int childIndex = 0; - do { - String str; - int i = filename.indexOf("\" \""); - if (i > 0) { - str = filename.substring(0, i); - filename = filename.substring(i+3); - } else { - str = filename; - filename = ""; - } - File file = fs.createFileObject(str); - if (!file.isAbsolute()) { - if (children == null) { - children = fs.getFiles(dir, false); - Arrays.sort(children); - } - for (int k = 0; k < children.length; k++) { - int l = (childIndex + k) % children.length; - if (children[l].getName().equals(str)) { - file = children[l]; - childIndex = l + 1; - break; - } - } - } - fList.add(file); - } while (filename.length() > 0); - if (fList.size() > 0) { - selectedFiles = fList.toArray(new File[fList.size()]); - } - resetGlobFilter(); - } else { - selectedFile = fs.createFileObject(filename); - if(!selectedFile.isAbsolute()) { - selectedFile = fs.getChild(dir, filename); - } - // check for wildcard pattern - FileFilter currentFilter = chooser.getFileFilter(); - if (!selectedFile.exists() && isGlobPattern(filename)) { - changeDirectory(selectedFile.getParentFile()); - if (globFilter == null) { - globFilter = new GlobFilter(); - } - try { - globFilter.setPattern(selectedFile.getName()); - if (!(currentFilter instanceof GlobFilter)) { - actualFileFilter = currentFilter; - } - chooser.setFileFilter(null); - chooser.setFileFilter(globFilter); - return; - } catch (PatternSyntaxException pse) { - // Not a valid glob pattern. Abandon filter. - } - } - - resetGlobFilter(); - - // Check for directory change action - boolean isDir = (selectedFile != null && selectedFile.isDirectory()); - boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); - boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); - boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); - boolean isCtrl = (e != null && (e.getModifiers() & ActionEvent.CTRL_MASK) != 0); - - if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { - changeDirectory(selectedFile); - return; - } else if ((isDir || !isFileSelEnabled) - && (!isDir || !isDirSelEnabled) - && (!isDirSelEnabled || selectedFile.exists())) { - selectedFile = null; - } + // Unix: Resolve '~' to user's home directory + if (File.separatorChar == '/') { + if (filename.startsWith("~/")) { + filename = System.getProperty("user.home") + filename.substring(1); + } else if (filename.equals("~")) { + filename = System.getProperty("user.home"); } } + + if (chooser.isMultiSelectionEnabled() && filename.length() > 1 && + filename.charAt(0) == '"' && filename.charAt(filename.length() - 1) == '"') { + List fList = new ArrayList(); + + String[] files = filename.substring(1, filename.length() - 1).split("\" \""); + // Optimize searching files by names in "children" array + Arrays.sort(files); + + File[] children = null; + int childIndex = 0; + + for (String str : files) { + File file = fs.createFileObject(str); + if (!file.isAbsolute()) { + if (children == null) { + children = fs.getFiles(dir, false); + Arrays.sort(children); + } + for (int k = 0; k < children.length; k++) { + int l = (childIndex + k) % children.length; + if (children[l].getName().equals(str)) { + file = children[l]; + childIndex = l + 1; + break; + } + } + } + fList.add(file); + } + + if (!fList.isEmpty()) { + selectedFiles = fList.toArray(new File[fList.size()]); + } + resetGlobFilter(); + } else { + selectedFile = fs.createFileObject(filename); + if (!selectedFile.isAbsolute()) { + selectedFile = fs.getChild(dir, filename); + } + // check for wildcard pattern + FileFilter currentFilter = chooser.getFileFilter(); + if (!selectedFile.exists() && isGlobPattern(filename)) { + changeDirectory(selectedFile.getParentFile()); + if (globFilter == null) { + globFilter = new GlobFilter(); + } + try { + globFilter.setPattern(selectedFile.getName()); + if (!(currentFilter instanceof GlobFilter)) { + actualFileFilter = currentFilter; + } + chooser.setFileFilter(null); + chooser.setFileFilter(globFilter); + return; + } catch (PatternSyntaxException pse) { + // Not a valid glob pattern. Abandon filter. + } + } + + resetGlobFilter(); + + // Check for directory change action + boolean isDir = (selectedFile != null && selectedFile.isDirectory()); + boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); + boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); + boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); + boolean isCtrl = (e != null && (e.getModifiers() & ActionEvent.CTRL_MASK) != 0); + + if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { + changeDirectory(selectedFile); + return; + } else if ((isDir || !isFileSelEnabled) + && (!isDir || !isDirSelEnabled) + && (!isDirSelEnabled || selectedFile.exists())) { + selectedFile = null; + } + } + if (selectedFiles != null || selectedFile != null) { if (selectedFiles != null || chooser.isMultiSelectionEnabled()) { if (selectedFiles == null) { From b4ad1bd707c616c3b5d7c02969018d349f2cd867 Mon Sep 17 00:00:00 2001 From: Pavel Porvatov Date: Fri, 29 Aug 2008 13:23:55 +0400 Subject: [PATCH 31/45] 6742490: JSlider tests are located in JFileChooser directory Tests were moved to appropriate folder Reviewed-by: peterz --- .../javax/swing/{JFileChooser => JSlider}/4252173/bug4252173.java | 0 .../javax/swing/{JFileChooser => JSlider}/6524424/bug6524424.html | 0 .../javax/swing/{JFileChooser => JSlider}/6524424/bug6524424.java | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename jdk/test/javax/swing/{JFileChooser => JSlider}/4252173/bug4252173.java (100%) rename jdk/test/javax/swing/{JFileChooser => JSlider}/6524424/bug6524424.html (100%) rename jdk/test/javax/swing/{JFileChooser => JSlider}/6524424/bug6524424.java (100%) diff --git a/jdk/test/javax/swing/JFileChooser/4252173/bug4252173.java b/jdk/test/javax/swing/JSlider/4252173/bug4252173.java similarity index 100% rename from jdk/test/javax/swing/JFileChooser/4252173/bug4252173.java rename to jdk/test/javax/swing/JSlider/4252173/bug4252173.java diff --git a/jdk/test/javax/swing/JFileChooser/6524424/bug6524424.html b/jdk/test/javax/swing/JSlider/6524424/bug6524424.html similarity index 100% rename from jdk/test/javax/swing/JFileChooser/6524424/bug6524424.html rename to jdk/test/javax/swing/JSlider/6524424/bug6524424.html diff --git a/jdk/test/javax/swing/JFileChooser/6524424/bug6524424.java b/jdk/test/javax/swing/JSlider/6524424/bug6524424.java similarity index 100% rename from jdk/test/javax/swing/JFileChooser/6524424/bug6524424.java rename to jdk/test/javax/swing/JSlider/6524424/bug6524424.java From 7861fdb86270ad5eb1c714c72731417ba45953a2 Mon Sep 17 00:00:00 2001 From: Pavel Porvatov Date: Fri, 29 Aug 2008 18:58:17 +0400 Subject: [PATCH 32/45] 6742358: MetalSliderUI paint wrong vertical disabled filled JSlider for DefaultMetalTheme Corrected the method MetalSliderUI.paintTrack Reviewed-by: malenkov --- .../javax/swing/plaf/metal/MetalSliderUI.java | 3 +- .../swing/JSlider/6742358/bug6742358.html | 6 ++ .../swing/JSlider/6742358/bug6742358.java | 92 +++++++++++++++++++ 3 files changed, 99 insertions(+), 2 deletions(-) create mode 100644 jdk/test/javax/swing/JSlider/6742358/bug6742358.html create mode 100644 jdk/test/javax/swing/JSlider/6742358/bug6742358.java diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java index 13563b80ecc..ce9462737eb 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java @@ -314,8 +314,7 @@ public class MetalSliderUI extends BasicSliderUI { } else { g.setColor( MetalLookAndFeel.getControlShadow() ); - g.fillRect( fillLeft, fillTop, - fillRight - fillLeft, trackBottom - trackTop ); + g.fillRect(fillLeft, fillTop, fillRight - fillLeft, fillBottom - fillTop); } } diff --git a/jdk/test/javax/swing/JSlider/6742358/bug6742358.html b/jdk/test/javax/swing/JSlider/6742358/bug6742358.html new file mode 100644 index 00000000000..d004e116c93 --- /dev/null +++ b/jdk/test/javax/swing/JSlider/6742358/bug6742358.html @@ -0,0 +1,6 @@ + + + +Check that all sliders look good. + + diff --git a/jdk/test/javax/swing/JSlider/6742358/bug6742358.java b/jdk/test/javax/swing/JSlider/6742358/bug6742358.java new file mode 100644 index 00000000000..a50f50cd791 --- /dev/null +++ b/jdk/test/javax/swing/JSlider/6742358/bug6742358.java @@ -0,0 +1,92 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6742358 + * @summary MetalSliderUI paint wrong vertical disabled filled JSlider for DefaultMetalTheme + * @author Pavel Porvatov + * @run applet/manual=done bug6742358.html + */ + +import javax.swing.*; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalLookAndFeel; + +public class bug6742358 extends JApplet { + public static void main(String[] args) { + MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme()); + + JFrame frame = new JFrame(); + + frame.setContentPane(new TestPanel()); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.pack(); + frame.setLocationRelativeTo(null); + + frame.setVisible(true); + } + + public void init() { + MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme()); + + TestPanel panel = new TestPanel(); + + setContentPane(panel); + } + + private static class TestPanel extends JPanel { + + private TestPanel() { + JPanel pnVertical = new JPanel(); + + pnVertical.setLayout(new BoxLayout(pnVertical, BoxLayout.Y_AXIS)); + + for (int i = 0; i < 8; i++) { + pnVertical.add(createSlider(false, (i & 4) == 0, (i & 2) == 0, (i & 1) == 0)); + } + + JPanel pnHorizontal = new JPanel(); + + pnHorizontal.setLayout(new BoxLayout(pnHorizontal, BoxLayout.X_AXIS)); + + for (int i = 0; i < 8; i++) { + pnHorizontal.add(createSlider(true, (i & 4) == 0, (i & 2) == 0, (i & 1) == 0)); + } + + add(pnHorizontal); + add(pnVertical); + } + } + + private static JSlider createSlider(boolean vertical, boolean enabled, boolean filled, boolean inverted) { + JSlider result = new JSlider(vertical ? SwingConstants.VERTICAL : SwingConstants.HORIZONTAL, 0, 10, 5); + + result.setEnabled(enabled); + result.putClientProperty("JSlider.isFilled", filled); + result.setInverted(inverted); + result.setToolTipText("vertical = " + vertical + "
enabled = " + enabled + "
filled = " + filled + + "
inverted = " + inverted + ""); + + return result; + } +} From 5f00e2cd20049cdb8ec65e48e52c72bcb98dbf4f Mon Sep 17 00:00:00 2001 From: Pavel Porvatov Date: Sat, 30 Aug 2008 17:29:59 +0400 Subject: [PATCH 33/45] 6554743: JFileChooser dn't close after pressing escape key after changing the views Restore focus after changing the views in JFileChooser Reviewed-by: loneid --- jdk/src/share/classes/sun/swing/FilePane.java | 110 +++++++++--------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/jdk/src/share/classes/sun/swing/FilePane.java b/jdk/src/share/classes/sun/swing/FilePane.java index fd5a430864c..298fd42b146 100644 --- a/jdk/src/share/classes/sun/swing/FilePane.java +++ b/jdk/src/share/classes/sun/swing/FilePane.java @@ -308,44 +308,80 @@ public class FilePane extends JPanel implements PropertyChangeListener { } public void setViewType(int viewType) { - int oldValue = this.viewType; - if (viewType == oldValue) { + if (viewType == this.viewType) { return; } + + int oldValue = this.viewType; this.viewType = viewType; + JPanel createdViewPanel = null; + Component newFocusOwner = null; + switch (viewType) { case VIEWTYPE_LIST: if (viewPanels[viewType] == null) { - JPanel p = fileChooserUIAccessor.createList(); - if (p == null) { - p = createList(); + createdViewPanel = fileChooserUIAccessor.createList(); + if (createdViewPanel == null) { + createdViewPanel = createList(); + } + + list = (JList) findChildComponent(createdViewPanel, JList.class); + if (listSelectionModel == null) { + listSelectionModel = list.getSelectionModel(); + if (detailsTable != null) { + detailsTable.setSelectionModel(listSelectionModel); + } + } else { + list.setSelectionModel(listSelectionModel); } - setViewPanel(viewType, p); } list.setLayoutOrientation(JList.VERTICAL_WRAP); + newFocusOwner = list; break; case VIEWTYPE_DETAILS: if (viewPanels[viewType] == null) { - JPanel p = fileChooserUIAccessor.createDetailsView(); - if (p == null) { - p = createDetailsView(); + createdViewPanel = fileChooserUIAccessor.createDetailsView(); + if (createdViewPanel == null) { + createdViewPanel = createDetailsView(); + } + + detailsTable = (JTable) findChildComponent(createdViewPanel, JTable.class); + detailsTable.setRowHeight(Math.max(detailsTable.getFont().getSize() + 4, 16 + 1)); + if (listSelectionModel != null) { + detailsTable.setSelectionModel(listSelectionModel); } - setViewPanel(viewType, p); } + newFocusOwner = detailsTable; break; } - JPanel oldViewPanel = currentViewPanel; - currentViewPanel = viewPanels[viewType]; - if (currentViewPanel != oldViewPanel) { - if (oldViewPanel != null) { - remove(oldViewPanel); - } - add(currentViewPanel, BorderLayout.CENTER); - revalidate(); - repaint(); + + if (createdViewPanel != null) { + viewPanels[viewType] = createdViewPanel; + recursivelySetInheritsPopupMenu(createdViewPanel, true); } + + boolean isFocusOwner = false; + + if (currentViewPanel != null) { + Component owner = DefaultKeyboardFocusManager. + getCurrentKeyboardFocusManager().getPermanentFocusOwner(); + + isFocusOwner = owner == detailsTable || owner == list; + + remove(currentViewPanel); + } + + currentViewPanel = viewPanels[viewType]; + add(currentViewPanel, BorderLayout.CENTER); + + if (isFocusOwner && newFocusOwner != null) { + newFocusOwner.requestFocusInWindow(); + } + + revalidate(); + repaint(); updateViewMenu(); firePropertyChange("viewType", oldValue, viewType); } @@ -385,42 +421,6 @@ public class FilePane extends JPanel implements PropertyChangeListener { } } - public void setViewPanel(int viewType, JPanel viewPanel) { - viewPanels[viewType] = viewPanel; - recursivelySetInheritsPopupMenu(viewPanel, true); - - switch (viewType) { - case VIEWTYPE_LIST: - list = (JList)findChildComponent(viewPanels[viewType], JList.class); - if (listSelectionModel == null) { - listSelectionModel = list.getSelectionModel(); - if (detailsTable != null) { - detailsTable.setSelectionModel(listSelectionModel); - } - } else { - list.setSelectionModel(listSelectionModel); - } - break; - - case VIEWTYPE_DETAILS: - detailsTable = (JTable)findChildComponent(viewPanels[viewType], JTable.class); - detailsTable.setRowHeight(Math.max(detailsTable.getFont().getSize() + 4, 16+1)); - if (listSelectionModel != null) { - detailsTable.setSelectionModel(listSelectionModel); - } - break; - } - if (this.viewType == viewType) { - if (currentViewPanel != null) { - remove(currentViewPanel); - } - currentViewPanel = viewPanel; - add(currentViewPanel, BorderLayout.CENTER); - revalidate(); - repaint(); - } - } - protected void installDefaults() { Locale l = getFileChooser().getLocale(); From 803014e138d94c2d6ba4063953741bd3562fd484 Mon Sep 17 00:00:00 2001 From: Peter Zhelezniakov Date: Mon, 1 Sep 2008 15:21:46 +0400 Subject: [PATCH 34/45] 5062055: JEditorPane HTML: HR-tag with attribute size=1px causes NumberFormatException Wrapped parseInt() with try/catch Reviewed-by: gsm --- .../javax/swing/text/html/HRuleView.java | 11 ++-- .../text/html/HRuleView/Test5062055.java | 53 +++++++++++++++++++ 2 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 jdk/test/javax/swing/text/html/HRuleView/Test5062055.java diff --git a/jdk/src/share/classes/javax/swing/text/html/HRuleView.java b/jdk/src/share/classes/javax/swing/text/html/HRuleView.java index d345b348dd6..26303a59602 100644 --- a/jdk/src/share/classes/javax/swing/text/html/HRuleView.java +++ b/jdk/src/share/classes/javax/swing/text/html/HRuleView.java @@ -67,13 +67,18 @@ class HRuleView extends View { // use ALIGN_CENTER by default, so we check if the alignment // attribute is actually defined if (attr.getAttribute(StyleConstants.Alignment) != null) { - alignment = StyleConstants.getAlignment(attr); + alignment = StyleConstants.getAlignment(attr); } noshade = (String)eAttr.getAttribute(HTML.Attribute.NOSHADE); Object value = eAttr.getAttribute(HTML.Attribute.SIZE); - if (value != null && (value instanceof String)) - size = Integer.parseInt((String)value); + if (value != null && (value instanceof String)) { + try { + size = Integer.parseInt((String)value); + } catch (NumberFormatException e) { + size = 1; + } + } value = attr.getAttribute(CSS.Attribute.WIDTH); if (value != null && (value instanceof CSS.LengthValue)) { widthValue = (CSS.LengthValue)value; diff --git a/jdk/test/javax/swing/text/html/HRuleView/Test5062055.java b/jdk/test/javax/swing/text/html/HRuleView/Test5062055.java new file mode 100644 index 00000000000..4fe2dbbcc9b --- /dev/null +++ b/jdk/test/javax/swing/text/html/HRuleView/Test5062055.java @@ -0,0 +1,53 @@ +/* + * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + @bug 5062055 + @summary Tests parsing of incorrect HR attributes + @author Peter Zhelezniakov + @run main Test5062055 +*/ + +import java.awt.Dimension; +import javax.swing.*; + +public class Test5062055 implements Runnable +{ + public static void main(String argv[]) { + SwingUtilities.invokeLater(new Test5062055()); + // give HTML time to be parsed + try { + Thread.sleep(5000); + } catch (InterruptedException ex) { + throw new Error("Wait interrupted"); + } + } + + public void run() { + JEditorPane jep = new JEditorPane(); + jep.setContentType("text/html"); + jep.setEditable(false); + jep.setText("
"); + jep.setPreferredSize(new Dimension(640,480)); + } +} From fe4ebb456ffb2f6aa2032de83282f4ae0e66a50f Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Mon, 1 Sep 2008 17:36:57 +0400 Subject: [PATCH 35/45] 5026703: RFE: DOC: Are PropertyChangeSupport & VetoableChangeSupport Thread-Safe? --Docs Should Say Reviewed-by: peterz, rupashka --- .../java/beans/PropertyChangeSupport.java | 41 ++++++++++++++++++- .../java/beans/VetoableChangeSupport.java | 41 ++++++++++++++++++- 2 files changed, 78 insertions(+), 4 deletions(-) diff --git a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java index 2a3f79ff3f2..04b510ae2ca 100644 --- a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java +++ b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java @@ -34,12 +34,49 @@ import java.util.Map.Entry; /** * This is a utility class that can be used by beans that support bound - * properties. You can use an instance of this class as a member field - * of your bean and delegate various work to it. + * properties. It manages a list of listeners and dispatches + * {@link PropertyChangeEvent}s to them. You can use an instance of this class + * as a member field of your bean and delegate these types of work to it. + * The {@link PropertyChangeListener} can be registered for all properties + * or for a property specified by name. + *

+ * Here is an example of {@code PropertyChangeSupport} usage that follows + * the rules and recommendations laid out in the JavaBeans™ specification: + *

+ * public class MyBean {
+ *     private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
  *
+ *     public void addPropertyChangeListener(PropertyChangeListener listener) {
+ *         this.pcs.addPropertyChangeListener(listener);
+ *     }
+ *
+ *     public void removePropertyChangeListener(PropertyChangeListener listener) {
+ *         this.pcs.removePropertyChangeListener(listener);
+ *     }
+ *
+ *     private String value;
+ *
+ *     public String getValue() {
+ *         return this.value;
+ *     }
+ *
+ *     public void setValue(String newValue) {
+ *         String oldValue = this.value;
+ *         this.value = newValue;
+ *         this.pcs.firePropertyChange("value", oldValue, newValue);
+ *     }
+ *
+ *     [...]
+ * }
+ * 
+ *

+ * A {@code PropertyChangeSupport} instance is thread-safe. + *

* This class is serializable. When it is serialized it will save * (and restore) any listeners that are themselves serializable. Any * non-serializable listeners will be skipped during serialization. + * + * @see VetoableChangeSupport */ public class PropertyChangeSupport implements Serializable { private PropertyChangeListenerMap map = new PropertyChangeListenerMap(); diff --git a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java index f6707b49f7f..addf68b36cd 100644 --- a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java +++ b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java @@ -34,12 +34,49 @@ import java.util.Map.Entry; /** * This is a utility class that can be used by beans that support constrained - * properties. You can use an instance of this class as a member field - * of your bean and delegate various work to it. + * properties. It manages a list of listeners and dispatches + * {@link PropertyChangeEvent}s to them. You can use an instance of this class + * as a member field of your bean and delegate these types of work to it. + * The {@link VetoableChangeListener} can be registered for all properties + * or for a property specified by name. + *

+ * Here is an example of {@code VetoableChangeSupport} usage that follows + * the rules and recommendations laid out in the JavaBeans™ specification: + *

+ * public class MyBean {
+ *     private final VetoableChangeSupport vcs = new VetoableChangeSupport(this);
  *
+ *     public void addVetoableChangeListener(VetoableChangeListener listener) {
+ *         this.vcs.addVetoableChangeListener(listener);
+ *     }
+ *
+ *     public void removeVetoableChangeListener(VetoableChangeListener listener) {
+ *         this.vcs.removeVetoableChangeListener(listener);
+ *     }
+ *
+ *     private String value;
+ *
+ *     public String getValue() {
+ *         return this.value;
+ *     }
+ *
+ *     public void setValue(String newValue) throws PropertyVetoException {
+ *         String oldValue = this.value;
+ *         this.vcs.fireVetoableChange("value", oldValue, newValue);
+ *         this.value = newValue;
+ *     }
+ *
+ *     [...]
+ * }
+ * 
+ *

+ * A {@code VetoableChangeSupport} instance is thread-safe. + *

* This class is serializable. When it is serialized it will save * (and restore) any listeners that are themselves serializable. Any * non-serializable listeners will be skipped during serialization. + * + * @see PropertyChangeSupport */ public class VetoableChangeSupport implements Serializable { private VetoableChangeListenerMap map = new VetoableChangeListenerMap(); From d46ed5c358e5a0b0643ea929ce90cdc03a4a263d Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 3 Sep 2008 21:00:04 +0400 Subject: [PATCH 36/45] 6397609: DOC: De-register API required for PropertyEditorManager and/or doc change Reviewed-by: peterz, rupashka --- .../classes/com/sun/beans/WeakCache.java | 84 ++++++++++ .../java/beans/PropertyEditorManager.java | 70 ++++----- .../PropertyEditor/MemoryClassLoader.java | 143 ++++++++++++++++++ .../beans/PropertyEditor/Test6397609.java | 59 ++++++++ .../java/beans/PropertyEditor/TestEditor.java | 120 ++------------- 5 files changed, 331 insertions(+), 145 deletions(-) create mode 100644 jdk/src/share/classes/com/sun/beans/WeakCache.java create mode 100644 jdk/test/java/beans/PropertyEditor/MemoryClassLoader.java create mode 100644 jdk/test/java/beans/PropertyEditor/Test6397609.java diff --git a/jdk/src/share/classes/com/sun/beans/WeakCache.java b/jdk/src/share/classes/com/sun/beans/WeakCache.java new file mode 100644 index 00000000000..461c48e1fd3 --- /dev/null +++ b/jdk/src/share/classes/com/sun/beans/WeakCache.java @@ -0,0 +1,84 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package com.sun.beans; + +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; + +import java.util.Map; +import java.util.WeakHashMap; + +/** + * A hashtable-based cache with weak keys and weak values. + * An entry in the map will be automatically removed + * when its key is no longer in the ordinary use. + * A value will be automatically removed as well + * when it is no longer in the ordinary use. + * + * @since 1.7 + * + * @author Sergey A. Malenkov + */ +public final class WeakCache { + private final Map> map = new WeakHashMap>(); + + /** + * Returns a value to which the specified {@code key} is mapped, + * or {@code null} if this map contains no mapping for the {@code key}. + * + * @param key the key whose associated value is returned + * @return a value to which the specified {@code key} is mapped + */ + public V get(K key) { + Reference reference = this.map.get(key); + if (reference == null) { + return null; + } + V value = reference.get(); + if (value == null) { + this.map.remove(key); + } + return value; + } + + /** + * Associates the specified {@code value} with the specified {@code key}. + * Removes the mapping for the specified {@code key} from this cache + * if it is present and the specified {@code value} is {@code null}. + * If the cache previously contained a mapping for the {@code key}, + * the old value is replaced by the specified {@code value}. + * + * @param key the key with which the specified value is associated + * @param value the value to be associated with the specified key + */ + public void put(K key, V value) { + if (value != null) { + this.map.put(key, new WeakReference(value)); + } + else { + this.map.remove(key); + } + } +} diff --git a/jdk/src/share/classes/java/beans/PropertyEditorManager.java b/jdk/src/share/classes/java/beans/PropertyEditorManager.java index 055df1ad98c..a456c2bff54 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditorManager.java +++ b/jdk/src/share/classes/java/beans/PropertyEditorManager.java @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ package java.beans; +import com.sun.beans.WeakCache; import sun.beans.editors.*; /** @@ -55,32 +56,30 @@ import sun.beans.editors.*; public class PropertyEditorManager { /** - * Register an editor class to be used to edit values of - * a given target class. + * Registers an editor class to edit values of the given target class. + * If the editor class is {@code null}, + * then any existing definition will be removed. + * Thus this method can be used to cancel the registration. + * The registration is canceled automatically + * if either the target or editor class is unloaded. + *

+ * If there is a security manager, its {@code checkPropertiesAccess} + * method is called. This could result in a {@linkplain SecurityException}. * - *

First, if there is a security manager, its checkPropertiesAccess - * method is called. This could result in a SecurityException. + * @param targetType the class object of the type to be edited + * @param editorClass the class object of the editor class + * @throws SecurityException if a security manager exists and + * its {@code checkPropertiesAccess} method + * doesn't allow setting of system properties * - * @param targetType the Class object of the type to be edited - * @param editorClass the Class object of the editor class. If - * this is null, then any existing definition will be removed. - * @exception SecurityException if a security manager exists and its - * checkPropertiesAccess method doesn't allow setting - * of system properties. * @see SecurityManager#checkPropertiesAccess */ - - public static void registerEditor(Class targetType, Class editorClass) { + public static synchronized void registerEditor(Class targetType, Class editorClass) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } - initialize(); - if (editorClass == null) { - registry.remove(targetType); - } else { - registry.put(targetType, editorClass); - } + registry.put(targetType, editorClass); } /** @@ -90,10 +89,8 @@ public class PropertyEditorManager { * @return An editor object for the given target class. * The result is null if no suitable editor can be found. */ - public static synchronized PropertyEditor findEditor(Class targetType) { - initialize(); - Class editorClass = (Class)registry.get(targetType); + Class editorClass = registry.get(targetType); if (editorClass != null) { try { Object o = editorClass.newInstance(); @@ -143,10 +140,7 @@ public class PropertyEditorManager { * e.g. Sun implementation initially sets to {"sun.beans.editors"}. */ public static synchronized String[] getEditorSearchPath() { - // Return a copy of the searchPath. - String result[] = new String[searchPath.length]; - System.arraycopy(searchPath, 0, result, 0, searchPath.length); - return result; + return searchPath.clone(); } /** @@ -162,23 +156,22 @@ public class PropertyEditorManager { * of system properties. * @see SecurityManager#checkPropertiesAccess */ - - public static synchronized void setEditorSearchPath(String path[]) { + public static synchronized void setEditorSearchPath(String[] path) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } - if (path == null) { - path = new String[0]; - } - searchPath = path; + searchPath = (path != null) + ? path.clone() + : EMPTY; } - private static synchronized void initialize() { - if (registry != null) { - return; - } - registry = new java.util.Hashtable(); + private static String[] searchPath = { "sun.beans.editors" }; + private static final String[] EMPTY = {}; + private static final WeakCache, Class> registry; + + static { + registry = new WeakCache, Class>(); registry.put(Byte.TYPE, ByteEditor.class); registry.put(Short.TYPE, ShortEditor.class); registry.put(Integer.TYPE, IntegerEditor.class); @@ -187,7 +180,4 @@ public class PropertyEditorManager { registry.put(Float.TYPE, FloatEditor.class); registry.put(Double.TYPE, DoubleEditor.class); } - - private static String[] searchPath = { "sun.beans.editors" }; - private static java.util.Hashtable registry; } diff --git a/jdk/test/java/beans/PropertyEditor/MemoryClassLoader.java b/jdk/test/java/beans/PropertyEditor/MemoryClassLoader.java new file mode 100644 index 00000000000..cd462f88306 --- /dev/null +++ b/jdk/test/java/beans/PropertyEditor/MemoryClassLoader.java @@ -0,0 +1,143 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +import java.io.ByteArrayOutputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject.Kind; +import javax.tools.SimpleJavaFileObject; +import javax.tools.ToolProvider; + +public final class MemoryClassLoader extends ClassLoader { + private final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + private final MemoryFileManager manager = new MemoryFileManager(this.compiler); + + public Class compile(String name, String content) { + compile(new Source(name, content)); + try { + return findClass(name); + } + catch (ClassNotFoundException exception) { + throw new Error(exception); + } + } + + public void compile(Source... sources) { + List list = new ArrayList(); + if (sources != null) { + for (Source source : sources) { + if (source != null) { + list.add(source); + } + } + } + synchronized (this.manager) { + this.compiler.getTask(null, this.manager, null, null, null, list).call(); + } + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + synchronized (this.manager) { + Output mc = this.manager.map.remove(name); + if (mc != null) { + byte[] array = mc.toByteArray(); + return defineClass(name, array, 0, array.length); + } + } + return super.findClass(name); + } + + private static final class MemoryFileManager extends ForwardingJavaFileManager { + private final Map map = new HashMap(); + + MemoryFileManager(JavaCompiler compiler) { + super(compiler.getStandardFileManager(null, null, null)); + } + + @Override + public Output getJavaFileForOutput(Location location, String name, Kind kind, FileObject source) { + Output mc = this.map.get(name); + if (mc == null) { + mc = new Output(name); + this.map.put(name, mc); + } + return mc; + } + } + + private static class MemoryFileObject extends SimpleJavaFileObject { + MemoryFileObject(String name, Kind kind) { + super(toURI(name, kind.extension), kind); + } + + private static URI toURI(String name, String extension) { + try { + return new URI("mfm:///" + name.replace('.', '/') + extension); + } + catch (URISyntaxException exception) { + throw new Error(exception); + } + } + } + + private static final class Output extends MemoryFileObject { + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + Output(String name) { + super(name, Kind.CLASS); + } + + byte[] toByteArray() { + return this.baos.toByteArray(); + } + + @Override + public ByteArrayOutputStream openOutputStream() { + this.baos.reset(); + return this.baos; + } + } + + public static final class Source extends MemoryFileObject { + private final String content; + + Source(String name, String content) { + super(name, Kind.SOURCE); + this.content = content; + } + + @Override + public CharSequence getCharContent(boolean ignore) { + return this.content; + } + } +} diff --git a/jdk/test/java/beans/PropertyEditor/Test6397609.java b/jdk/test/java/beans/PropertyEditor/Test6397609.java new file mode 100644 index 00000000000..ac7065e0b3b --- /dev/null +++ b/jdk/test/java/beans/PropertyEditor/Test6397609.java @@ -0,0 +1,59 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6397609 + * @summary Tests autocleaning + * @author Sergey Malenkov + */ + +import java.beans.PropertyEditorManager; + +public class Test6397609 { + public static void main(String[] args) throws Exception { + MemoryClassLoader loader = new MemoryClassLoader(); + PropertyEditorManager.registerEditor( + Object.class, + loader.compile("Editor", + "public class Editor extends java.beans.PropertyEditorSupport {}")); + + if (!isEditorExist(Object.class)) { + throw new Error("the editor is lost"); + } + loader = null; // clean the reference + if (isEditorExist(Object.class)) { + throw new Error("unexpected editor is found"); + } + } + + private static boolean isEditorExist(Class type) { + for (int i = 0; i < 10; i++) { + System.gc(); // clean all weak references + if (null == PropertyEditorManager.findEditor(type)) { + return false; + } + } + return true; + } +} diff --git a/jdk/test/java/beans/PropertyEditor/TestEditor.java b/jdk/test/java/beans/PropertyEditor/TestEditor.java index 85a9ec338a5..25c7acf6090 100644 --- a/jdk/test/java/beans/PropertyEditor/TestEditor.java +++ b/jdk/test/java/beans/PropertyEditor/TestEditor.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2006-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,18 +23,6 @@ import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; -import java.io.ByteArrayOutputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import javax.tools.FileObject; -import javax.tools.ForwardingJavaFileManager; -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject.Kind; -import javax.tools.SimpleJavaFileObject; -import javax.tools.ToolProvider; final class TestEditor { private final PropertyEditor editor; @@ -53,8 +41,7 @@ final class TestEditor { void testJava(Object value) { this.editor.setValue(value); - MemoryFileManager manager = new MemoryFileManager(); - Object object = manager.invoke(this.editor.getJavaInitializationString()); + Object object = execute("Executor", "execute", this.editor.getJavaInitializationString()); System.out.println("Property value before: " + value); System.out.println("Property value after: " + object); @@ -87,98 +74,21 @@ final class TestEditor { : object1.equals(object2); } - private static final class MemoryFileManager extends ForwardingJavaFileManager { - private static final String CLASS = "Executor"; - private static final String METHOD = "execute"; - private static final JavaCompiler COMPILER = ToolProvider.getSystemJavaCompiler(); - private final Map map = new HashMap(); - private final MemoryClassLoader loader = new MemoryClassLoader(); + private static Object execute(String classname, String methodname, String value) { + String content + = "public class " + classname + " {" + + " public static Object " + methodname + "() throws Exception {" + + " return " + value + ";" + + " }" + + "}"; - MemoryFileManager() { - super(COMPILER.getStandardFileManager(null, null, null)); + try { + MemoryClassLoader loader = new MemoryClassLoader(); + Class type = loader.compile(classname, content); + return type.getMethod(methodname).invoke(null); } - - public Object invoke(String expression) { - MemorySource file = new MemorySource(CLASS, METHOD, expression); - if (!COMPILER.getTask(null, this, null, null, null, Arrays.asList(file)).call()) - throw new Error("compilation failed"); - - MemoryClass mc = this.map.get(CLASS); - if (mc == null) - throw new Error("class not found: " + CLASS); - - Class c = this.loader.loadClass(CLASS, mc.toByteArray()); - try { - return c.getMethod(METHOD).invoke(null); - } - catch (Exception exception) { - throw new Error(exception); - } - } - - public MemoryClass getJavaFileForOutput(Location location, String name, Kind kind, FileObject source) { - MemoryClass type = this.map.get(name); - if (type == null) { - type = new MemoryClass(name); - this.map.put(name, type); - } - return type; - } - } - - private static final class MemoryClassLoader extends ClassLoader { - public Class loadClass(String name, byte[] array) { - return defineClass(name, array, 0, array.length); - } - } - - private static class MemoryObject extends SimpleJavaFileObject { - protected MemoryObject(String name, Kind kind) { - super(toURI(name, kind.extension), kind); - } - - private static URI toURI(String name, String extension) { - try { - return new URI("mfm:///" + name.replace('.', '/') + extension); - } - catch (URISyntaxException exception) { - throw new Error(exception); - } - } - } - - private static final class MemoryClass extends MemoryObject { - private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - MemoryClass(String className) { - super(className, Kind.CLASS); - } - - public ByteArrayOutputStream openOutputStream() { - this.baos.reset(); - return this.baos; - } - - public byte[] toByteArray() { - return this.baos.toByteArray(); - } - } - - private static final class MemorySource extends MemoryObject { - private final String value; - - MemorySource(String className, String methodName, String expression) { - super(className, Kind.SOURCE); - this.value - = "public class " + className + " {\n" - + " public static Object " + methodName + "() throws Exception {\n" - + " return " + expression + ";\n" - + " }\n" - + "}\n"; - } - - public CharSequence getCharContent(boolean ignore) { - return this.value; + catch (Exception exception) { + throw new Error(exception); } } } From 4a2921184f05da4e35e1868edc310754bc5c0d2d Mon Sep 17 00:00:00 2001 From: Pavel Porvatov Date: Thu, 4 Sep 2008 15:15:24 +0400 Subject: [PATCH 37/45] 6278700: JSlider created with BoundedRangeModel fires twice when changed Removed second registration of listener Reviewed-by: peterz --- .../share/classes/javax/swing/JSlider.java | 20 +++-- .../swing/JSlider/6278700/bug6278700.java | 73 +++++++++++++++++++ 2 files changed, 82 insertions(+), 11 deletions(-) create mode 100644 jdk/test/javax/swing/JSlider/6278700/bug6278700.java diff --git a/jdk/src/share/classes/javax/swing/JSlider.java b/jdk/src/share/classes/javax/swing/JSlider.java index c2941c64234..c014f170b35 100644 --- a/jdk/src/share/classes/javax/swing/JSlider.java +++ b/jdk/src/share/classes/javax/swing/JSlider.java @@ -270,8 +270,7 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { { checkOrientation(orientation); this.orientation = orientation; - sliderModel = new DefaultBoundedRangeModel(value, 0, min, max); - sliderModel.addChangeListener(changeListener); + setModel(new DefaultBoundedRangeModel(value, 0, min, max)); updateUI(); } @@ -284,7 +283,6 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { { this.orientation = JSlider.HORIZONTAL; setModel(brm); - sliderModel.addChangeListener(changeListener); updateUI(); } @@ -476,15 +474,15 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { if (newModel != null) { newModel.addChangeListener(changeListener); + } - if (accessibleContext != null) { - accessibleContext.firePropertyChange( - AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, - (oldModel == null - ? null : Integer.valueOf(oldModel.getValue())), - (newModel == null - ? null : Integer.valueOf(newModel.getValue()))); - } + if (accessibleContext != null) { + accessibleContext.firePropertyChange( + AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, + (oldModel == null + ? null : Integer.valueOf(oldModel.getValue())), + (newModel == null + ? null : Integer.valueOf(newModel.getValue()))); } firePropertyChange("model", oldModel, sliderModel); diff --git a/jdk/test/javax/swing/JSlider/6278700/bug6278700.java b/jdk/test/javax/swing/JSlider/6278700/bug6278700.java new file mode 100644 index 00000000000..56d70d4cfad --- /dev/null +++ b/jdk/test/javax/swing/JSlider/6278700/bug6278700.java @@ -0,0 +1,73 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6278700 + * @summary JSlider created with BoundedRangeModel fires twice when changed + * @author Pavel Porvatov + @run main bug6278700 + */ + +import javax.swing.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +public class bug6278700 { + private int changeCount; + + private final ChangeListener listener = new ChangeListener() { + public void stateChanged(ChangeEvent e) { + changeCount++; + } + }; + + public static void main(String[] args) { + new bug6278700(); + } + + public bug6278700() { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + JSlider slider = new JSlider(new DefaultBoundedRangeModel(5, 0, 0, 10)); + + slider.addChangeListener(listener); + slider.setValue(0); + + if (changeCount != 1) { + throw new RuntimeException("Incorrect stateChanged count: " + Integer.toString(changeCount)); + } + + changeCount = 0; + + slider = new JSlider(); + + slider.addChangeListener(listener); + slider.setValue(0); + + if (changeCount != 1) { + throw new RuntimeException("Incorrect stateChanged count: " + Integer.toString(changeCount)); + } + } + }); + } +} From 14ea0be2120854d9620bd10cbd229c6bd3a05a37 Mon Sep 17 00:00:00 2001 From: Yuka Kamiya Date: Mon, 8 Sep 2008 10:44:57 +0900 Subject: [PATCH 38/45] 6665028: native code of method j*.text.Bidi.nativeBidiChars is using the contents of a primitive array direct Reviewed-by: okutsu --- jdk/src/share/native/sun/font/bidi/ubidi.c | 26 ++--- jdk/test/java/text/Bidi/Bug6665028.java | 129 +++++++++++++++++++++ 2 files changed, 142 insertions(+), 13 deletions(-) create mode 100644 jdk/test/java/text/Bidi/Bug6665028.java diff --git a/jdk/src/share/native/sun/font/bidi/ubidi.c b/jdk/src/share/native/sun/font/bidi/ubidi.c index 97392b91d2a..41be82c3870 100644 --- a/jdk/src/share/native/sun/font/bidi/ubidi.c +++ b/jdk/src/share/native/sun/font/bidi/ubidi.c @@ -384,23 +384,23 @@ ubidi_setPara(UBiDi *pBiDi, const UChar *text, int32_t length, return; } - /* are explicit levels specified? */ - if(embeddingLevels==NULL) { - /* no: determine explicit levels according to the (Xn) rules */\ - if(getLevelsMemory(pBiDi, length)) { - pBiDi->levels=pBiDi->levelsMemory; + if (getLevelsMemory(pBiDi, length)) { + pBiDi->levels=pBiDi->levelsMemory; + /* are explicit levels specified? */ + if(embeddingLevels==NULL) { + /* no: determine explicit levels according to the (Xn) rules */ direction=resolveExplicitLevels(pBiDi); } else { - *pErrorCode=U_MEMORY_ALLOCATION_ERROR; - return; + /* set BN for all explicit codes, check that all levels are paraLevel..UBIDI_MAX_EXPLICIT_LEVEL */ + icu_memcpy(pBiDi->levels, embeddingLevels, length); + direction=checkExplicitLevels(pBiDi, pErrorCode); + if(U_FAILURE(*pErrorCode)) { + return; + } } } else { - /* set BN for all explicit codes, check that all levels are paraLevel..UBIDI_MAX_EXPLICIT_LEVEL */ - pBiDi->levels=embeddingLevels; - direction=checkExplicitLevels(pBiDi, pErrorCode); - if(U_FAILURE(*pErrorCode)) { - return; - } + *pErrorCode=U_MEMORY_ALLOCATION_ERROR; + return; } /* diff --git a/jdk/test/java/text/Bidi/Bug6665028.java b/jdk/test/java/text/Bidi/Bug6665028.java new file mode 100644 index 00000000000..e8edd54a5c3 --- /dev/null +++ b/jdk/test/java/text/Bidi/Bug6665028.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6665028 + * @summary verify that the memory corruption doesn't happen. Note + * that this test case fails without the fix in some different ways, + * including timeout, due to the memory corruption. + * @build Bug6665028 + * @run main/othervm/timeout=60 -Xmx16m Bug6665028 + */ + +import java.awt.font.TextAttribute; +import java.text.AttributedString; +import java.text.Bidi; + +// test1() and test2() were derived from BidiEmbeddingTest. +public class Bug6665028 { + + private static boolean runrun = true; + + private static class Test extends Thread { + public void run() { + while (runrun) { + test1(); + test2(); + } + } + } + + public static void main(String[] args) { + Test[] tests = new Test[4]; + for (int i = 0; i < tests.length; i++) { + Test t = new Test(); + tests[i] = t; + t.start(); + } + + try { + Thread.sleep(45000); + } catch (InterruptedException e) { + } + + runrun = false; + + for (int i = 0; i < tests.length; i++) { + try { + tests[i].join(); + } catch (InterruptedException e) { + } + } + } + + static String target; + static { + String s = "A Bidi object provides information on the bidirectional reordering of the text used to create it. This is required, for example, to properly display Arabic or Hebrew text. "; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 1000; i++) { + sb.append(s); + } + target = sb.toString(); + } + + static void test1() { + String str = "If this text is >" + target + "< the test passed."; + int start = str.indexOf(target); + int limit = start + target.length(); + + AttributedString astr = new AttributedString(str); + astr.addAttribute(TextAttribute.BIDI_EMBEDDING, + new Integer(-1), + start, + limit); + + Bidi bidi = new Bidi(astr.getIterator()); + + byte[] embs = new byte[str.length() + 3]; + for (int i = start + 1; i < limit + 1; ++i) { + embs[i] = -1; + } + + Bidi bidi2 = new Bidi(str.toCharArray(), 0, embs, 1, str.length(), Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT); + if (bidi.getRunCount() != 3 || bidi2.getRunCount() != 3) { + throw new Error("Bidi run count incorrect"); + } + } + + static void test2() { + String str = "If this text is >" + target + "< the test passed."; + int length = str.length(); + int start = str.indexOf(target); + int limit = start + target.length(); + + AttributedString astr = new AttributedString(str); + astr.addAttribute(TextAttribute.RUN_DIRECTION, TextAttribute.RUN_DIRECTION_RTL); + + astr.addAttribute(TextAttribute.BIDI_EMBEDDING, + new Integer(-3), + start, + limit); + + Bidi bidi = new Bidi(astr.getIterator()); + + if (bidi.getRunCount() != 6) { // runs of spaces and angles at embedding bound,s and final period, each get level 1 + throw new Error("Bidi embedding processing failed"); + } + } +} From 9ce33168b12ff98fd14b3ba85c2ea5eb72c77616 Mon Sep 17 00:00:00 2001 From: Yuka Kamiya Date: Mon, 8 Sep 2008 11:49:49 +0900 Subject: [PATCH 39/45] 6607310: InputContext may cause loading of swing classes even for non-Swing applets Reviewed-by: okutsu --- jdk/src/share/classes/sun/awt/im/CompositionArea.java | 3 ++- jdk/src/share/classes/sun/awt/im/InputContext.java | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/sun/awt/im/CompositionArea.java b/jdk/src/share/classes/sun/awt/im/CompositionArea.java index ff8bfb60fa9..4808aa45730 100644 --- a/jdk/src/share/classes/sun/awt/im/CompositionArea.java +++ b/jdk/src/share/classes/sun/awt/im/CompositionArea.java @@ -56,7 +56,8 @@ import javax.swing.border.LineBorder; * @author JavaSoft International */ -public class CompositionArea extends JPanel implements InputMethodListener { +// This class is final due to the 6607310 fix. Refer to the CR for details. +public final class CompositionArea extends JPanel implements InputMethodListener { private CompositionAreaHandler handler; diff --git a/jdk/src/share/classes/sun/awt/im/InputContext.java b/jdk/src/share/classes/sun/awt/im/InputContext.java index 8948d55b458..d0c84c726ed 100644 --- a/jdk/src/share/classes/sun/awt/im/InputContext.java +++ b/jdk/src/share/classes/sun/awt/im/InputContext.java @@ -297,7 +297,7 @@ public class InputContext extends java.awt.im.InputContext */ synchronized (source.getTreeLock()) { synchronized (this) { - if (source instanceof CompositionArea) { + if ("sun.awt.im.CompositionArea".equals(source.getClass().getName())) { // no special handling for this one } else if (getComponentWindow(source) instanceof InputMethodWindow) { // no special handling for this one either From 3927ae98322f00b5af1cf6cb461e1e215f95ab1c Mon Sep 17 00:00:00 2001 From: Yuka Kamiya Date: Mon, 8 Sep 2008 13:31:45 +0900 Subject: [PATCH 40/45] 6645292: [Fmt-Da] Timezone Western Summer Time (Australia) is parsed incorrectly Reviewed-by: okutsu --- .../classes/java/text/SimpleDateFormat.java | 9 ++- .../text/Format/DateFormat/Bug6645292.java | 66 +++++++++++++++++++ 2 files changed, 72 insertions(+), 3 deletions(-) create mode 100644 jdk/test/java/text/Format/DateFormat/Bug6645292.java diff --git a/jdk/src/share/classes/java/text/SimpleDateFormat.java b/jdk/src/share/classes/java/text/SimpleDateFormat.java index 548ffb730f3..38893c9d1ca 100644 --- a/jdk/src/share/classes/java/text/SimpleDateFormat.java +++ b/jdk/src/share/classes/java/text/SimpleDateFormat.java @@ -1482,10 +1482,13 @@ public class SimpleDateFormat extends DateFormat { // If the time zone matched uses the same name // (abbreviation) for both standard and daylight time, // let the time zone in the Calendar decide which one. - if (!useSameName) { + // + // Also if tz.getDSTSaving() returns 0 for DST, use tz to + // determine the local time. (6645292) + int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0; + if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) { calendar.set(Calendar.ZONE_OFFSET, tz.getRawOffset()); - calendar.set(Calendar.DST_OFFSET, - nameIndex >= 3 ? tz.getDSTSavings() : 0); + calendar.set(Calendar.DST_OFFSET, dstAmount); } return (start + zoneNames[nameIndex].length()); } diff --git a/jdk/test/java/text/Format/DateFormat/Bug6645292.java b/jdk/test/java/text/Format/DateFormat/Bug6645292.java new file mode 100644 index 00000000000..9c62833cf47 --- /dev/null +++ b/jdk/test/java/text/Format/DateFormat/Bug6645292.java @@ -0,0 +1,66 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6645292 + * @summary Make sure to parse a DST time zone name with which the + * last DST rule doesn't observe DST. + */ + +import java.text.*; +import java.util.*; +import static java.util.Calendar.*; + +public class Bug6645292 { + public static void main(String[] args) { + Locale loc = Locale.getDefault(); + TimeZone zone = TimeZone.getDefault(); + try { + Locale.setDefault(Locale.US); + // Use "Asia/Shanghai" with an old time stamp rather than + // "Australia/Perth" because if Perth decides to obserb DST + // permanently, that decision will make this test case + // useless. There's the same risk with China, though. + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); + Calendar cal = Calendar.getInstance(); + cal.clear(); + cal.set(1986, JUNE, 1); + Date d1 = cal.getTime(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzzz"); + String s = df.format(d1); + Date d2 = null; + try { + d2 = df.parse(s); + } catch (Exception e) { + throw new RuntimeException(e); + } + if (!d1.equals(d2)) { + throw new RuntimeException("d1 (" + d1 + ") != d2 (" + d2 + ")"); + } + } finally { + Locale.setDefault(loc); + TimeZone.setDefault(zone); + } + } +} From 6ee252719cd4182bd1412e866ee2a1854fc8b9b7 Mon Sep 17 00:00:00 2001 From: Yuka Kamiya Date: Mon, 8 Sep 2008 14:31:08 +0900 Subject: [PATCH 41/45] 4823811: [Fmt-Da] SimpleDateFormat patterns don't allow embedding of some literal punctuation Reviewed-by: okutsu --- .../classes/java/text/SimpleDateFormat.java | 115 ++- .../text/Format/DateFormat/Bug4823811.java | 789 ++++++++++++++++++ 2 files changed, 895 insertions(+), 9 deletions(-) create mode 100644 jdk/test/java/text/Format/DateFormat/Bug4823811.java diff --git a/jdk/src/share/classes/java/text/SimpleDateFormat.java b/jdk/src/share/classes/java/text/SimpleDateFormat.java index 38893c9d1ca..e543899fe95 100644 --- a/jdk/src/share/classes/java/text/SimpleDateFormat.java +++ b/jdk/src/share/classes/java/text/SimpleDateFormat.java @@ -373,6 +373,24 @@ public class SimpleDateFormat extends DateFormat { */ private String pattern; + /** + * Saved numberFormat and pattern. + * @see SimpleDateFormat#checkNegativeNumberExpression + */ + transient private NumberFormat originalNumberFormat; + transient private String originalNumberPattern; + + /** + * The minus sign to be used with format and parse. + */ + transient private char minusSign = '-'; + + /** + * True when a negative sign follows a number. + * (True as default in Arabic.) + */ + transient private boolean hasFollowingMinusSign = false; + /** * The compiled pattern. */ @@ -1226,6 +1244,8 @@ public class SimpleDateFormat extends DateFormat { */ public Date parse(String text, ParsePosition pos) { + checkNegativeNumberExpression(); + int start = pos.index; int oldStart = start; int textLength = text.length(); @@ -1271,14 +1291,42 @@ public class SimpleDateFormat extends DateFormat { // digit text (e.g., "20010704") with a pattern which // has no delimiters between fields, like "yyyyMMdd". boolean obeyCount = false; + + // In Arabic, a minus sign for a negative number is put after + // the number. Even in another locale, a minus sign can be + // put after a number using DateFormat.setNumberFormat(). + // If both the minus sign and the field-delimiter are '-', + // subParse() needs to determine whether a '-' after a number + // in the given text is a delimiter or is a minus sign for the + // preceding number. We give subParse() a clue based on the + // information in compiledPattern. + boolean useFollowingMinusSignAsDelimiter = false; + if (i < compiledPattern.length) { int nextTag = compiledPattern[i] >>> 8; - if (!(nextTag == TAG_QUOTE_ASCII_CHAR || nextTag == TAG_QUOTE_CHARS)) { + if (!(nextTag == TAG_QUOTE_ASCII_CHAR || + nextTag == TAG_QUOTE_CHARS)) { obeyCount = true; } + + if (hasFollowingMinusSign && + (nextTag == TAG_QUOTE_ASCII_CHAR || + nextTag == TAG_QUOTE_CHARS)) { + int c; + if (nextTag == TAG_QUOTE_ASCII_CHAR) { + c = compiledPattern[i] & 0xff; + } else { + c = compiledPattern[i+1]; + } + + if (c == minusSign) { + useFollowingMinusSignAsDelimiter = true; + } + } } start = subParse(text, start, tag, count, obeyCount, - ambiguousYear, pos); + ambiguousYear, pos, + useFollowingMinusSignAsDelimiter); if (start < 0) { pos.index = oldStart; return null; @@ -1514,8 +1562,8 @@ public class SimpleDateFormat extends DateFormat { */ private int subParse(String text, int start, int patternCharIndex, int count, boolean obeyCount, boolean[] ambiguousYear, - ParsePosition origPos) - { + ParsePosition origPos, + boolean useFollowingMinusSignAsDelimiter) { Number number = null; int value = 0; ParsePosition pos = new ParsePosition(0); @@ -1540,10 +1588,10 @@ public class SimpleDateFormat extends DateFormat { // a number value. We handle further, more generic cases below. We need // to handle some of them here because some fields require extra processing on // the parsed value. - if (patternCharIndex == 4 /*HOUR_OF_DAY1_FIELD*/ || - patternCharIndex == 15 /*HOUR1_FIELD*/ || - (patternCharIndex == 2 /*MONTH_FIELD*/ && count <= 2) || - patternCharIndex == 1) { + if (patternCharIndex == 4 /* HOUR_OF_DAY1_FIELD */ || + patternCharIndex == 15 /* HOUR1_FIELD */ || + (patternCharIndex == 2 /* MONTH_FIELD */ && count <= 2) || + patternCharIndex == 1 /* YEAR_FIELD */) { // It would be good to unify this with the obeyCount logic below, // but that's going to be difficult. if (obeyCount) { @@ -1560,6 +1608,15 @@ public class SimpleDateFormat extends DateFormat { } } else { value = number.intValue(); + + if (useFollowingMinusSignAsDelimiter && (value < 0) && + (((pos.index < text.length()) && + (text.charAt(pos.index) != minusSign)) || + ((pos.index == text.length()) && + (text.charAt(pos.index-1) == minusSign)))) { + value = -value; + pos.index--; + } } } @@ -1891,7 +1948,18 @@ public class SimpleDateFormat extends DateFormat { number = numberFormat.parse(text, pos); } if (number != null) { - calendar.set(field, number.intValue()); + value = number.intValue(); + + if (useFollowingMinusSignAsDelimiter && (value < 0) && + (((pos.index < text.length()) && + (text.charAt(pos.index) != minusSign)) || + ((pos.index == text.length()) && + (text.charAt(pos.index-1) == minusSign)))) { + value = -value; + pos.index--; + } + + calendar.set(field, value); return pos.index; } break parsing; @@ -2102,4 +2170,33 @@ public class SimpleDateFormat extends DateFormat { } } } + + /** + * Analyze the negative subpattern of DecimalFormat and set/update values + * as necessary. + */ + private void checkNegativeNumberExpression() { + if ((numberFormat instanceof DecimalFormat) && + !numberFormat.equals(originalNumberFormat)) { + String numberPattern = ((DecimalFormat)numberFormat).toPattern(); + if (!numberPattern.equals(originalNumberPattern)) { + hasFollowingMinusSign = false; + + int separatorIndex = numberPattern.indexOf(';'); + // If the negative subpattern is not absent, we have to analayze + // it in order to check if it has a following minus sign. + if (separatorIndex > -1) { + int minusIndex = numberPattern.indexOf('-', separatorIndex); + if ((minusIndex > numberPattern.lastIndexOf('0')) && + (minusIndex > numberPattern.lastIndexOf('#'))) { + hasFollowingMinusSign = true; + minusSign = ((DecimalFormat)numberFormat).getDecimalFormatSymbols().getMinusSign(); + } + } + originalNumberPattern = numberPattern; + } + originalNumberFormat = numberFormat; + } + } + } diff --git a/jdk/test/java/text/Format/DateFormat/Bug4823811.java b/jdk/test/java/text/Format/DateFormat/Bug4823811.java new file mode 100644 index 00000000000..65b4aa26349 --- /dev/null +++ b/jdk/test/java/text/Format/DateFormat/Bug4823811.java @@ -0,0 +1,789 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * @test + * @bug 4823811 + * @summary Confirm that text which includes numbers with a trailing minus sign is parsed correctly. + */ + +import java.text.*; +import java.util.*; + +public class Bug4823811 { + + private static Locale localeEG = new Locale("ar", "EG"); + private static Locale localeUS = Locale.US; + + private static String JuneInArabic = "\u064a\u0648\u0646\u064a\u0648"; + private static String JulyInArabic = "\u064a\u0648\u0644\u064a\u0648"; + private static String JuneInEnglish = "June"; + private static String JulyInEnglish = "July"; + + private static String BORDER = + "============================================================"; + + /* + * I don't use static import here intentionally so that this test program + * can be run on JDK 1.4.2. + */ + private static int ERA = Calendar.ERA; + private static int BC = GregorianCalendar.BC; +// private static int JAN = Calendar.JANUARY; +// private static int FEB = Calendar.FEBRUARY; +// private static int MAR = Calendar.MARCH; + private static int APR = Calendar.APRIL; + private static int MAY = Calendar.MAY; + private static int JUN = Calendar.JUNE; + private static int JUL = Calendar.JULY; +// private static int AUG = Calendar.AUGUST; +// private static int SEP = Calendar.SEPTEMBER; +// private static int OCT = Calendar.OCTOBER; +// private static int NOV = Calendar.NOVEMBER; +// private static int DEC = Calendar.DECEMBER; + + private static String[] patterns = { + "yyyy MMMM d H m s", + "yyyy MM dd hh mm ss", + + /* + * Because 1-based HOUR_OF_DAY, 1-based HOUR, MONTH, and YEAR fields + * are parsed using different code from the code for other numeric + * fields, I prepared YEAR-preceding patterns and SECOND-preceding + * patterns. + */ + "yyyy M d h m s", + " yyyy M d h m s", + "yyyy M d h m s ", + + "s m h d M yyyy", + " s m h d M yyyy", + "s m h d M yyyy ", + }; + + private static char originalMinusSign1 = ':'; + private static char originalMinusSign2 = '\uff0d'; // fullwidth minus + private static String[] delimiters = {"-", "/", ":", "/", "\uff0d", "/"}; + private static String[][] specialDelimiters = { + // for Arabic formatter and modified English formatter + {"--", "-/", "::", ":/", "\uff0d\uff0d", "\uff0d/"}, + + // for English formatter and modified Arabic formatter + {"--", "/-", "::", "/:", "\uff0d\uff0d", "/\uff0d"}, + }; + + /* + * Format: + * +-------------------------------------------------------------------+ + * | Input | Output | + * +---------------------+---------------------------------------------| + * | datesEG & datesUS | formattedDatesEG & formattedDatesUS | + * +-------------------------------------------------------------------+ + * + * Parse: + * +-------------------------------------------------------------------+ + * | Input | Output | + * |---------------------+---------------------------------------------| + * | datesToParse | datesEG & datesUS | + * +-------------------------------------------------------------------+ + */ + private static String[][] datesToParse = { + // "JUNE" and "JULY" are replaced with a localized month name later. + {"2008 JULY 20 3 12 83", + "2008 JULY 20 3 12 83", + "2008 JULY 20 3 12 83"}, + + {"2008 07 20 03 12 83", + "2008 07 20 03 12 83", + "2008 07 20 03 12 83"}, + + {"2008 7 20 3 12 83", + "2008 7 20 3 12 83", + "2008 7 20 3 12 83"}, + + {" 2008 7 20 3 12 83", + " 2008 7 20 3 12 83", + " 2008 7 20 3 12 83", + "2008 7 20 3 12 83"}, + + {"2008 7 20 3 12 83 ", + "2008 7 20 3 12 83 ", + "2008 7 20 3 12 83"}, + + {"83 12 3 20 7 2008", + "83 12 3 20 7 2008", + "83 12 3 20 7 2008"}, + + {" 83 12 3 20 7 2008", + " 83 12 3 20 7 2008", + " 83 12 3 20 7 2008", + "83 12 3 20 7 2008"}, + + {"83 12 3 20 7 2008 ", + "83 12 3 20 7 2008 ", + "83 12 3 20 7 2008"}, + }; + + // For formatting + private static String[][] formattedDatesEG = { + {"2008 JULY 20 3 13 23", + "2009 JULY 20 3 13 23", + null}, + + {"2008 07 20 03 13 23", + "2009 07 20 03 13 23", + "2007 05 20 03 13 23"}, + + {"2008 7 20 3 13 23", + "2009 6 10 3 13 23", + "2007 4 10 3 13 23"}, + + {" 2008 7 20 3 13 23", + null, + " 2009 7 20 3 13 23", + null}, + + {"2008 7 20 3 13 23 ", + "2008 7 20 3 10 37 ", + null}, + + {"23 13 3 20 7 2008", + "37 10 9 19 7 2008", + "23 49 8 19 7 2008"}, + + {" 23 13 3 20 7 2008", + null, + " 37 10 3 20 7 2008", + null}, + + {"23 13 3 20 7 2008 ", + "23 13 3 20 7 2009 ", + null}, + }; + + private static String[][] formattedDatesUS = { + {"2008 JULY 20 3 13 23", + null, + "2008 JUNE 10 3 13 23"}, + + {"2008 07 20 03 13 23", + "2007 05 20 03 13 23", + "2008 06 10 03 13 23"}, + + {"2008 7 20 3 13 23", + "2007 5 19 9 13 23", + "2008 6 9 9 13 23"}, + + {" 2008 7 20 3 13 23", + " 2009 7 20 3 13 23", + " 2007 5 20 3 13 23", + null}, + + {"2008 7 20 3 13 23 ", + "2008 7 20 3 13 23 ", + null}, + + {"23 13 3 20 7 2008", + "23 49 2 10 6 2008", + "23 13 9 9 6 2008"}, + + {" 23 13 3 20 7 2008", + " 37 10 3 20 7 2008", + " 23 49 2 20 7 2008", + null}, + + {"23 13 3 20 7 2008 ", + "23 13 3 20 7 2008 ", + null}, + }; + + private static GregorianCalendar[][] datesEG = { + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), + null}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2007, MAY, 20, 3, 12, 83)}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar(-2008, JUL, -20, 3, 12, 83), + new GregorianCalendar( 2007, APR, 10, 3, 12, 83)}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + null, + new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), + null}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2008, JUL, 20, 3, 12, -83), + null}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2008, JUL, 20, -3, 12, -83), + new GregorianCalendar( 2008, JUL, 20, -3, -12, 83)}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + null, + new GregorianCalendar( 2008, JUL, 20, 3, 12, -83), + null}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), + null}, + }; + + private static GregorianCalendar[][] datesUS = { + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + null, + new GregorianCalendar( 2008, JUN, 10, 3, 12, 83)}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2007, MAY, 20, 3, 12, 83), + new GregorianCalendar( 2008, JUN, 10, 3, 12, 83)}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2007, MAY, 20, -3, 12, 83), + new GregorianCalendar( 2008, JUL, -20, -3, 12, 83)}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2007, MAY, 20, 3, 12, 83), + null}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + null}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2008, JUL, -20, 3, -12, 83), + new GregorianCalendar( 2008, JUL, -20, -3, 12, 83)}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2008, JUL, 20, 3, 12, -83), + new GregorianCalendar( 2008, JUL, 20, 3, -12, 83), + null}, + + {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), + null}, + }; + + /* flags */ + private static boolean err = false; + private static boolean verbose = false; + + + public static void main(String[] args) { + if (args.length == 1 && args[0].equals("-v")) { + verbose = true; + } + + Locale defaultLocale = Locale.getDefault(); + TimeZone defaultTimeZone = TimeZone.getDefault(); + + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo")); + + try { + /* + * Test SimpleDateFormat.parse() and format() for original + * SimpleDateFormat instances + */ + testDateFormat1(); + + /* + * Test SimpleDateFormat.parse() and format() for modified + * SimpleDateFormat instances using an original minus sign, + * pattern, and diffenrent month names in DecimalFormat + */ + testDateFormat2(); + + /* + * Test SimpleDateFormat.parse() and format() for modified + * SimpleDateFormat instances using a fullwidth minus sign + */ + testDateFormat3(); + + /* + * Just to confirm that regressions aren't introduced in + * DecimalFormat. This cannot happen, though. Because I didn't + * change DecimalFormat at all. + */ + testNumberFormat(); + } + catch (Exception e) { + err = true; + System.err.println("Unexpected exception: " + e); + } + finally { + Locale.setDefault(defaultLocale); + TimeZone.setDefault(defaultTimeZone); + + if (err) { + System.err.println(BORDER + " Test failed."); + throw new RuntimeException("Date/Number formatting/parsing error."); + } else { + System.out.println(BORDER + " Test passed."); + } + } + } + + + // + // DateFormat test + // + private static void testDateFormat1() { + for (int i = 0; i < patterns.length; i++) { + System.out.println(BORDER); + for (int j = 0; j <= 1; j++) { + // Generate a pattern + String pattern = patterns[i].replaceAll(" ", delimiters[j]); + System.out.println("Pattern=\"" + pattern + "\""); + + System.out.println("*** DateFormat.format test in ar_EG"); + testDateFormatFormattingInRTL(pattern, i, j, null, localeEG, false); + + System.out.println("*** DateFormat.parse test in ar_EG"); + testDateFormatParsingInRTL(pattern, i, j, null, localeEG, false); + + System.out.println("*** DateFormat.format test in en_US"); + testDateFormatFormattingInLTR(pattern, i, j, null, localeUS, true); + + System.out.println("*** DateFormat.parse test in en_US"); + testDateFormatParsingInLTR(pattern, i, j, null, localeUS, true); + } + } + } + + private static void testDateFormat2() { + /* + * modified ar_EG Date&Time formatter : + * minus sign: ':' + * pattern: "#,##0.###" + * month names: In Arabic + * + * modified en_US Date&Time formatter : + * minus sign: ':' + * pattern: "#,##0.###;#,##0.###-" + * month names: In English + */ + DecimalFormat dfEG = (DecimalFormat)NumberFormat.getInstance(localeEG); + DecimalFormat dfUS = (DecimalFormat)NumberFormat.getInstance(localeUS); + + DecimalFormatSymbols dfsEG = dfEG.getDecimalFormatSymbols(); + DecimalFormatSymbols dfsUS = dfUS.getDecimalFormatSymbols(); + dfsEG.setMinusSign(originalMinusSign1); + dfsUS.setMinusSign(originalMinusSign1); + dfEG.setDecimalFormatSymbols(dfsUS); + dfUS.setDecimalFormatSymbols(dfsEG); + + String patternEG = dfEG.toPattern(); + String patternUS = dfUS.toPattern(); + + dfEG.applyPattern(patternUS); + dfUS.applyPattern(patternEG); + + for (int i = 0; i < patterns.length; i++) { + System.out.println(BORDER); + for (int j = 2; j <= 3; j++) { + // Generate a pattern + String pattern = patterns[i].replaceAll(" ", delimiters[j]); + System.out.println("Pattern=\"" + pattern + "\""); + + System.out.println("*** DateFormat.format test in modified en_US"); + testDateFormatFormattingInRTL(pattern, i, j, dfUS, localeUS, true); + + System.out.println("*** DateFormat.parse test in modified en_US"); + testDateFormatParsingInRTL(pattern, i, j, dfUS, localeUS, true); + + System.out.println("*** DateFormat.format test in modified ar_EG"); + testDateFormatFormattingInLTR(pattern, i, j, dfEG, localeEG, false); + + System.out.println("*** DateFormat.parse test in modified ar_EG"); + testDateFormatParsingInLTR(pattern, i, j, dfEG, localeEG, false); + } + } + } + + private static void testDateFormat3() { + /* + * modified ar_EG Date&Time formatter : + * minus sign: '\uff0d' // fullwidth minus + * pattern: "#,##0.###;#,##0.###-" + * month names: In Arabic + * + * modified en_US Date&Time formatter : + * minus sign: '\uff0d' // fullwidth minus + * pattern: "#,##0.###" + * month names: In English + */ + DecimalFormat dfEG = (DecimalFormat)NumberFormat.getInstance(localeEG); + DecimalFormat dfUS = (DecimalFormat)NumberFormat.getInstance(localeUS); + + DecimalFormatSymbols dfsEG = dfEG.getDecimalFormatSymbols(); + DecimalFormatSymbols dfsUS = dfUS.getDecimalFormatSymbols(); + dfsEG.setMinusSign(originalMinusSign2); + dfsUS.setMinusSign(originalMinusSign2); + dfEG.setDecimalFormatSymbols(dfsEG); + dfUS.setDecimalFormatSymbols(dfsUS); + + for (int i = 0; i < patterns.length; i++) { + System.out.println(BORDER); + for (int j = 4; j <= 5; j++) { + // Generate a pattern + String pattern = patterns[i].replaceAll(" ", delimiters[j]); + System.out.println("Pattern=\"" + pattern + "\""); + + System.out.println("*** DateFormat.format test in modified ar_EG"); + testDateFormatFormattingInRTL(pattern, i, j, dfEG, localeEG, false); + + System.out.println("*** DateFormat.parse test in modified ar_EG"); + testDateFormatParsingInRTL(pattern, i, j, dfEG, localeEG, false); + + System.out.println("*** DateFormat.format test in modified en_US"); + testDateFormatFormattingInLTR(pattern, i, j, dfUS, localeUS, true); + + System.out.println("*** DateFormat.parse test in modified en_US"); + testDateFormatParsingInLTR(pattern, i, j, dfUS, localeUS, true); + } + } + } + + private static void testDateFormatFormattingInRTL(String pattern, + int basePattern, + int delimiter, + NumberFormat nf, + Locale locale, + boolean useEnglishMonthName) { + Locale.setDefault(locale); + + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + if (nf != null) { + sdf.setNumberFormat(nf); + } + for (int i = 0; i < datesToParse[basePattern].length; i++) { + if (datesEG[basePattern][i] == null) { + continue; + } + + String expected = formattedDatesEG[basePattern][i] + .replaceAll("JUNE", (useEnglishMonthName ? + JuneInEnglish : JuneInArabic)) + .replaceAll("JULY", (useEnglishMonthName ? + JulyInEnglish : JulyInArabic)) + .replaceAll(" ", delimiters[delimiter]); + testDateFormatFormatting(sdf, pattern, datesEG[basePattern][i], + expected, locale.toString()); + } + } + + private static void testDateFormatFormattingInLTR(String pattern, + int basePattern, + int delimiter, + NumberFormat nf, + Locale locale, + boolean useEnglishMonthName) { + Locale.setDefault(locale); + + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + if (nf != null) { + sdf.setNumberFormat(nf); + } + for (int i = 0; i < datesToParse[basePattern].length; i++) { + if (datesUS[basePattern][i] == null) { + continue; + } + + String expected = formattedDatesUS[basePattern][i] + .replaceAll("JUNE", (useEnglishMonthName ? + JuneInEnglish : JuneInArabic)) + .replaceAll("JULY", (useEnglishMonthName ? + JulyInEnglish : JulyInArabic)) + .replaceAll(" ", delimiters[delimiter]); + testDateFormatFormatting(sdf, pattern, datesUS[basePattern][i], + expected, locale.toString()); + } + } + + private static void testDateFormatFormatting(SimpleDateFormat sdf, + String pattern, + GregorianCalendar givenGC, + String expected, + String locale) { + Date given = givenGC.getTime(); + String str = sdf.format(given); + if (expected.equals(str)) { + if (verbose) { + System.out.print(" Passed: SimpleDateFormat("); + System.out.print(locale + ", \"" + pattern + "\").format("); + System.out.println(given + ")"); + + System.out.print(" ---> \"" + str + "\" "); + System.out.println((givenGC.get(ERA) == BC) ? "(BC)" : "(AD)"); + } + } else { + err = true; + + System.err.print(" Failed: Unexpected SimpleDateFormat("); + System.out.print(locale + ", \"" + pattern + "\").format("); + System.out.println(given + ") result."); + + System.out.println(" Expected: \"" + expected + "\""); + + System.out.print(" Got: \"" + str + "\" "); + System.out.println((givenGC.get(ERA) == BC) ? "(BC)" : "(AD)"); + } + } + + private static void testDateFormatParsingInRTL(String pattern, + int basePattern, + int delimiter, + NumberFormat nf, + Locale locale, + boolean useEnglishMonthName) { + Locale.setDefault(locale); + + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + if (nf != null) { + sdf.setNumberFormat(nf); + } + for (int i = 0; i < datesToParse[basePattern].length; i++) { + String given = datesToParse[basePattern][i] + .replaceAll(" ", specialDelimiters[0][delimiter]) + .replaceAll(" ", delimiters[delimiter]); + + testDateFormatParsing(sdf, pattern, + given.replaceAll("JULY", (useEnglishMonthName ? + JulyInEnglish : JulyInArabic)), + datesEG[basePattern][i], locale.toString()); + } + } + + private static void testDateFormatParsingInLTR(String pattern, + int basePattern, + int delimiter, + NumberFormat nf, + Locale locale, + boolean useEnglishMonthName) { + Locale.setDefault(locale); + + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + if (nf != null) { + sdf.setNumberFormat(nf); + } + for (int i = 0; i < datesToParse[basePattern].length; i++) { + String given = datesToParse[basePattern][i] + .replaceAll(" ", specialDelimiters[1][delimiter]) + .replaceAll(" ", delimiters[delimiter]); + + testDateFormatParsing(sdf, pattern, + given.replaceAll("JULY", (useEnglishMonthName ? + JulyInEnglish : JulyInArabic)), + datesUS[basePattern][i], locale.toString()); + } + } + + private static void testDateFormatParsing(SimpleDateFormat sdf, + String pattern, + String given, + GregorianCalendar expectedGC, + String locale) { + try { + Date d = sdf.parse(given); + if (expectedGC == null) { + err = true; + System.err.print(" Failed: SimpleDateFormat(" + locale); + System.err.print(", \"" + pattern + "\").parse(\"" + given); + System.err.println("\") should have thrown ParseException"); + } else if (expectedGC.getTime().equals(d)) { + if (verbose) { + System.out.print(" Passed: SimpleDateFormat(" + locale); + System.out.print(", \"" + pattern + "\").parse(\"" + given); + System.out.println("\")"); + + System.out.print(" ---> " + d + " (" + d.getTime()); + System.out.println(")"); + } + } else { + err = true; + System.err.print(" Failed: SimpleDateFormat(" + locale); + System.err.print(", \"" + pattern + "\").parse(\"" + given); + System.err.println("\")"); + + System.err.print(" Expected: " + expectedGC.getTime()); + System.err.println(" (" + d.getTime() + ")"); + + System.err.print(" Got: " + d + " (" + d.getTime()); + System.err.println(")"); + + System.err.print(" Pattern: \""); + System.err.print(((DecimalFormat)sdf.getNumberFormat()).toPattern()); + System.err.println("\""); + } + } + catch (ParseException pe) { + if (expectedGC == null) { + if (verbose) { + System.out.print(" Passed: SimpleDateFormat(" + locale); + System.out.print(", \"" + pattern + "\").parse(\"" + given); + System.out.println("\")"); + + System.out.println(" threw ParseException as expected"); + } + } else { + err = true; + System.err.println(" Failed: Unexpected exception with"); + + System.err.print(" SimpleDateFormat(" + locale); + System.err.print(", \"" + pattern + "\").parse(\""); + System.err.println(given + "\"):"); + + System.err.println(" " + pe); + + System.err.print(" Pattern: \""); + System.err.print(((DecimalFormat)sdf.getNumberFormat()).toPattern()); + System.err.println("\""); + + System.err.print(" Month 0: "); + System.err.println(sdf.getDateFormatSymbols().getMonths()[0]); + } + } + } + + + // + // NumberFormat test + // + private static void testNumberFormat() { + NumberFormat nfEG = NumberFormat.getInstance(localeEG); + NumberFormat nfUS = NumberFormat.getInstance(localeUS); + + System.out.println("*** DecimalFormat.format test in ar_EG"); + testNumberFormatFormatting(nfEG, -123456789, "123,456,789-", "ar_EG"); + testNumberFormatFormatting(nfEG, -456, "456-", "ar_EG"); + + System.out.println("*** DecimalFormat.parse test in ar_EG"); + testNumberFormatParsing(nfEG, "123-", new Long(-123), "ar_EG"); + testNumberFormatParsing(nfEG, "123--", new Long(-123), "ar_EG"); + testNumberFormatParsingCheckException(nfEG, "-123", 0, "ar_EG"); + + System.out.println("*** DecimalFormat.format test in en_US"); + testNumberFormatFormatting(nfUS, -123456789, "-123,456,789", "en_US"); + testNumberFormatFormatting(nfUS, -456, "-456", "en_US"); + + System.out.println("*** DecimalFormat.parse test in en_US"); + testNumberFormatParsing(nfUS, "123-", new Long(123), "en_US"); + testNumberFormatParsing(nfUS, "-123", new Long(-123), "en_US"); + testNumberFormatParsingCheckException(nfUS, "--123", 0, "en_US"); + } + + private static void testNumberFormatFormatting(NumberFormat nf, + int given, + String expected, + String locale) { + String str = nf.format(given); + if (expected.equals(str)) { + if (verbose) { + System.out.print(" Passed: NumberFormat(" + locale); + System.out.println(").format(" + given + ")"); + + System.out.println(" ---> \"" + str + "\""); + } + } else { + err = true; + System.err.print(" Failed: Unexpected NumberFormat(" + locale); + System.err.println(").format(" + given + ") result."); + + System.err.println(" Expected: \"" + expected + "\""); + + System.err.println(" Got: \"" + str + "\""); + } + } + + private static void testNumberFormatParsing(NumberFormat nf, + String given, + Number expected, + String locale) { + try { + Number n = nf.parse(given); + if (n.equals(expected)) { + if (verbose) { + System.out.print(" Passed: NumberFormat(" + locale); + System.out.println(").parse(\"" + given + "\")"); + + System.out.println(" ---> " + n); + } + } else { + err = true; + System.err.print(" Failed: Unexpected NumberFormat(" + locale); + System.err.println(").parse(\"" + given + "\") result."); + + System.err.println(" Expected: " + expected); + + System.err.println(" Got: " + n); + } + } + catch (ParseException pe) { + err = true; + System.err.print(" Failed: Unexpected exception with NumberFormat("); + System.err.println(locale + ").parse(\"" + given + "\") :"); + + System.err.println(" " + pe); + } + } + + private static void testNumberFormatParsingCheckException(NumberFormat nf, + String given, + int expected, + String locale) { + try { + Number n = nf.parse(given); + err = true; + + System.err.print(" Failed: NumberFormat(" + locale); + System.err.println(").parse(\"" + given + "\")"); + + System.err.println(" should have thrown ParseException"); + } + catch (ParseException pe) { + int errorOffset = pe.getErrorOffset(); + if (errorOffset == expected) { + if (verbose) { + System.out.print(" Passed: NumberFormat(" + locale); + System.out.println(").parse(\"" + given + "\")"); + + System.out.print(" threw ParseException as expected, and its errorOffset was correct: "); + System.out.println(errorOffset); + } + } else { + err = true; + System.err.print(" Failed: NumberFormat(" + locale); + System.err.println(").parse(\"" + given + "\")"); + + System.err.print(" threw ParseException as expected, but its errorOffset was incorrect: "); + System.err.println(errorOffset); + } + } + } + +} From f7ea37f1b9a411481ee58b6d59c5774dbf9e907e Mon Sep 17 00:00:00 2001 From: Yuka Kamiya Date: Mon, 8 Sep 2008 14:48:14 +0900 Subject: [PATCH 42/45] 6650748: (tz) Java runtime doesn't detect VET time zone correctly on Windows Reviewed-by: okutsu --- jdk/src/windows/lib/tzmappings | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jdk/src/windows/lib/tzmappings b/jdk/src/windows/lib/tzmappings index 998ff075409..a45200b7596 100644 --- a/jdk/src/windows/lib/tzmappings +++ b/jdk/src/windows/lib/tzmappings @@ -65,8 +65,8 @@ Newfoundland:-1,81::America/St_Johns: Newfoundland Standard Time:-1,81::America/St_Johns: Pacific SA:-1,82::America/Santiago: Pacific SA Standard Time:-1,82::America/Santiago: -SA Western:-1,82::America/Caracas: -SA Western Standard Time:-1,82::America/Caracas: +SA Western:-1,82:BO:America/La_Paz: +SA Western Standard Time:-1,82:BO:America/La_Paz: SA Pacific:-1,83::America/Bogota: SA Pacific Standard Time:-1,83::America/Bogota: US Eastern:-1,84::America/Indianapolis: @@ -177,3 +177,4 @@ Jordan Standard Time:908,908:JO:Asia/Amman: Middle East Standard Time:909,909:LB:Asia/Beirut: Armenian Standard Time:910,910:AM:Asia/Yerevan: Montevideo Standard Time:911,911:UY:America/Montevideo: +Venezuela Standard Time:912,912::America/Caracas: From c8b641166143392746f85295899593f4fb200c66 Mon Sep 17 00:00:00 2001 From: Yuka Kamiya Date: Mon, 8 Sep 2008 15:21:55 +0900 Subject: [PATCH 43/45] 6466476: (tz) Introduction of tzdata2005r can introduce incompatility issues with some JDK1.1 3-letter TZ Ids Reviewed-by: okutsu --- jdk/make/java/java/FILES_java.gmk | 1 + .../sun/util/calendar/TzIDOldMapping.java | 68 +++++++++++ .../classes/sun/util/calendar/ZoneInfo.java | 30 ++++- .../java/util/TimeZone/OldIDMappingTest.java | 110 ++++++++++++++++++ .../java/util/TimeZone/OldIDMappingTest.sh | 59 ++++++++++ 5 files changed, 266 insertions(+), 2 deletions(-) create mode 100644 jdk/src/share/classes/sun/util/calendar/TzIDOldMapping.java create mode 100644 jdk/test/java/util/TimeZone/OldIDMappingTest.java create mode 100644 jdk/test/java/util/TimeZone/OldIDMappingTest.sh diff --git a/jdk/make/java/java/FILES_java.gmk b/jdk/make/java/java/FILES_java.gmk index b4a07fc352f..18b1d35115d 100644 --- a/jdk/make/java/java/FILES_java.gmk +++ b/jdk/make/java/java/FILES_java.gmk @@ -209,6 +209,7 @@ JAVA_JAVA_java = \ sun/util/TimeZoneNameUtility.java \ sun/util/calendar/ZoneInfo.java \ sun/util/calendar/ZoneInfoFile.java \ + sun/util/calendar/TzIDOldMapping.java \ java/util/TooManyListenersException.java \ java/util/Comparator.java \ java/util/Collections.java \ diff --git a/jdk/src/share/classes/sun/util/calendar/TzIDOldMapping.java b/jdk/src/share/classes/sun/util/calendar/TzIDOldMapping.java new file mode 100644 index 00000000000..1e3c6caa7a2 --- /dev/null +++ b/jdk/src/share/classes/sun/util/calendar/TzIDOldMapping.java @@ -0,0 +1,68 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package sun.util.calendar; + +import java.util.Map; +import java.util.HashMap; + +class TzIDOldMapping { + static final Map MAP = new HashMap(); + static { + String[][] oldmap = { + { "ACT", "Australia/Darwin" }, + { "AET", "Australia/Sydney" }, + { "AGT", "America/Argentina/Buenos_Aires" }, + { "ART", "Africa/Cairo" }, + { "AST", "America/Anchorage" }, + { "BET", "America/Sao_Paulo" }, + { "BST", "Asia/Dhaka" }, + { "CAT", "Africa/Harare" }, + { "CNT", "America/St_Johns" }, + { "CST", "America/Chicago" }, + { "CTT", "Asia/Shanghai" }, + { "EAT", "Africa/Addis_Ababa" }, + { "ECT", "Europe/Paris" }, + { "EST", "America/New_York" }, + { "HST", "Pacific/Honolulu" }, + { "IET", "America/Indianapolis" }, + { "IST", "Asia/Calcutta" }, + { "JST", "Asia/Tokyo" }, + { "MIT", "Pacific/Apia" }, + { "MST", "America/Denver" }, + { "NET", "Asia/Yerevan" }, + { "NST", "Pacific/Auckland" }, + { "PLT", "Asia/Karachi" }, + { "PNT", "America/Phoenix" }, + { "PRT", "America/Puerto_Rico" }, + { "PST", "America/Los_Angeles" }, + { "SST", "Pacific/Guadalcanal" }, + { "VST", "Asia/Saigon" }, + }; + for (String[] pair : oldmap) { + MAP.put(pair[0], pair[1]); + } + } +} diff --git a/jdk/src/share/classes/sun/util/calendar/ZoneInfo.java b/jdk/src/share/classes/sun/util/calendar/ZoneInfo.java index 709ac38158e..cde5959e481 100644 --- a/jdk/src/share/classes/sun/util/calendar/ZoneInfo.java +++ b/jdk/src/share/classes/sun/util/calendar/ZoneInfo.java @@ -28,10 +28,12 @@ package sun.util.calendar; import java.io.IOException; import java.io.ObjectInputStream; import java.lang.ref.SoftReference; +import java.security.AccessController; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.SimpleTimeZone; import java.util.TimeZone; @@ -77,6 +79,14 @@ public class ZoneInfo extends TimeZone { private static final long ABBR_MASK = 0xf00L; private static final int TRANSITION_NSHIFT = 12; + // Flag for supporting JDK backward compatible IDs, such as "EST". + private static final boolean USE_OLDMAPPING; + static { + String oldmapping = AccessController.doPrivileged( + new sun.security.action.GetPropertyAction("sun.timezone.ids.oldmapping", "false")).toLowerCase(Locale.ROOT); + USE_OLDMAPPING = (oldmapping.equals("yes") || oldmapping.equals("true")); + } + private static final CalendarSystem gcal = CalendarSystem.getGregorianCalendar(); /** @@ -595,9 +605,21 @@ public class ZoneInfo extends TimeZone { * time zone of the ID. */ public static TimeZone getTimeZone(String ID) { - ZoneInfo zi = null; + String givenID = null; - zi = ZoneInfoFile.getZoneInfo(ID); + /* + * If old JDK compatibility is specified, get the old alias + * name. + */ + if (USE_OLDMAPPING) { + String compatibleID = TzIDOldMapping.MAP.get(ID); + if (compatibleID != null) { + givenID = ID; + ID = compatibleID; + } + } + + ZoneInfo zi = ZoneInfoFile.getZoneInfo(ID); if (zi == null) { // if we can't create an object for the ID, try aliases. try { @@ -616,6 +638,10 @@ public class ZoneInfo extends TimeZone { // ignore exceptions } } + + if (givenID != null && zi != null) { + zi.setID(givenID); + } return zi; } diff --git a/jdk/test/java/util/TimeZone/OldIDMappingTest.java b/jdk/test/java/util/TimeZone/OldIDMappingTest.java new file mode 100644 index 00000000000..90752b34270 --- /dev/null +++ b/jdk/test/java/util/TimeZone/OldIDMappingTest.java @@ -0,0 +1,110 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * See OldMappingTest.sh + */ + +import java.lang.reflect.*; +import java.util.*; + +public class OldIDMappingTest { + private static final String MAPPING_PROPERTY_NAME = "sun.timezone.ids.oldmapping"; + private static final Map newmap = new HashMap(); + static { + // Add known new mappings + newmap.put("EST", "EST"); + newmap.put("MST", "MST"); + newmap.put("HST", "HST"); + } + + public static void main(String[] args) { + boolean useOldMapping = true; + String arg = args[0]; + if (arg.equals("-new")) { + useOldMapping = false; + } else if (arg.equals("-old")) { + useOldMapping = true; + } else { + throw new RuntimeException("-old or -new must be specified; got " + arg); + } + + // Get a Field for TzIDOldMapping in sun.util.calendar. + Map oldmap = null; + try { + Class oldmapClass = Class.forName("sun.util.calendar.TzIDOldMapping"); + Field map = oldmapClass.getDeclaredField("MAP"); + map.setAccessible(true); + oldmap = (Map) map.get(null); + } catch (Exception e) { + throw new RuntimeException("can't get TzIDOldMapping.MAP", e); + } + + String prop = System.getProperty(MAPPING_PROPERTY_NAME); + System.out.println(MAPPING_PROPERTY_NAME + "=" + prop); + + // Try the test multiple times with modifying TimeZones to + // make sure TimeZone instances for the old mapping are + // properly copied (defensive copy). + for (int count = 0; count < 3; count++) { + for (String id : oldmap.keySet()) { + TimeZone tzAlias = TimeZone.getTimeZone(id); + TimeZone tz = TimeZone.getTimeZone(oldmap.get(id)); + if (useOldMapping) { + if (!tzAlias.hasSameRules(tz)) { + throw new RuntimeException("OLDMAP: " + MAPPING_PROPERTY_NAME + "=" + prop + ": " + + id + " isn't an alias of " + oldmap.get(id)); + } + if (count == 0) { + System.out.println(" " + id + " => " + oldmap.get(id)); + } + tzAlias.setRawOffset(tzAlias.getRawOffset() * count); + } else { + if (!newmap.containsKey(id)) { + // ignore ids not contained in the new map + if (count == 0) { + System.out.println(" " + id + " => " + oldmap.get(id)); + } + tzAlias.setRawOffset(tzAlias.getRawOffset() * count); + continue; + } + if (tzAlias.hasSameRules(tz)) { + throw new RuntimeException("NEWMAP: " + MAPPING_PROPERTY_NAME + "=" + prop + ": " + + id + " is an alias of " + oldmap.get(id)); + } + tz = TimeZone.getTimeZone(newmap.get(id)); + if (!tzAlias.hasSameRules(tz)) { + throw new RuntimeException("NEWMAP: " + MAPPING_PROPERTY_NAME + "=" + prop + ": " + + id + " isn't an alias of " + newmap.get(id)); + } + if (count == 0) { + System.out.println(" " + id + " => " + newmap.get(id)); + } + tzAlias.setRawOffset(tzAlias.getRawOffset() * count); + } + } + } + } +} diff --git a/jdk/test/java/util/TimeZone/OldIDMappingTest.sh b/jdk/test/java/util/TimeZone/OldIDMappingTest.sh new file mode 100644 index 00000000000..156d4f60ab5 --- /dev/null +++ b/jdk/test/java/util/TimeZone/OldIDMappingTest.sh @@ -0,0 +1,59 @@ +# Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Sun designates this +# particular file as subject to the "Classpath" exception as provided +# by Sun in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. + +# @test +# @bug 6466476 +# @summary Compatibility test for the old JDK ID mapping and Olson IDs +# @build OldIDMappingTest +# @run shell OldIDMappingTest.sh + +: ${TESTJAVA:=${JAVA_HOME}} +: ${TESTCLASSES:="`pwd`"} + +JAVA="${TESTJAVA}/bin/java" + +STATUS=0 + +# Expecting the new (Olson compatible) mapping (default) +for I in "" " " no No NO false False FALSE Hello +do + if [ x"$I" != x ]; then + D="-Dsun.timezone.ids.oldmapping=${I}" + fi + if ! ${JAVA} ${D} -cp ${TESTCLASSES} OldIDMappingTest -new; then + STATUS=1 + fi +done + +# Expecting the old mapping +for I in true True TRUE yes Yes YES +do + if [ "x$I" != x ]; then + D="-Dsun.timezone.ids.oldmapping=${I}" + fi + if ! ${JAVA} ${D} -cp ${TESTCLASSES} OldIDMappingTest -old; then + STATUS=1 + fi +done + +exit ${STATUS} From 54e427219cca41c60f5754c3082edfda60808284 Mon Sep 17 00:00:00 2001 From: Yuka Kamiya Date: Mon, 8 Sep 2008 17:35:07 +0900 Subject: [PATCH 44/45] 6730743: (tz) Support tzdata2008e Reviewed-by: okutsu --- jdk/make/sun/javazic/tzdata/VERSION | 2 +- jdk/make/sun/javazic/tzdata/africa | 131 ++++++++- jdk/make/sun/javazic/tzdata/asia | 185 ++++++++++++- jdk/make/sun/javazic/tzdata/australasia | 4 +- jdk/make/sun/javazic/tzdata/backward | 3 + jdk/make/sun/javazic/tzdata/europe | 75 ++++- jdk/make/sun/javazic/tzdata/iso3166.tab | 4 +- jdk/make/sun/javazic/tzdata/leapseconds | 32 ++- jdk/make/sun/javazic/tzdata/northamerica | 77 +++++- jdk/make/sun/javazic/tzdata/southamerica | 260 +++++++++++++++--- jdk/make/sun/javazic/tzdata/zone.tab | 15 +- .../sun/util/resources/TimeZoneNames.java | 14 +- .../sun/util/resources/TimeZoneNames_de.java | 14 +- .../sun/util/resources/TimeZoneNames_es.java | 14 +- .../sun/util/resources/TimeZoneNames_fr.java | 14 +- .../sun/util/resources/TimeZoneNames_it.java | 14 +- .../sun/util/resources/TimeZoneNames_ja.java | 14 +- .../sun/util/resources/TimeZoneNames_ko.java | 14 +- .../sun/util/resources/TimeZoneNames_sv.java | 14 +- .../util/resources/TimeZoneNames_zh_CN.java | 14 +- .../util/resources/TimeZoneNames_zh_TW.java | 14 +- 21 files changed, 794 insertions(+), 134 deletions(-) diff --git a/jdk/make/sun/javazic/tzdata/VERSION b/jdk/make/sun/javazic/tzdata/VERSION index 95ed6ee539e..2f4f9df808f 100644 --- a/jdk/make/sun/javazic/tzdata/VERSION +++ b/jdk/make/sun/javazic/tzdata/VERSION @@ -21,4 +21,4 @@ # CA 95054 USA or visit www.sun.com if you need additional information or # have any questions. # -tzdata2007h +tzdata2008e diff --git a/jdk/make/sun/javazic/tzdata/africa b/jdk/make/sun/javazic/tzdata/africa index f1f4b5f1b7a..8141f080997 100644 --- a/jdk/make/sun/javazic/tzdata/africa +++ b/jdk/make/sun/javazic/tzdata/africa @@ -409,9 +409,63 @@ Zone Africa/Nouakchott -1:03:48 - LMT 1912 0:00 - GMT # Mauritius + +# From Steffen Thorsen (2008-06-25): +# Mauritius plans to observe DST from 2008-11-01 to 2009-03-31 on a trial +# basis.... +# It seems that Mauritius observed daylight saving time from 1982-10-10 to +# 1983-03-20 as well, but that was not successful.... +# http://www.timeanddate.com/news/time/mauritius-daylight-saving-time.html + +# From Alex Krivenyshev (2008-06-25): +# http://economicdevelopment.gov.mu/portal/site/Mainhomepage/menuitem.a42b24128104d9845dabddd154508a0c/?content_id=0a7cee8b5d69a110VgnVCM1000000a04a8c0RCRD + +# From Arthur David Olson (2008-06-30): +# The www.timeanddate.com article cited by Steffen Thorsen notes that "A +# final decision has yet to be made on the times that daylight saving +# would begin and end on these dates." As a place holder, use midnight. + +# From Paul Eggert (2008-06-30): +# Follow Thorsen on DST in 1982/1983, instead of Shanks & Pottenger. + +# From Steffen Thorsen (2008-07-10): +# According to +# +# http://www.lexpress.mu/display_article.php?news_id=111216 +# +# (in French), Mauritius will start and end their DST a few days earlier +# than previously announced (2008-11-01 to 2009-03-31). The new start +# date is 2008-10-26 at 02:00 and the new end date is 2009-03-27 (no time +# given, but it is probably at either 2 or 3 wall clock time). +# +# A little strange though, since the article says that they moved the date +# to align itself with Europe and USA which also change time on that date, +# but that means they have not paid attention to what happened in +# USA/Canada last year (DST ends first Sunday in November). I also wonder +# why that they end on a Friday, instead of aligning with Europe which +# changes two days later. + +# From Alex Krivenyshev (2008-07-11): +# Seems that English language article "The revival of daylight saving +# time: Energy conservation?"-# No. 16578 (07/11/2008) was originally +# published on Monday, June 30, 2008... +# +# I guess that article in French "Le gouvernement avance l'introduction +# de l'heure d'ete" stating that DST in Mauritius starting on October 26 +# and ending on March 27, 2009 is the most recent one. +# ... +# +# http://www.worldtimezone.com/dst_news/dst_news_mauritius02.html +# + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Mauritius 1982 only - Oct 10 0:00 1:00 S +Rule Mauritius 1983 only - Mar 21 0:00 0 - +Rule Mauritius 2008 only - Oct 26 2:00s 1:00 S +Rule Mauritius 2009 only - Mar 27 2:00s 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Indian/Mauritius 3:50:00 - LMT 1907 # Port Louis - 4:00 - MUT # Mauritius Time + 4:00 Mauritius MU%sT # Mauritius Time # Agalega Is, Rodriguez # no information; probably like Indian/Mauritius @@ -422,6 +476,77 @@ Zone Indian/Mayotte 3:00:56 - LMT 1911 Jul # Mamoutzou # Morocco # See the `europe' file for Spanish Morocco (Africa/Ceuta). + +# From Alex Krivenyshev (2008-05-09): +# Here is an article that Morocco plan to introduce Daylight Saving Time between +# 1 June, 2008 and 27 September, 2008. +# +# "... Morocco is to save energy by adjusting its clock during summer so it will +# be one hour ahead of GMT between 1 June and 27 September, according to +# Communication Minister and Gov ernment Spokesman, Khalid Naciri...." +# +# +# http://www.worldtimezone.net/dst_news/dst_news_morocco01.html +# +# OR +# +# http://en.afrik.com/news11892.html +# + +# From Alex Krivenyshev (2008-05-09): +# The Morocco time change can be confirmed on Morocco web site Maghreb Arabe Presse: +# +# http://www.map.ma/eng/sections/box3/morocco_shifts_to_da/view +# +# +# Morocco shifts to daylight time on June 1st through September 27, Govt. +# spokesman. + +# From Patrice Scattolin (2008-05-09): +# According to this article: +# +# http://www.avmaroc.com/actualite/heure-dete-comment-a127896.html +# +# (and republished here: +# +# http://www.actu.ma/heure-dete-comment_i127896_0.html +# +# ) +# the changes occurs at midnight: +# +# saturday night may 31st at midnight (which in french is to be +# intrepreted as the night between saturday and sunday) +# sunday night the 28th at midnight +# +# Seeing that the 28th is monday, I am guessing that she intends to say +# the midnight of the 28th which is the midnight between sunday and +# monday, which jives with other sources that say that it's inclusive +# june1st to sept 27th. +# +# The decision was taken by decree *2-08-224 *but I can't find the decree +# published on the web. +# +# It's also confirmed here: +# +# http://www.maroc.ma/NR/exeres/FACF141F-D910-44B0-B7FA-6E03733425D1.htm +# +# on a government portal as being between june 1st and sept 27th (not yet +# posted in english). +# +# The following google query will generate many relevant hits: +# +# http://www.google.com/search?hl=en&q=Conseil+de+gouvernement+maroc+heure+avance&btnG=Search +# + +# From Alex Krivenyshev (2008-05-09): +# Is Western Sahara (part which administrated by Morocco) going to follow +# Morocco DST changes? Any information? What about other part of +# Western Sahara - under administration of POLISARIO Front (also named +# SADR Saharawi Arab Democratic Republic)? + +# From Arthur David Olson (2008-05-09): +# XXX--guess that it is only Morocco for now; guess only 2008 for now. + # RULE NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Morocco 1939 only - Sep 12 0:00 1:00 S Rule Morocco 1939 only - Nov 19 0:00 0 - @@ -438,11 +563,13 @@ Rule Morocco 1976 only - Aug 1 0:00 0 - Rule Morocco 1977 only - Sep 28 0:00 0 - Rule Morocco 1978 only - Jun 1 0:00 1:00 S Rule Morocco 1978 only - Aug 4 0:00 0 - +Rule Morocco 2008 only - Jun 1 0:00 1:00 S +Rule Morocco 2008 only - Sep 28 0:00 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 1:00 - CET 1986 - 0:00 - WET + 0:00 Morocco WE%sT # Western Sahara Zone Africa/El_Aaiun -0:52:48 - LMT 1934 Jan -1:00 - WAT 1976 Apr 14 diff --git a/jdk/make/sun/javazic/tzdata/asia b/jdk/make/sun/javazic/tzdata/asia index bec343b7796..be581970001 100644 --- a/jdk/make/sun/javazic/tzdata/asia +++ b/jdk/make/sun/javazic/tzdata/asia @@ -251,6 +251,28 @@ Rule PRC 1987 1991 - Apr Sun>=10 0:00 1:00 D # (could be true), for the moment I am assuming that those two # counties are mistakes in the astro.com data. +# From Paul Eggert (2008-02-11): +# I just now checked Google News for western news sources that talk +# about China's single time zone, and couldn't find anything before 1986 +# talking about China being in one time zone. (That article was: Jim +# Mann, "A clumsy embrace for another western custom: China on daylight +# time--sort of", Los Angeles Times, 1986-05-05. By the way, this +# article confirms the tz database's data claiming that China began +# observing daylight saving time in 1986. +# +# From Thomas S. Mullaney (2008-02-11): +# I think you're combining two subjects that need to treated +# separately: daylight savings (which, you're correct, wasn't +# implemented until the 1980s) and the unified time zone centered near +# Beijing (which was implemented in 1949). Briefly, there was also a +# "Lhasa Time" in Tibet and "Urumqi Time" in Xinjiang. The first was +# ceased, and the second eventually recognized (again, in the 1980s). +# +# From Paul Eggert (2008-06-30): +# There seems to be a good chance China switched to a single time zone in 1949 +# rather than in 1980 as Shanks & Pottenger have it, but we don't have a +# reliable documentary source saying so yet, so for now we still go with +# Shanks & Pottenger. # Zone NAME GMTOFF RULES FORMAT [UNTIL] # Changbai Time ("Long-white Time", Long-white = Heilongjiang area) @@ -468,13 +490,13 @@ Zone Asia/Dili 8:22:20 - LMT 1912 # India # Zone NAME GMTOFF RULES FORMAT [UNTIL] -Zone Asia/Calcutta 5:53:28 - LMT 1880 # Kolkata +Zone Asia/Kolkata 5:53:28 - LMT 1880 # Kolkata 5:53:20 - HMT 1941 Oct # Howrah Mean Time? 6:30 - BURT 1942 May 15 # Burma Time 5:30 - IST 1942 Sep 5:30 1:00 IST 1945 Oct 15 5:30 - IST -# The following are like Asia/Calcutta: +# The following are like Asia/Kolkata: # Andaman Is # Lakshadweep (Laccadive, Minicoy and Amindivi Is) # Nicobar Is @@ -599,6 +621,15 @@ Zone Asia/Jayapura 9:22:48 - LMT 1932 Nov # daylight saving time ... # http://uk.reuters.com/article/oilRpt/idUKBLA65048420070916 # +# From Roozbeh Pournader (2007-11-05): +# This is quoted from Official Gazette of the Islamic Republic of +# Iran, Volume 63, Number 18242, dated Tuesday 1386/6/24 +# [2007-10-16]. I am doing the best translation I can:... +# The official time of the country will be moved forward for one hour +# on the 24 hours of the first day of the month of Farvardin and will +# be changed back to its previous state on the 24 hours of the +# thirtieth day of Shahrivar. +# # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Iran 1978 1980 - Mar 21 0:00 1:00 D Rule Iran 1978 only - Oct 21 0:00 0 S @@ -673,6 +704,21 @@ Zone Asia/Tehran 3:25:44 - LMT 1916 # # So we'll ignore the Economist's claim. +# From Steffen Thorsen (2008-03-10): +# The cabinet in Iraq abolished DST last week, according to the following +# news sources (in Arabic): +# +# http://www.aljeeran.net/wesima_articles/news-20080305-98602.html +# +# +# http://www.aswataliraq.info/look/article.tpl?id=2047&IdLanguage=17&IdPublication=4&NrArticle=71743&NrIssue=1&NrSection=10 +# +# +# We have published a short article in English about the change: +# +# http://www.timeanddate.com/news/time/iraq-dumps-daylight-saving.html +# + # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Iraq 1982 only - May 1 0:00 1:00 D Rule Iraq 1982 1984 - Oct 1 0:00 0 S @@ -683,8 +729,8 @@ Rule Iraq 1986 1990 - Mar lastSun 1:00s 1:00 D # IATA SSIM (1991/1996) says Apr 1 12:01am UTC; guess the `:01' is a typo. # Shanks & Pottenger say Iraq did not observe DST 1992/1997; ignore this. # -Rule Iraq 1991 max - Apr 1 3:00s 1:00 D -Rule Iraq 1991 max - Oct 1 3:00s 0 S +Rule Iraq 1991 2007 - Apr 1 3:00s 1:00 D +Rule Iraq 1991 2007 - Oct 1 3:00s 0 S # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Asia/Baghdad 2:57:40 - LMT 1890 2:57:36 - BMT 1918 # Baghdad Mean Time? @@ -1374,6 +1420,42 @@ Zone Indian/Maldives 4:54:00 - LMT 1880 # Male # They decided not to adopt daylight-saving time.... # http://www.mongolnews.mn/index.php?module=unuudur&sec=view&id=15742 +# From Deborah Goldsmith (2008-03-30): +# We received a bug report claiming that the tz database UTC offset for +# Asia/Choibalsan (GMT+09:00) is incorrect, and that it should be GMT +# +08:00 instead. Different sources appear to disagree with the tz +# database on this, e.g.: +# +# +# http://www.timeanddate.com/worldclock/city.html?n=1026 +# +# +# http://www.worldtimeserver.com/current_time_in_MN.aspx +# +# +# both say GMT+08:00. + +# From Steffen Thorsen (2008-03-31): +# eznis airways, which operates several domestic flights, has a flight +# schedule here: +# +# http://www.eznis.com/Container.jsp?id=112 +# +# (click the English flag for English) +# +# There it appears that flights between Choibalsan and Ulaanbatar arrive +# about 1:35 - 1:50 hours later in local clock time, no matter the +# direction, while Ulaanbaatar-Khvod takes 2 hours in the Eastern +# direction and 3:35 back, which indicates that Ulaanbatar and Khvod are +# in different time zones (like we know about), while Choibalsan and +# Ulaanbatar are in the same time zone (correction needed). + +# From Arthur David Olson (2008-05-19): +# Assume that Choibalsan is indeed offset by 8:00. +# XXX--in the absence of better information, assume that transition +# was at the start of 2008-03-31 (the day of Steffen Thorsen's report); +# this is almost surely wrong. + # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Mongol 1983 1984 - Apr 1 0:00 1:00 S Rule Mongol 1983 only - Oct 1 0:00 0 - @@ -1409,7 +1491,8 @@ Zone Asia/Ulaanbaatar 7:07:32 - LMT 1905 Aug Zone Asia/Choibalsan 7:38:00 - LMT 1905 Aug 7:00 - ULAT 1978 8:00 - ULAT 1983 Apr - 9:00 Mongol CHO%sT # Choibalsan Time + 9:00 Mongol CHO%sT 2008 Mar 31 # Choibalsan Time + 8:00 Mongol CHO%sT # Nepal # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -1459,10 +1542,32 @@ Zone Asia/Muscat 3:54:20 - LMT 1920 # The minister told a news conference that the experiment had rather # shown 8 per cent higher consumption of electricity. +# From Alex Krivenyshev (2008-05-15): +# +# Here is an article that Pakistan plan to introduce Daylight Saving Time +# on June 1, 2008 for 3 months. +# +# "... The federal cabinet on Wednesday announced a new conservation plan to help +# reduce load shedding by approving the closure of commercial centres at 9pm and +# moving clocks forward by one hour for the next three months. +# ...." +# +# +# http://www.worldtimezone.net/dst_news/dst_news_pakistan01.html +# +# OR +# +# http://www.dailytimes.com.pk/default.asp?page=2008%5C05%5C15%5Cstory_15-5-2008_pg1_4 +# + +# From Arthur David Olson (2008-05-19): +# XXX--midnight transitions is a guess; 2008 only is a guess. # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Pakistan 2002 only - Apr Sun>=2 0:01 1:00 S Rule Pakistan 2002 only - Oct Sun>=2 0:01 0 - +Rule Pakistan 2008 only - Jun 1 0:00 1:00 S +Rule Pakistan 2008 only - Sep 1 0:00 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Asia/Karachi 4:28:12 - LMT 1907 5:30 - IST 1942 Sep @@ -1700,7 +1805,7 @@ Zone Asia/Singapore 6:55:25 - LMT 1901 Jan 1 # kept their clocks set five and a half hours ahead of Greenwich Mean # Time (GMT), in line with neighbor India. # From Paul Eggert (2006-04-18): -# People who live in regions under Tamil control can use TZ='Asia/Calcutta', +# People who live in regions under Tamil control can use [TZ='Asia/Kolkata'], # as that zone has agreed with the Tamil areas since our cutoff date of 1970. # From K Sethu (2006-04-25): @@ -1790,10 +1895,62 @@ Rule Syria 2006 only - Sep 22 0:00 0 - # From Paul Eggert (2007-03-29): # Today the AP reported "Syria will switch to summertime at midnight Thursday." # http://www.iht.com/articles/ap/2007/03/29/africa/ME-GEN-Syria-Time-Change.php -# For lack of better info, assume the rule changed to "last Friday in March" -# this year. -Rule Syria 2007 max - Mar lastFri 0:00 1:00 S -Rule Syria 2007 max - Oct 1 0:00 0 - +Rule Syria 2007 only - Mar lastFri 0:00 1:00 S +# From Jesper Norgard (2007-10-27): +# The sister center ICARDA of my work CIMMYT is confirming that Syria DST will +# not take place 1.st November at 0:00 o'clock but 1.st November at 24:00 or +# rather Midnight between Thursday and Friday. This does make more sence than +# having it between Wednesday and Thursday (two workdays in Syria) since the +# weekend in Syria is not Saturday and Sunday, but Friday and Saturday. So now +# it is implemented at midnight of the last workday before weekend... +# +# From Steffen Thorsen (2007-10-27): +# Jesper Norgaard Welen wrote: +# +# > "Winter local time in Syria will be observed at midnight of Thursday 1 +# > November 2007, and the clock will be put back 1 hour." +# +# I found confirmation on this in this gov.sy-article (Arabic): +# http://wehda.alwehda.gov.sy/_print_veiw.asp?FileName=12521710520070926111247 +# +# which using Google's translate tools says: +# Council of Ministers also approved the commencement of work on +# identifying the winter time as of Friday, 2/11/2007 where the 60th +# minute delay at midnight Thursday 1/11/2007. +Rule Syria 2007 only - Nov Fri>=1 0:00 0 - + +# From Stephen Colebourne (2008-03-17): +# For everyone's info, I saw an IATA time zone change for [Syria] for +# this month (March 2008) in the last day or so...This is the data IATA +# are now using: +# Country Time Standard --- DST Start --- --- DST End --- DST +# Name Zone Variation Time Date Time Date +# Variation +# Syrian Arab +# Republic SY +0200 2200 03APR08 2100 30SEP08 +0300 +# 2200 02APR09 2100 30SEP09 +0300 +# 2200 01APR10 2100 30SEP10 +0300 + +# From Arthur David Olson (2008-03-17): +# Here's a link to English-language coverage by the Syrian Arab News +# Agency (SANA)... +# +# http://www.sana.sy/eng/21/2008/03/11/165173.htm +# ...which reads (in part) "The Cabinet approved the suggestion of the +# Ministry of Electricity to begin daylight savings time on Friday April +# 4th, advancing clocks one hour ahead on midnight of Thursday April 3rd." +# Since Syria is two hours east of UTC, the 2200 and 2100 transition times +# shown above match up with midnight in Syria. + +# From Arthur David Olson (2008-03-18): +# My buest guess at a Syrian rule is "the Friday nearest April 1"; +# coding that involves either using a "Mar Fri>=29" construct that old time zone +# compilers can't handle or having multiple Rules (a la Israel). +# For now, use "Apr Fri>=1", and go with IATA on a uniform Sep 30 end. + +Rule Syria 2008 max - Apr Fri>=1 0:00 1:00 S +Rule Syria 2008 max - Oct 1 0:00 0 - + # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Asia/Damascus 2:25:12 - LMT 1920 # Dimashq 2:00 Syria EE%sT @@ -1847,13 +2004,13 @@ Zone Asia/Tashkent 4:37:12 - LMT 1924 May 2 # Vietnam -# From Paul Eggert (1993-11-18): -# Saigon's official name is Thanh-Pho Ho Chi Minh, but it's too long. -# We'll stick with the traditional name for now. +# From Arthur David Olson (2008-03-18): +# The English-language name of Vietnam's most populous city is "Ho Chi Min City"; +# we use Ho_Chi_Minh below to avoid a name of more than 14 characters. # From Shanks & Pottenger: # Zone NAME GMTOFF RULES FORMAT [UNTIL] -Zone Asia/Saigon 7:06:40 - LMT 1906 Jun 9 +Zone Asia/Ho_Chi_Minh 7:06:40 - LMT 1906 Jun 9 7:06:20 - SMT 1911 Mar 11 0:01 # Saigon MT? 7:00 - ICT 1912 May 8:00 - ICT 1931 May diff --git a/jdk/make/sun/javazic/tzdata/australasia b/jdk/make/sun/javazic/tzdata/australasia index eee5c0b5478..823550415e0 100644 --- a/jdk/make/sun/javazic/tzdata/australasia +++ b/jdk/make/sun/javazic/tzdata/australasia @@ -1368,7 +1368,7 @@ Zone Pacific/Wallis 12:15:20 - LMT 1901 # * Tonga will introduce DST in November # # I was given this link by John Letts: -# +# # http://news.bbc.co.uk/hi/english/world/asia-pacific/newsid_424000/424764.stm # # @@ -1378,7 +1378,7 @@ Zone Pacific/Wallis 12:15:20 - LMT 1901 # (12 + 1 hour DST). # From Arthur David Olson (1999-09-20): -# According to # http://www.tongaonline.com/news/sept1799.html # : # "Daylight Savings Time will take effect on Oct. 2 through April 15, 2000 diff --git a/jdk/make/sun/javazic/tzdata/backward b/jdk/make/sun/javazic/tzdata/backward index 0e64882a465..85522740f41 100644 --- a/jdk/make/sun/javazic/tzdata/backward +++ b/jdk/make/sun/javazic/tzdata/backward @@ -46,12 +46,15 @@ Link America/St_Thomas America/Virgin Link Asia/Ashgabat Asia/Ashkhabad Link Asia/Chongqing Asia/Chungking Link Asia/Dhaka Asia/Dacca +Link Asia/Kolkata Asia/Calcutta Link Asia/Macau Asia/Macao Link Asia/Jerusalem Asia/Tel_Aviv +Link Asia/Ho_Chi_Minh Asia/Saigon Link Asia/Thimphu Asia/Thimbu Link Asia/Makassar Asia/Ujung_Pandang Link Asia/Ulaanbaatar Asia/Ulan_Bator Link Atlantic/Faroe Atlantic/Faeroe +Link Europe/Oslo Atlantic/Jan_Mayen Link Australia/Sydney Australia/ACT Link Australia/Sydney Australia/Canberra Link Australia/Lord_Howe Australia/LHI diff --git a/jdk/make/sun/javazic/tzdata/europe b/jdk/make/sun/javazic/tzdata/europe index 16fedf8036d..30724328383 100644 --- a/jdk/make/sun/javazic/tzdata/europe +++ b/jdk/make/sun/javazic/tzdata/europe @@ -479,7 +479,7 @@ Rule EU 1979 1995 - Sep lastSun 1:00u 0 - Rule EU 1981 max - Mar lastSun 1:00u 1:00 S Rule EU 1996 max - Oct lastSun 1:00u 0 - # The most recent directive covers the years starting in 2002. See: -# # Directive 2000/84/EC of the European Parliament and of the Council # of 19 January 2001 on summer-time arrangements. # @@ -502,9 +502,48 @@ Rule C-Eur 1940 only - Apr 1 2:00s 1:00 S Rule C-Eur 1942 only - Nov 2 2:00s 0 - Rule C-Eur 1943 only - Mar 29 2:00s 1:00 S Rule C-Eur 1943 only - Oct 4 2:00s 0 - -Rule C-Eur 1944 only - Apr 3 2:00s 1:00 S +Rule C-Eur 1944 1945 - Apr Mon>=1 2:00s 1:00 S # Whitman gives 1944 Oct 7; go with Shanks & Pottenger. Rule C-Eur 1944 only - Oct 2 2:00s 0 - +# From Jesper Norgaard Welen (2008-07-13): +# +# I found what is probably a typo of 2:00 which should perhaps be 2:00s +# in the C-Eur rule from tz database version 2008d (this part was +# corrected in version 2008d). The circumstancial evidence is simply the +# tz database itself, as seen below: +# +# Zone Europe/Paris 0:09:21 - LMT 1891 Mar 15 0:01 +# 0:00 France WE%sT 1945 Sep 16 3:00 +# +# Zone Europe/Monaco 0:29:32 - LMT 1891 Mar 15 +# 0:00 France WE%sT 1945 Sep 16 3:00 +# +# Zone Europe/Belgrade 1:22:00 - LMT 1884 +# 1:00 1:00 CEST 1945 Sep 16 2:00s +# +# Rule France 1945 only - Sep 16 3:00 0 - +# Rule Belgium 1945 only - Sep 16 2:00s 0 - +# Rule Neth 1945 only - Sep 16 2:00s 0 - +# +# The rule line to be changed is: +# +# Rule C-Eur 1945 only - Sep 16 2:00 0 - +# +# It seems that Paris, Monaco, Rule France, Rule Belgium all agree on +# 2:00 standard time, e.g. 3:00 local time. However there are no +# countries that use C-Eur rules in September 1945, so the only items +# affected are apparently these ficticious zones that translates acronyms +# CET and MET: +# +# Zone CET 1:00 C-Eur CE%sT +# Zone MET 1:00 C-Eur ME%sT +# +# It this is right then the corrected version would look like: +# +# Rule C-Eur 1945 only - Sep 16 2:00s 0 - +# +# A small step for mankind though 8-) +Rule C-Eur 1945 only - Sep 16 2:00s 0 - Rule C-Eur 1977 1980 - Apr Sun>=1 2:00s 1:00 S Rule C-Eur 1977 only - Sep lastSun 2:00s 0 - Rule C-Eur 1978 only - Oct 1 2:00s 0 - @@ -747,7 +786,8 @@ Rule Bulg 1981 only - Sep 27 2:00 0 - Zone Europe/Sofia 1:33:16 - LMT 1880 1:56:56 - IMT 1894 Nov 30 # Istanbul MT? 2:00 - EET 1942 Nov 2 3:00 - 1:00 C-Eur CE%sT 1945 Apr 2 3:00 + 1:00 C-Eur CE%sT 1945 + 1:00 - CET 1945 Apr 2 3:00 2:00 - EET 1979 Mar 31 23:00 2:00 Bulg EE%sT 1982 Sep 26 2:00 2:00 C-Eur EE%sT 1991 @@ -1115,33 +1155,40 @@ Zone Europe/Paris 0:09:21 - LMT 1891 Mar 15 0:01 # [See tz-link.htm for the URL.] # From Joerg Schilling (2002-10-23): -# In 1945, Berlin was switched to Moscow Summer time (GMT+4) by +# In 1945, Berlin was switched to Moscow Summer time (GMT+4) by +# # General [Nikolai] Bersarin. # From Paul Eggert (2003-03-08): # +# http://www.parlament-berlin.de/pds-fraktion.nsf/727459127c8b66ee8525662300459099/defc77cb784f180ac1256c2b0030274b/$FILE/bersarint.pdf +# # says that Bersarin issued an order to use Moscow time on May 20. # However, Moscow did not observe daylight saving in 1945, so # this was equivalent to CEMT (GMT+3), not GMT+4. # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S -Rule Germany 1945 only - Apr 2 2:00s 1:00 S -Rule Germany 1945 only - May 24 2:00 2:00 M # Midsummer -Rule Germany 1945 only - Sep 24 3:00 1:00 S -Rule Germany 1945 only - Nov 18 2:00s 0 - Rule Germany 1946 only - Apr 14 2:00s 1:00 S Rule Germany 1946 only - Oct 7 2:00s 0 - Rule Germany 1947 1949 - Oct Sun>=1 2:00s 0 - -Rule Germany 1947 only - Apr 6 2:00s 1:00 S +# http://www.ptb.de/de/org/4/44/441/salt.htm says the following transition +# occurred at 3:00 MEZ, not the 2:00 MEZ given in Shanks & Pottenger. +# Go with the PTB. +Rule Germany 1947 only - Apr 6 3:00s 1:00 S Rule Germany 1947 only - May 11 2:00s 2:00 M Rule Germany 1947 only - Jun 29 3:00 1:00 S Rule Germany 1948 only - Apr 18 2:00s 1:00 S Rule Germany 1949 only - Apr 10 2:00s 1:00 S + +Rule SovietZone 1945 only - May 24 2:00 2:00 M # Midsummer +Rule SovietZone 1945 only - Sep 24 3:00 1:00 S +Rule SovietZone 1945 only - Nov 18 2:00s 0 - + # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Europe/Berlin 0:53:28 - LMT 1893 Apr - 1:00 C-Eur CE%sT 1945 Apr 2 2:00 + 1:00 C-Eur CE%sT 1945 May 24 2:00 + 1:00 SovietZone CE%sT 1946 1:00 Germany CE%sT 1980 1:00 EU CE%sT @@ -1218,7 +1265,7 @@ Rule Hungary 1980 only - Apr 6 1:00 1:00 S Zone Europe/Budapest 1:16:20 - LMT 1890 Oct 1:00 C-Eur CE%sT 1918 1:00 Hungary CE%sT 1941 Apr 6 2:00 - 1:00 C-Eur CE%sT 1945 May 1 23:00 + 1:00 C-Eur CE%sT 1945 1:00 Hungary CE%sT 1980 Sep 28 2:00s 1:00 EU CE%sT @@ -1736,7 +1783,6 @@ Zone Europe/Oslo 0:43:00 - LMT 1895 Jan 1 # come up with more definitive info about the timekeeping during the # war years it's probably best just do do the following for now: Link Europe/Oslo Arctic/Longyearbyen -Link Europe/Oslo Atlantic/Jan_Mayen # Poland # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S @@ -2136,7 +2182,8 @@ Zone Asia/Anadyr 11:49:56 - LMT 1924 May 2 # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Europe/Belgrade 1:22:00 - LMT 1884 1:00 - CET 1941 Apr 18 23:00 - 1:00 C-Eur CE%sT 1945 May 8 2:00s + 1:00 C-Eur CE%sT 1945 + 1:00 - CET 1945 May 8 2:00s 1:00 1:00 CEST 1945 Sep 16 2:00s # Metod Kozelj reports that the legal date of # transition to EU rules was 1982-11-27, for all of Yugoslavia at the time. diff --git a/jdk/make/sun/javazic/tzdata/iso3166.tab b/jdk/make/sun/javazic/tzdata/iso3166.tab index d976eb1a1a6..6931ee04a71 100644 --- a/jdk/make/sun/javazic/tzdata/iso3166.tab +++ b/jdk/make/sun/javazic/tzdata/iso3166.tab @@ -28,7 +28,7 @@ # # This file contains a table with the following columns: # 1. ISO 3166-1 alpha-2 country code, current as of -# ISO 3166-1 Newsletter No. V-12 (2006-09-26). See: +# ISO 3166-1 Newsletter VI-1 (2007-09-21). See: # # ISO 3166 Maintenance agency (ISO 3166/MA) # . @@ -69,6 +69,7 @@ BG Bulgaria BH Bahrain BI Burundi BJ Benin +BL St Barthelemy BM Bermuda BN Brunei BO Bolivia @@ -181,6 +182,7 @@ MA Morocco MC Monaco MD Moldova ME Montenegro +MF St Martin (French part) MG Madagascar MH Marshall Islands MK Macedonia diff --git a/jdk/make/sun/javazic/tzdata/leapseconds b/jdk/make/sun/javazic/tzdata/leapseconds index 77d28dae9dd..4526cddf5b6 100644 --- a/jdk/make/sun/javazic/tzdata/leapseconds +++ b/jdk/make/sun/javazic/tzdata/leapseconds @@ -66,8 +66,10 @@ Leap 1995 Dec 31 23:59:60 + S Leap 1997 Jun 30 23:59:60 + S Leap 1998 Dec 31 23:59:60 + S Leap 2005 Dec 31 23:59:60 + S +Leap 2008 Dec 31 23:59:60 + S # INTERNATIONAL EARTH ROTATION AND REFERENCE SYSTEMS SERVICE (IERS) +# # SERVICE INTERNATIONAL DE LA ROTATION TERRESTRE ET DES SYSTEMES DE REFERENCE # # SERVICE DE LA ROTATION TERRESTRE @@ -75,30 +77,38 @@ Leap 2005 Dec 31 23:59:60 + S # 61, Av. de l'Observatoire 75014 PARIS (France) # Tel. : 33 (0) 1 40 51 22 26 # FAX : 33 (0) 1 40 51 22 91 -# Internet : services.iers@obspm.fr +# e-mail : services.iers@obspm.fr +# http://hpiers.obspm.fr/eop-pc # -# Paris, 28 June 2007 +# Paris, 4 July 2008 # -# Bulletin C 34 +# Bulletin C 36 # # To authorities responsible # for the measurement and # distribution of time # -# INFORMATION ON UTC - TAI +# UTC TIME STEP +# on the 1st of January 2009 # -# NO positive leap second will be introduced at the end of December 2007. -# The difference between Coordinated Universal Time UTC and the -# International Atomic Time TAI is : +# A positive leap second will be introduced at the end of December 2008. +# The sequence of dates of the UTC second markers will be: # -# from 2006 January 1, 0h UTC, until further notice : UTC-TAI = -33 s +# 2008 December 31, 23h 59m 59s +# 2008 December 31, 23h 59m 60s +# 2009 January 1, 0h 0m 0s +# +# The difference between UTC and the International Atomic Time TAI is: +# +# from 2006 January 1, 0h UTC, to 2009 January 1 0h UTC : UTC-TAI = - 33s +# from 2009 January 1, 0h UTC, until further notice : UTC-TAI = - 34s # # Leap seconds can be introduced in UTC at the end of the months of December -# or June, depending on the evolution of UT1-TAI. Bulletin C is mailed every -# six months, either to announce a time step in UTC, or to confirm that there +# or June, depending on the evolution of UT1-TAI. Bulletin C is mailed every +# six months, either to announce a time step in UTC or to confirm that there # will be no time step at the next possible date. # # Daniel GAMBIS -# Director +# Head # Earth Orientation Center of IERS # Observatoire de Paris, France diff --git a/jdk/make/sun/javazic/tzdata/northamerica b/jdk/make/sun/javazic/tzdata/northamerica index ab5bb5b2153..6e0317277b7 100644 --- a/jdk/make/sun/javazic/tzdata/northamerica +++ b/jdk/make/sun/javazic/tzdata/northamerica @@ -2098,8 +2098,8 @@ Zone America/Antigua -4:07:12 - LMT 1912 Mar 2 # http://www.jonesbahamas.com/?c=45&a=10412 # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S -Rule Bahamas 1964 2006 - Oct lastSun 2:00 0 S -Rule Bahamas 1964 1986 - Apr lastSun 2:00 1:00 D +Rule Bahamas 1964 1975 - Oct lastSun 2:00 0 S +Rule Bahamas 1964 1975 - Apr lastSun 2:00 1:00 D # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone America/Nassau -5:09:24 - LMT 1912 Mar 2 -5:00 Bahamas E%sT 1976 @@ -2209,6 +2209,69 @@ Zone America/Costa_Rica -5:36:20 - LMT 1890 # San Jose # says Cuban clocks will advance at midnight on March 10. # For lack of better information, assume Cuba will use US rules, # except that it switches at midnight standard time as usual. +# +# From Steffen Thorsen (2007-10-25): +# Carlos Alberto Fonseca Arauz informed me that Cuba will end DST one week +# earlier - on the last Sunday of October, just like in 2006. +# +# He supplied these references: +# +# http://www.prensalatina.com.mx/article.asp?ID=%7B4CC32C1B-A9F7-42FB-8A07-8631AFC923AF%7D&language=ES +# http://actualidad.terra.es/sociedad/articulo/cuba_llama_ahorrar_energia_cambio_1957044.htm +# +# From Alex Kryvenishev (2007-10-25): +# Here is also article from Granma (Cuba): +# +# [Regira] el Horario Normal desde el [proximo] domingo 28 de octubre +# http://www.granma.cubaweb.cu/2007/10/24/nacional/artic07.html +# +# http://www.worldtimezone.com/dst_news/dst_news_cuba03.html + +# From Arthur David Olson (2008-03-09): +# I'm in Maryland which is now observing United States Eastern Daylight +# Time. At 9:44 local time I used RealPlayer to listen to +# +# http://media.enet.cu/radioreloj +# , a Cuban information station, and heard +# the time announced as "ocho cuarenta y cuatro" ("eight forty-four"), +# indicating that Cuba is still on standard time. + +# From Steffen Thorsen (2008-03-12): +# It seems that Cuba will start DST on Sunday, 2007-03-16... +# It was announced yesterday, according to this source (in Spanish): +# +# http://www.nnc.cubaweb.cu/marzo-2008/cien-1-11-3-08.htm +# +# +# Some more background information is posted here: +# +# http://www.timeanddate.com/news/time/cuba-starts-dst-march-16.html +# +# +# The article also says that Cuba has been observing DST since 1963, +# while Shanks (and tzdata) has 1965 as the first date (except in the +# 1940's). Many other web pages in Cuba also claim that it has been +# observed since 1963, but with the exception of 1970 - an exception +# which is not present in tzdata/Shanks. So there is a chance we need to +# change some historic records as well. +# +# One example: +# +# http://www.radiohc.cu/espanol/noticias/mar07/11mar/hor.htm +# + +# From Jesper Norgaard Welen (2008-03-13): +# The Cuban time change has just been confirmed on the most authoritative +# web site, the Granma. Please check out +# +# http://www.granma.cubaweb.cu/2008/03/13/nacional/artic10.html +# +# +# Basically as expected after Steffen Thorsens information, the change +# will take place midnight between Saturday and Sunday. + +# From Arthur David Olson (2008-03-12): +# Assume Sun>=15 (third Sunday) going forward. # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Cuba 1928 only - Jun 10 0:00 1:00 D @@ -2240,9 +2303,9 @@ Rule Cuba 1997 only - Oct 12 0:00s 0 S Rule Cuba 1998 1999 - Mar lastSun 0:00s 1:00 D Rule Cuba 1998 2003 - Oct lastSun 0:00s 0 S Rule Cuba 2000 2006 - Apr Sun>=1 0:00s 1:00 D -Rule Cuba 2006 only - Oct lastSun 0:00s 0 S -Rule Cuba 2007 max - Mar Sun>=8 0:00s 1:00 D -Rule Cuba 2007 max - Nov Sun>=1 0:00s 0 S +Rule Cuba 2006 max - Oct lastSun 0:00s 0 S +Rule Cuba 2007 only - Mar Sun>=8 0:00s 1:00 D +Rule Cuba 2008 max - Mar Sun>=15 0:00s 1:00 D # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone America/Havana -5:29:28 - LMT 1890 @@ -2309,6 +2372,10 @@ Zone America/Grenada -4:07:00 - LMT 1911 Jul # St George's # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone America/Guadeloupe -4:06:08 - LMT 1911 Jun 8 # Pointe a Pitre -4:00 - AST +# St Barthelemy +Link America/Guadeloupe America/St_Barthelemy +# St Martin (French part) +Link America/Guadeloupe America/Marigot # Guatemala # diff --git a/jdk/make/sun/javazic/tzdata/southamerica b/jdk/make/sun/javazic/tzdata/southamerica index a147a1b0870..06a8d130e39 100644 --- a/jdk/make/sun/javazic/tzdata/southamerica +++ b/jdk/make/sun/javazic/tzdata/southamerica @@ -127,7 +127,11 @@ Rule Arg 1989 1992 - Oct Sun>=15 0:00 1:00 S # which did not result in the switch of a time zone, as they stayed 9 hours # from the International Date Line. Rule Arg 1999 only - Oct Sun>=1 0:00 1:00 S -Rule Arg 2000 only - Mar Sun>=1 0:00 0 - +# From Paul Eggert (2007-12-28): +# DST was set to expire on March 5, not March 3, but since it was converted +# to standard time on March 3 it's more convenient for us to pretend that +# it ended on March 3. +Rule Arg 2000 only - Mar 3 0:00 0 - # # From Peter Gradelski via Steffen Thorsen (2000-03-01): # We just checked with our Sao Paulo office and they say the government of @@ -162,6 +166,30 @@ Rule Arg 2000 only - Mar Sun>=1 0:00 0 - # This kind of things had always been done this way in Argentina. # We are still -03:00 all year round in all of the country. # +# From Steffen Thorsen (2007-12-21): +# A user (Leonardo Chaim) reported that Argentina will adopt DST.... +# all of the country (all Zone-entries) are affected. News reports like +# http://www.lanacion.com.ar/opinion/nota.asp?nota_id=973037 indicate +# that Argentina will use DST next year as well, from October to +# March, although exact rules are not given. +# +# From Jesper Norgaard Welen (2007-12-26) +# The last hurdle of Argentina DST is over, the proposal was approved in +# the lower chamber too (Deputados) with a vote 192 for and 2 against. +# By the way thanks to Mariano Absatz and Daniel Mario Vega for the link to +# the original scanned proposal, where the dates and the zero hours are +# clear and unambiguous...This is the article about final approval: +# +# http://www.lanacion.com.ar/politica/nota.asp?nota_id=973996 +# +# +# From Paul Eggert (2007-12-22): +# For dates after mid-2008, the following rules are my guesses and +# are quite possibly wrong, but are more likely than no DST at all. +Rule Arg 2007 only - Dec 30 0:00 1:00 S +Rule Arg 2008 max - Mar Sun>=15 0:00 0 - +Rule Arg 2008 max - Oct Sun>=1 0:00 1:00 S + # From Mariano Absatz (2004-05-21): # Today it was officially published that the Province of Mendoza is changing # its timezone this winter... starting tomorrow night.... @@ -222,10 +250,80 @@ Rule Arg 2000 only - Mar Sun>=1 0:00 0 - # http://www.sanjuan.gov.ar/prensa/archivo/000426.html # http://www.sanjuan.gov.ar/prensa/archivo/000441.html +# From Alex Krivenyshev (2008-01-17): +# Here are articles that Argentina Province San Luis is planning to end DST +# as earlier as upcoming Monday January 21, 2008 or February 2008: +# +# Provincia argentina retrasa reloj y marca diferencia con resto del pais +# (Argentine Province delayed clock and mark difference with the rest of the +# country) +# +# http://cl.invertia.com/noticias/noticia.aspx?idNoticia=200801171849_EFE_ET4373&idtel +# +# +# Es inminente que en San Luis atrasen una hora los relojes +# (It is imminent in San Luis clocks one hour delay) +# +# http://www.lagaceta.com.ar/vernotae.asp?id_nota=253414 +# +# +# +# http://www.worldtimezone.net/dst_news/dst_news_argentina02.html +# + +# From Jesper Norgaard Welen (2008-01-18): +# The page of the San Luis provincial government +# +# http://www.sanluis.gov.ar/notas.asp?idCanal=0&id=22812 +# +# confirms what Alex Krivenyshev has earlier sent to the tz +# emailing list about that San Luis plans to return to standard +# time much earlier than the rest of the country. It also +# confirms that upon request the provinces San Juan and Mendoza +# refused to follow San Luis in this change. +# +# The change is supposed to take place Monday the 21.st at 0:00 +# hours. As far as I understand it if this goes ahead, we need +# a new timezone for San Luis (although there are also documented +# independent changes in the southamerica file of San Luis in +# 1990 and 1991 which has not been confirmed). + +# From Jesper Norgaard Welen (2008-01-25): +# Unfortunately the below page has become defunct, about the San Luis +# time change. Perhaps because it now is part of a group of pages "Most +# important pages of 2008." +# +# You can use +# +# http://www.sanluis.gov.ar/notas.asp?idCanal=8141&id=22834 +# +# instead it seems. Or use "Buscador" from the main page of the San Luis +# government, and fill in "huso" and click OK, and you will get 3 pages +# from which the first one is identical to the above. + +# From Mariano Absatz (2008-01-28): +# I can confirm that the Province of San Luis (and so far only that +# province) decided to go back to UTC-3 effective midnight Jan 20th 2008 +# (that is, Monday 21st at 0:00 is the time the clocks were delayed back +# 1 hour), and they intend to keep UTC-3 as their timezone all year round +# (that is, unless they change their mind any minute now). +# +# So we'll have to add yet another city to 'southamerica' (I think San +# Luis city is the mos populated city in the Province, so it'd be +# America/Argentina/San_Luis... of course I can't remember if San Luis's +# history of particular changes goes along with Mendoza or San Juan :-( +# (I only remember not being able to collect hard facts about San Luis +# back in 2004, when these provinces changed to UTC-4 for a few days, I +# mailed them personally and never got an answer). + +# From Paul Eggert (2008-06-30): # Unless otherwise specified, data are from Shanks & Pottenger through 1992, # from the IATA otherwise. As noted below, Shanks & Pottenger say that -# America/Cordoba split into 6 subregions during 1991/1992, but we -# haven't verified this yet so for now we'll keep it a single region. +# America/Cordoba split into 6 subregions during 1991/1992, one of which +# was America/San_Luis, but we haven't verified this yet so for now we'll +# keep America/Cordoba a single region rather than splitting it into the +# other 5 subregions. + # # Zone NAME GMTOFF RULES FORMAT [UNTIL] # @@ -236,18 +334,16 @@ Zone America/Argentina/Buenos_Aires -3:53:48 - LMT 1894 Oct 31 -4:00 Arg AR%sT 1969 Oct 5 -3:00 Arg AR%sT 1999 Oct 3 -4:00 Arg AR%sT 2000 Mar 3 - -3:00 - ART + -3:00 Arg AR%sT # # Santa Fe (SF), Entre Rios (ER), Corrientes (CN), Misiones (MN), Chaco (CC), # Formosa (FM), Salta (SA), Santiago del Estero (SE), Cordoba (CB), -# San Luis (SL), La Pampa (LP), Neuquen (NQ), Rio Negro (RN) +# La Pampa (LP), Neuquen (NQ), Rio Negro (RN) # # Shanks & Pottenger also make the following claims, which we haven't verified: # - Formosa switched to -3:00 on 1991-01-07. # - Misiones switched to -3:00 on 1990-12-29. # - Chaco switched to -3:00 on 1991-01-04. -# - San Luis switched to -4:00 on 1990-03-14, then to -3:00 on 1990-10-15, -# then to -4:00 on 1991-03-01, then to -3:00 on 1991-06-01. # - Santiago del Estero switched to -4:00 on 1991-04-01, # then to -3:00 on 1991-04-26. # @@ -259,7 +355,7 @@ Zone America/Argentina/Cordoba -4:16:48 - LMT 1894 Oct 31 -4:00 - WART 1991 Oct 20 -3:00 Arg AR%sT 1999 Oct 3 -4:00 Arg AR%sT 2000 Mar 3 - -3:00 - ART + -3:00 Arg AR%sT # # Tucuman (TM) Zone America/Argentina/Tucuman -4:20:52 - LMT 1894 Oct 31 @@ -272,7 +368,7 @@ Zone America/Argentina/Tucuman -4:20:52 - LMT 1894 Oct 31 -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 Jun 1 -4:00 - WART 2004 Jun 13 - -3:00 - ART + -3:00 Arg AR%sT # # La Rioja (LR) Zone America/Argentina/La_Rioja -4:27:24 - LMT 1894 Oct 31 @@ -285,7 +381,7 @@ Zone America/Argentina/La_Rioja -4:27:24 - LMT 1894 Oct 31 -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 Jun 1 -4:00 - WART 2004 Jun 20 - -3:00 - ART + -3:00 Arg AR%sT # # San Juan (SJ) Zone America/Argentina/San_Juan -4:34:04 - LMT 1894 Oct 31 @@ -298,7 +394,7 @@ Zone America/Argentina/San_Juan -4:34:04 - LMT 1894 Oct 31 -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 May 31 -4:00 - WART 2004 Jul 25 - -3:00 - ART + -3:00 Arg AR%sT # # Jujuy (JY) Zone America/Argentina/Jujuy -4:21:12 - LMT 1894 Oct 31 @@ -312,7 +408,7 @@ Zone America/Argentina/Jujuy -4:21:12 - LMT 1894 Oct 31 -3:00 1:00 ARST 1992 -3:00 Arg AR%sT 1999 Oct 3 -4:00 Arg AR%sT 2000 Mar 3 - -3:00 - ART + -3:00 Arg AR%sT # # Catamarca (CT), Chubut (CH) Zone America/Argentina/Catamarca -4:23:08 - LMT 1894 Oct 31 @@ -325,7 +421,7 @@ Zone America/Argentina/Catamarca -4:23:08 - LMT 1894 Oct 31 -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 Jun 1 -4:00 - WART 2004 Jun 20 - -3:00 - ART + -3:00 Arg AR%sT # # Mendoza (MZ) Zone America/Argentina/Mendoza -4:35:16 - LMT 1894 Oct 31 @@ -342,6 +438,23 @@ Zone America/Argentina/Mendoza -4:35:16 - LMT 1894 Oct 31 -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 May 23 -4:00 - WART 2004 Sep 26 + -3:00 Arg AR%sT +# +# San Luis (SL) +Zone America/Argentina/San_Luis -4:25:24 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1990 + -3:00 1:00 ARST 1990 Mar 14 + -4:00 - WART 1990 Oct 15 + -4:00 1:00 WARST 1991 Mar 1 + -4:00 - WART 1991 Jun 1 + -3:00 - ART 1999 Oct 3 + -4:00 1:00 WARST 2000 Mar 3 + -3:00 - ART 2004 May 31 + -4:00 - WART 2004 Jul 25 + -3:00 Arg AR%sT 2008 Jan 21 -3:00 - ART # # Santa Cruz (SC) @@ -353,7 +466,7 @@ Zone America/Argentina/Rio_Gallegos -4:36:52 - LMT 1894 Oct 31 -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 Jun 1 -4:00 - WART 2004 Jun 20 - -3:00 - ART + -3:00 Arg AR%sT # # Tierra del Fuego, Antartida e Islas del Atlantico Sur (TF) Zone America/Argentina/Ushuaia -4:33:12 - LMT 1894 Oct 31 @@ -364,7 +477,7 @@ Zone America/Argentina/Ushuaia -4:33:12 - LMT 1894 Oct 31 -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 May 30 -4:00 - WART 2004 Jun 20 - -3:00 - ART + -3:00 Arg AR%sT # Aruba # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -450,6 +563,50 @@ Zone America/La_Paz -4:32:36 - LMT 1890 # Brazil will start DST on 2007-10-14 00:00 and end on 2008-02-17 00:00: # http://www.mme.gov.br/site/news/detail.do;jsessionid=BBA06811AFCAAC28F0285210913513DA?newsId=13975 +# From Paul Schulze (2008-06-24): +# ...by law number 11.662 of April 24, 2008 (published in the "Diario +# Oficial da Uniao"...) in Brazil there are changes in the timezones, +# effective today (00:00am at June 24, 2008) as follows: +# +# a) The timezone UTC+5 is e[x]tinguished, with all the Acre state and the +# part of the Amazonas state that had this timezone now being put to the +# timezone UTC+4 +# b) The whole Para state now is put at timezone UTC+3, instead of just +# part of it, as was before. +# +# This change follows a proposal of senator Tiao Viana of Acre state, that +# proposed it due to concerns about open television channels displaying +# programs inappropriate to youths in the states that had the timezone +# UTC+5 too early in the night. In the occasion, some more corrections +# were proposed, trying to unify the timezones of any given state. This +# change modifies timezone rules defined in decree 2.784 of 18 June, +# 1913. + +# From Rodrigo Severo (2008-06-24): +# Just correcting the URL: +# +# https://www.in.gov.br/imprensa/visualiza/index.jsp?jornal=3Ddo&secao=3D1&pagina=3D1&data=3D25/04/2008 +# +# +# As a result of the above Decree I believe the America/Rio_Branco +# timezone shall be modified from UTC-5 to UTC-4 and a new timezone shall +# be created to represent the the west side of the Para State. I +# suggest this new timezone be called Santarem as the most +# important/populated city in the affected area. +# +# This new timezone would be the same as the Rio_Branco timezone up to +# the 2008/06/24 change which would be to UTC-3 instead of UTC-4. + +# From Alex Krivenyshev (2008-06-24): +# This is a quick reference page for New and Old Brazil Time Zones map. +# +# http://www.worldtimezone.com/brazil-time-new-old.php +# +# +# - 4 time zones replaced by 3 time zones-eliminating time zone UTC- 05 +# (state Acre and the part of the Amazonas will be UTC/GMT- 04) - western +# part of Par state is moving to one timezone UTC- 03 (from UTC -04). + # From Paul Eggert (2002-10-10): # The official decrees referenced below are mostly taken from # @@ -572,13 +729,13 @@ Rule Brazil 2000 only - Feb 27 0:00 0 - Rule Brazil 2000 2001 - Oct Sun>=8 0:00 1:00 S Rule Brazil 2001 2006 - Feb Sun>=15 0:00 0 - # Decree 4,399 (2002-10-01) repeals DST in AL, CE, MA, PB, PE, PI, RN, SE. -# +# 4,399 Rule Brazil 2002 only - Nov 3 0:00 1:00 S # Decree 4,844 (2003-09-24; corrected 2003-09-26) repeals DST in BA, MT, TO. -# +# 4,844 Rule Brazil 2003 only - Oct 19 0:00 1:00 S # Decree 5,223 (2004-10-01) reestablishes DST in MT. -# +# 5,223 Rule Brazil 2004 only - Nov 2 0:00 1:00 S # Decree 5,539 (2005-09-19), # adopted by the same states as before. @@ -587,9 +744,8 @@ Rule Brazil 2005 only - Oct 16 0:00 1:00 S # adopted by the same states as before. Rule Brazil 2006 only - Nov 5 0:00 1:00 S Rule Brazil 2007 only - Feb 25 0:00 0 - -# (Decree number not yet known) -# http://www.brasil.gov.br/noticias/ultimas_noticias/horario_verao070920/ -# (2007-09-20) after a heads-up from Steffen Thorsen: +# Decree 6,212 (2007-09-26), +# adopted by the same states as before. Rule Brazil 2007 max - Oct Sun>=8 0:00 1:00 S Rule Brazil 2008 max - Feb Sun>=15 0:00 0 - # The latest ruleset listed above says that the following states observe DST: @@ -597,7 +753,6 @@ Rule Brazil 2008 max - Feb Sun>=15 0:00 0 - # For dates after mid-2008, the above rules with TO="max" are guesses # and are quite possibly wrong, but are more likely than no DST at all. - # Zone NAME GMTOFF RULES FORMAT [UNTIL] # # Fernando de Noronha (administratively part of PE) @@ -623,6 +778,13 @@ Zone America/Belem -3:13:56 - LMT 1914 -3:00 Brazil BR%sT 1988 Sep 12 -3:00 - BRT # +# west Para (PA) +# West Para includes Altamira, Oribidos, Prainha, Oriximina, and Santarem. +Zone America/Santarem -3:38:48 - LMT 1914 + -4:00 Brazil AM%sT 1988 Sep 12 + -4:00 - AMT 2008 Jun 24 00:00 + -3:00 - BRT +# # Maranhao (MA), Piaui (PI), Ceara (CE), Rio Grande do Norte (RN), # Paraiba (PB) Zone America/Fortaleza -2:34:00 - LMT 1914 @@ -685,8 +847,7 @@ Zone America/Cuiaba -3:44:20 - LMT 1914 -4:00 - AMT 2004 Oct 1 -4:00 Brazil AM%sT # -# west Para (PA), Rondonia (RO) -# West Para includes Altamira, Oribidos, Prainha, Oriximina, and Santarem. +# Rondonia (RO) Zone America/Porto_Velho -4:15:36 - LMT 1914 -4:00 Brazil AM%sT 1988 Sep 12 -4:00 - AMT @@ -713,13 +874,14 @@ Zone America/Eirunepe -4:39:28 - LMT 1914 -5:00 Brazil AC%sT 1988 Sep 12 -5:00 - ACT 1993 Sep 28 -5:00 Brazil AC%sT 1994 Sep 22 - -5:00 - ACT + -5:00 - ACT 2008 Jun 24 00:00 + -4:00 - AMT # # Acre (AC) Zone America/Rio_Branco -4:31:12 - LMT 1914 -5:00 Brazil AC%sT 1988 Sep 12 - -5:00 - ACT - + -5:00 - ACT 2008 Jun 24 00:00 + -4:00 - AMT # Chile @@ -753,6 +915,26 @@ Zone America/Rio_Branco -4:31:12 - LMT 1914 # America/Santiago. The pre-1980 Pacific/Easter data are dubious, # but we have no other source. +# From German Poo-Caaman~o (2008-03-03): +# Due to drought, Chile extends Daylight Time in three weeks. This +# is one-time change (Saturday 3/29 at 24:00 for America/Santiago +# and Saturday 3/29 at 22:00 for Pacific/Easter) +# The Supreme Decree is located at +# +# http://www.shoa.cl/servicios/supremo316.pdf +# +# and the instructions for 2008 are located in: +# +# http://www.horaoficial.cl/cambio.htm +# . + +# From Jose Miguel Garrido (2008-03-05): +# ... +# You could see the announces of the change on +# +# http://www.shoa.cl/noticias/2008/04hora/hora.htm +# . + # 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 - @@ -783,7 +965,11 @@ 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 2000 max - Mar Sun>=9 3:00u 0 - +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 max - Mar Sun>=9 3:00u 0 - # IATA SSIM anomalies: (1992-02) says 1992-03-14; # (1996-09) says 1998-03-08. Ignore these. # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -1129,19 +1315,17 @@ Zone America/Montevideo -3:44:44 - LMT 1898 Jun 28 # Venezuela # -# From Kiraz Janicke (2007-09-25), in -# http://www.venezuelanalysis.com/analysis/2645: -# The proposal ... involves turning the clock back half an hour from -# +4.00 Greenwich Mean Time (GMT), to +4.30GMT, the time zone -# Venezuela had until December 31, 1964, when the current time zone -# was adopted. The change was due to take place on September 17 and -# then on September 24, but has since been postponed until December -# 31, to allow for compliance with international organizations, such -# as the International Office of Weights and Measures. +# From John Stainforth (2007-11-28): +# ... the change for Venezuela originally expected for 2007-12-31 has +# been brought forward to 2007-12-09. The official announcement was +# published today in the "Gaceta Oficial de la Republica Bolivariana +# de Venezuela, numero 38.819" (official document for all laws or +# resolution publication) +# http://www.globovision.com/news.php?nid=72208 # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone America/Caracas -4:27:44 - LMT 1890 -4:27:40 - CMT 1912 Feb 12 # Caracas Mean Time? -4:30 - VET 1965 # Venezuela Time - -4:00 - VET 2008 + -4:00 - VET 2007 Dec 9 03:00 -4:30 - VET diff --git a/jdk/make/sun/javazic/tzdata/zone.tab b/jdk/make/sun/javazic/tzdata/zone.tab index b252abd4fd0..a9c686227ec 100644 --- a/jdk/make/sun/javazic/tzdata/zone.tab +++ b/jdk/make/sun/javazic/tzdata/zone.tab @@ -64,7 +64,8 @@ AQ -7824+10654 Antarctica/Vostok Vostok Station, S Magnetic Pole AQ -6640+14001 Antarctica/DumontDUrville Dumont-d'Urville Station, Terre Adelie AQ -690022+0393524 Antarctica/Syowa Syowa Station, E Ongul I AR -3436-05827 America/Argentina/Buenos_Aires Buenos Aires (BA, CF) -AR -3124-06411 America/Argentina/Cordoba most locations (CB, CC, CN, ER, FM, LP, MN, NQ, RN, SA, SE, SF, SL) +AR -3124-06411 America/Argentina/Cordoba most locations (CB, CC, CN, ER, FM, LP, MN, NQ, RN, SA, SE, SF) +AR -3319-06621 America/Argentina/San_Luis San Luis (SL) AR -2411-06518 America/Argentina/Jujuy Jujuy (JY) AR -2649-06513 America/Argentina/Tucuman Tucuman (TM) AR -2828-06547 America/Argentina/Catamarca Catamarca (CT), Chubut (CH) @@ -99,6 +100,7 @@ BG +4241+02319 Europe/Sofia BH +2623+05035 Asia/Bahrain BI -0323+02922 Africa/Bujumbura BJ +0629+00237 Africa/Porto-Novo +BL +1753-06251 America/St_Barthelemy BM +3217-06446 Atlantic/Bermuda BN +0456+11455 Asia/Brunei BO -1630-06809 America/La_Paz @@ -112,7 +114,8 @@ BR -1259-03831 America/Bahia Bahia BR -2332-04637 America/Sao_Paulo S & SE Brazil (GO, DF, MG, ES, RJ, SP, PR, SC, RS) BR -2027-05437 America/Campo_Grande Mato Grosso do Sul BR -1535-05605 America/Cuiaba Mato Grosso -BR -0846-06354 America/Porto_Velho W Para, Rondonia +BR -0226-05452 America/Santarem W Para +BR -0846-06354 America/Porto_Velho Rondonia BR +0249-06040 America/Boa_Vista Roraima BR -0308-06001 America/Manaus E Amazonas BR -0640-06952 America/Eirunepe W Amazonas @@ -230,7 +233,7 @@ ID -0232+14042 Asia/Jayapura Irian Jaya & the Moluccas IE +5320-00615 Europe/Dublin IL +3146+03514 Asia/Jerusalem IM +5409-00428 Europe/Isle_of_Man -IN +2232+08822 Asia/Calcutta +IN +2232+08822 Asia/Kolkata IO -0720+07225 Indian/Chagos IQ +3321+04425 Asia/Baghdad IR +3540+05126 Asia/Tehran @@ -272,6 +275,7 @@ MA +3339-00735 Africa/Casablanca MC +4342+00723 Europe/Monaco MD +4700+02850 Europe/Chisinau ME +4226+01916 Europe/Podgorica +MF +1804-06305 America/Marigot MG -1855+04731 Indian/Antananarivo MH +0709+17112 Pacific/Majuro most locations MH +0905+16720 Pacific/Kwajalein Kwajalein @@ -361,8 +365,7 @@ SE +5920+01803 Europe/Stockholm SG +0117+10351 Asia/Singapore SH -1555-00542 Atlantic/St_Helena SI +4603+01431 Europe/Ljubljana -SJ +7800+01600 Arctic/Longyearbyen Svalbard -SJ +7059-00805 Atlantic/Jan_Mayen Jan Mayen +SJ +7800+01600 Arctic/Longyearbyen SK +4809+01707 Europe/Bratislava SL +0830-01315 Africa/Freetown SM +4355+01228 Europe/San_Marino @@ -432,7 +435,7 @@ VC +1309-06114 America/St_Vincent VE +1030-06656 America/Caracas VG +1827-06437 America/Tortola VI +1821-06456 America/St_Thomas -VN +1045+10640 Asia/Saigon +VN +1045+10640 Asia/Ho_Chi_Minh VU -1740+16825 Pacific/Efate WF -1318-17610 Pacific/Wallis WS -1350-17144 Pacific/Apia diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames.java index 770900f1b4a..6925ba12d5b 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames.java @@ -291,6 +291,7 @@ public final class TimeZoneNames extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames extends TimeZoneNamesBundle { "Suriname Summer Time", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames extends TimeZoneNamesBundle { "Tajikistan Summer Time", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"Hovd Time", "HOVT", "Hovd Summer Time", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"Nepal Time", "NPT", "Nepal Summer Time", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"Krasnoyarsk Time", "KRAT", "Krasnoyarsk Summer Time", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_de.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_de.java index f67f3d8a6b1..eed4bbfb37d 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_de.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_de.java @@ -291,6 +291,7 @@ public final class TimeZoneNames_de extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames_de extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames_de extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames_de extends TimeZoneNamesBundle { "Suriname Sommerzeit", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames_de extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames_de extends TimeZoneNamesBundle { "Tadschikische Sommerzeit", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"Hovd Zeit", "HOVT", "Hovd Sommerzeit", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames_de extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"Nepalesische Zeit", "NPT", "Nepalesische Sommerzeit", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"Krasnojarsker Zeit", "KRAT", "Krasnojarsker Sommerzeit", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames_de extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_es.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_es.java index 5b3001b708b..27bf6533143 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_es.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_es.java @@ -291,6 +291,7 @@ public final class TimeZoneNames_es extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames_es extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames_es extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames_es extends TimeZoneNamesBundle { "Hora de verano de Surinam", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames_es extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames_es extends TimeZoneNamesBundle { "Hora de verano de Tajikist\u00e1n", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"Hora de Hovd", "HOVT", "Hora de verano de Hovd", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames_es extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"Hora de Nepal", "NPT", "Hora de verano de Nepal", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"Hora de Krasnoyarsk", "KRAT", "Hora de verano de Krasnoyarsk", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames_es extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_fr.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_fr.java index 3e0f61ce6ac..e9a3811d1b7 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_fr.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_fr.java @@ -291,6 +291,7 @@ public final class TimeZoneNames_fr extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames_fr extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames_fr extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames_fr extends TimeZoneNamesBundle { "Heure d'\u00e9t\u00e9 du Surinam", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames_fr extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames_fr extends TimeZoneNamesBundle { "Heure d'\u00e9t\u00e9 du Tadjikistan", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"Heure de Hovd", "HOVT", "Heure d'\u00e9t\u00e9 de Hovd", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames_fr extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"Heure du N\u00e9pal", "NPT", "Heure d'\u00e9t\u00e9 du N\u00e9pal", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"Heure de Krasno\u00efarsk", "KRAT", "Heure d'\u00e9t\u00e9 de Krasno\u00efarsk", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames_fr extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_it.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_it.java index 2ca155757c9..8012c36f7e6 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_it.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_it.java @@ -291,6 +291,7 @@ public final class TimeZoneNames_it extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames_it extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames_it extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames_it extends TimeZoneNamesBundle { "Ora estiva di Suriname", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames_it extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames_it extends TimeZoneNamesBundle { "Ora estiva del Tagikistan", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"Ora di Hovd", "HOVT", "Ora estiva di Hovd", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames_it extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"Ora del Nepal", "NPT", "Ora estiva del Nepal", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"Ora di Krasnojarsk", "KRAT", "Ora estiva di Krasnojarsk", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames_it extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_ja.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_ja.java index 19b1291a1f3..33a1913bd52 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_ja.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_ja.java @@ -291,6 +291,7 @@ public final class TimeZoneNames_ja extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames_ja extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames_ja extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames_ja extends TimeZoneNamesBundle { "\u30b9\u30ea\u30ca\u30e0\u590f\u6642\u9593", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames_ja extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames_ja extends TimeZoneNamesBundle { "\u30bf\u30b8\u30ad\u30b9\u30bf\u30f3\u590f\u6642\u9593", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"\u30db\u30d6\u30c9\u6642\u9593", "HOVT", "\u30db\u30d6\u30c9\u590f\u6642\u9593", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames_ja extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"\u30cd\u30d1\u30fc\u30eb\u6642\u9593", "NPT", "\u30cd\u30d1\u30fc\u30eb\u590f\u6642\u9593", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"\u30af\u30e9\u30b9\u30ce\u30e4\u30eb\u30b9\u30af\u6642\u9593", "KRAT", "\u30af\u30e9\u30b9\u30ce\u30e4\u30eb\u30b9\u30af\u590f\u6642\u9593", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames_ja extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_ko.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_ko.java index 9cf574709f2..8068237976f 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_ko.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_ko.java @@ -291,6 +291,7 @@ public final class TimeZoneNames_ko extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames_ko extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames_ko extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames_ko extends TimeZoneNamesBundle { "\uc218\ub9ac\ub0a8 \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames_ko extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames_ko extends TimeZoneNamesBundle { "\ud0c0\uc9c0\ud0a4\uc2a4\ud0c4 \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"Hovd \uc2dc\uac04", "HOVT", "Hovd \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames_ko extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"\ub124\ud314 \uc2dc\uac04", "NPT", "\ub124\ud314 \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"\ud06c\ub77c\uc2a4\ub178\uc57c\ub974\uc2a4\ud06c \uc2dc\uac04", "KRAT", "\ud06c\ub77c\uc2a4\ub178\uc57c\ub974\uc2a4\ud06c \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames_ko extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_sv.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_sv.java index c8a6589a3f5..cc872089fe1 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_sv.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_sv.java @@ -291,6 +291,7 @@ public final class TimeZoneNames_sv extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames_sv extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames_sv extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames_sv extends TimeZoneNamesBundle { "Surinam, sommartid", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames_sv extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames_sv extends TimeZoneNamesBundle { "Tadzjikistan, sommartid", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"Hovd, normaltid", "HOVT", "Hovd, sommartid", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames_sv extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"Nepal, normaltid", "NPT", "Nepal, sommartid", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"Krasnojarsk, normaltid", "KRAT", "Krasnojarsk, sommartid", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames_sv extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_zh_CN.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_zh_CN.java index 9963863988e..62304e98586 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_zh_CN.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_zh_CN.java @@ -291,6 +291,7 @@ public final class TimeZoneNames_zh_CN extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames_zh_CN extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames_zh_CN extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames_zh_CN extends TimeZoneNamesBundle { "\u82cf\u5229\u5357\u590f\u4ee4\u65f6", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames_zh_CN extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames_zh_CN extends TimeZoneNamesBundle { "\u5854\u5409\u514b\u65af\u5766\u590f\u4ee4\u65f6", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"\u79d1\u5e03\u591a\u65f6\u95f4", "HOVT", "\u79d1\u5e03\u591a\u590f\u4ee4\u65f6", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames_zh_CN extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"\u5c3c\u6cca\u5c14\u65f6\u95f4", "NPT", "\u5c3c\u6cca\u5c14\u590f\u4ee4\u65f6", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"\u514b\u62c9\u65af\u8bfa\u4e9a\u5c14\u65af\u514b\u65f6\u95f4", "KRAT", "\u514b\u62c9\u65af\u8bfa\u4e9a\u5c14\u65af\u514b\u590f\u4ee4\u65f6", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames_zh_CN extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_zh_TW.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_zh_TW.java index d4796f1c1ab..77f539fe990 100644 --- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames_zh_TW.java +++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames_zh_TW.java @@ -291,6 +291,7 @@ public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle { {"America/Argentina/Mendoza", AGT}, {"America/Argentina/Rio_Gallegos", AGT}, {"America/Argentina/San_Juan", AGT}, + {"America/Argentina/San_Luis", AGT}, {"America/Argentina/Tucuman", AGT}, {"America/Argentina/Ushuaia", AGT}, {"America/Aruba", AST}, @@ -329,7 +330,7 @@ public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle { {"America/Detroit", EST}, {"America/Dominica", AST}, {"America/Edmonton", MST}, - {"America/Eirunepe", ACT}, + {"America/Eirunepe", AMT}, {"America/El_Salvador", CST}, {"America/Ensenada", PST}, {"America/Fort_Wayne", EST}, @@ -372,6 +373,7 @@ public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle { {"America/Maceio", BRT}, {"America/Managua", CST}, {"America/Manaus", AMT}, + {"America/Marigot", AST}, {"America/Martinique", AST}, {"America/Mazatlan", MST}, {"America/Mendoza", AGT}, @@ -398,7 +400,7 @@ public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle { "\u8607\u5229\u5357\u590f\u4ee4\u6642\u9593", "SRST"}}, {"America/Port-au-Prince", EST}, {"America/Port_of_Spain", AST}, - {"America/Porto_Acre", ACT}, + {"America/Porto_Acre", AMT}, {"America/Porto_Velho", AMT}, {"America/Puerto_Rico", AST}, {"America/Rainy_River", CST}, @@ -406,13 +408,15 @@ public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle { {"America/Recife", BRT}, {"America/Regina", CST}, {"America/Resolute", EST}, - {"America/Rio_Branco", ACT}, + {"America/Rio_Branco", AMT}, {"America/Rosario", AGT}, + {"America/Santarem", BRT}, {"America/Santiago", CLT}, {"America/Santo_Domingo", AST}, {"America/Sao_Paulo", BRT}, {"America/Scoresbysund", EGT}, {"America/Shiprock", MST}, + {"America/St_Barthelemy", AST}, {"America/St_Kitts", AST}, {"America/St_Lucia", AST}, {"America/St_Thomas", AST}, @@ -485,6 +489,7 @@ public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle { "\u5854\u5409\u514b\u590f\u4ee4\u6642\u9593", "TJST"}}, {"Asia/Gaza", EET}, {"Asia/Harbin", CTT}, + {"Asia/Ho_Chi_Minh", ICT}, {"Asia/Hong_Kong", HKT}, {"Asia/Hovd", new String[] {"\u4faf\u5fb7 (Hovd) \u6642\u9593", "HOVT", "\u4faf\u5fb7 (Hovd) \u590f\u4ee4\u6642\u9593", "HOVST"}}, @@ -502,6 +507,7 @@ public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle { {"Asia/Kashgar", CTT}, {"Asia/Katmandu", new String[] {"\u5c3c\u6cca\u723e\u6642\u9593", "NPT", "\u5c3c\u6cca\u723e\u590f\u4ee4\u6642\u9593", "NPST"}}, + {"Asia/Kolkata", IST}, {"Asia/Krasnoyarsk", new String[] {"\u514b\u62c9\u65af\u8afe\u4e9e\u723e\u65af\u514b\u6642\u9593", "KRAT", "\u514b\u62c9\u65af\u8afe\u4e9e\u723e\u65af\u514b\u590f\u4ee4\u6642\u9593", "KRAST"}}, {"Asia/Kuala_Lumpur", MYT}, @@ -599,7 +605,7 @@ public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle { {"Australia/Yancowinna", BROKEN_HILL}, {"BET", BRT}, {"BST", BDT}, - {"Brazil/Acre", ACT}, + {"Brazil/Acre", AMT}, {"Brazil/DeNoronha", NORONHA}, {"Brazil/East", BRT}, {"Brazil/West", AMT}, From 46533a9546b2c8f7808ee30adb6ed2a8de47c61a Mon Sep 17 00:00:00 2001 From: Pavel Porvatov Date: Wed, 10 Sep 2008 19:16:14 +0400 Subject: [PATCH 45/45] 6587742: filling half of a JSlider's track is no longer optional Now OceanTheme uses the JSlider.isFilled property like other themes Reviewed-by: alexp --- .../javax/swing/plaf/metal/MetalSliderUI.java | 277 +++++++++--------- .../swing/JSlider/6587742/bug6587742.html | 13 + .../swing/JSlider/6587742/bug6587742.java | 130 ++++++++ 3 files changed, 288 insertions(+), 132 deletions(-) create mode 100644 jdk/test/javax/swing/JSlider/6587742/bug6587742.html create mode 100644 jdk/test/javax/swing/JSlider/6587742/bug6587742.java diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java index ce9462737eb..7a26c46b225 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java @@ -27,23 +27,13 @@ package javax.swing.plaf.metal; import javax.swing.plaf.basic.BasicSliderUI; -import java.awt.Component; -import java.awt.Container; import java.awt.Graphics; import java.awt.Dimension; import java.awt.Rectangle; -import java.awt.Point; -import java.awt.Insets; import java.awt.Color; -import java.io.Serializable; -import java.awt.IllegalComponentStateException; -import java.awt.Polygon; import java.beans.*; -import javax.swing.border.AbstractBorder; - import javax.swing.*; -import javax.swing.event.*; import javax.swing.plaf.*; /** @@ -131,10 +121,7 @@ public class MetalSliderUI extends BasicSliderUI { scrollListener.setScrollByBlock( false ); - Object sliderFillProp = c.getClientProperty( SLIDER_FILL ); - if ( sliderFillProp != null ) { - filledSlider = ((Boolean)sliderFillProp).booleanValue(); - } + prepareFilledSliderField(); } protected PropertyChangeListener createPropertyChangeListener( JSlider slider ) { @@ -145,18 +132,23 @@ public class MetalSliderUI extends BasicSliderUI { public void propertyChange( PropertyChangeEvent e ) { // listen for slider fill super.propertyChange( e ); - String name = e.getPropertyName(); - if ( name.equals( SLIDER_FILL ) ) { - if ( e.getNewValue() != null ) { - filledSlider = ((Boolean)e.getNewValue()).booleanValue(); - } - else { - filledSlider = false; - } + if (e.getPropertyName().equals(SLIDER_FILL)) { + prepareFilledSliderField(); } } } + private void prepareFilledSliderField() { + // Use true for Ocean theme + filledSlider = MetalLookAndFeel.usingOcean(); + + Object sliderFillProp = slider.getClientProperty(SLIDER_FILL); + + if (sliderFillProp != null) { + filledSlider = ((Boolean) sliderFillProp).booleanValue(); + } + } + public void paintThumb(Graphics g) { Rectangle knobBounds = thumbRect; @@ -172,22 +164,11 @@ public class MetalSliderUI extends BasicSliderUI { g.translate( -knobBounds.x, -knobBounds.y ); } - /** - * If chooseFirstis true, c1 is returned, - * otherwise c2. - */ - private Color chooseColor(boolean chooseFirst, Color c1, Color c2) { - if (chooseFirst) { - return c2; - } - return c1; - } - /** * Returns a rectangle enclosing the track that will be painted. */ private Rectangle getPaintTrackRect() { - int trackLeft = 0, trackRight = 0, trackTop = 0, trackBottom = 0; + int trackLeft = 0, trackRight, trackTop = 0, trackBottom; if (slider.getOrientation() == JSlider.HORIZONTAL) { trackBottom = (trackRect.height - 1) - getThumbOverhang(); trackTop = trackBottom - (getTrackWidth() - 1); @@ -223,8 +204,8 @@ public class MetalSliderUI extends BasicSliderUI { int trackLeft = 0; int trackTop = 0; - int trackRight = 0; - int trackBottom = 0; + int trackRight; + int trackBottom; // Draw the track if ( slider.getOrientation() == JSlider.HORIZONTAL ) { @@ -266,11 +247,11 @@ public class MetalSliderUI extends BasicSliderUI { // Draw the fill if ( filledSlider ) { - int middleOfThumb = 0; - int fillTop = 0; - int fillLeft = 0; - int fillBottom = 0; - int fillRight = 0; + int middleOfThumb; + int fillTop; + int fillLeft; + int fillBottom; + int fillRight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { middleOfThumb = thumbRect.x + (thumbRect.width / 2); @@ -335,105 +316,137 @@ public class MetalSliderUI extends BasicSliderUI { int w = paintRect.width; int h = paintRect.height; - if (!slider.isEnabled()) { - g.setColor(MetalLookAndFeel.getControlShadow()); - g.drawRect(0, 0, w - 1, h - 1); - } - else if (slider.getOrientation() == JSlider.HORIZONTAL) { - int middleOfThumb = thumbRect.x + (thumbRect.width / 2) - - paintRect.x; - int fillMinX; - int fillMaxX; + if (slider.getOrientation() == JSlider.HORIZONTAL) { + int middleOfThumb = thumbRect.x + thumbRect.width / 2 - paintRect.x; - if (middleOfThumb > 0) { - g.setColor(chooseColor(drawInverted, - MetalLookAndFeel.getPrimaryControlDarkShadow(), - MetalLookAndFeel.getControlDarkShadow())); - g.drawRect(0, 0, middleOfThumb - 1, h - 1); - } - if (middleOfThumb < w) { - g.setColor(chooseColor(drawInverted, - MetalLookAndFeel.getControlDarkShadow(), - MetalLookAndFeel.getPrimaryControlDarkShadow())); - g.drawRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1); - } - g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); - if (drawInverted) { - fillMinX = middleOfThumb; - fillMaxX = w - 2; - g.drawLine(1, 1, middleOfThumb, 1); - } - else { - fillMinX = 1; - fillMaxX = middleOfThumb; - g.drawLine(middleOfThumb, 1, w - 1, 1); - } - if (h == 6) { - g.setColor(MetalLookAndFeel.getWhite()); - g.drawLine(fillMinX, 1, fillMaxX, 1); - g.setColor(sliderAltTrackColor); - g.drawLine(fillMinX, 2, fillMaxX, 2); + if (slider.isEnabled()) { + int fillMinX; + int fillMaxX; + + if (middleOfThumb > 0) { + g.setColor(drawInverted ? MetalLookAndFeel.getControlDarkShadow() : + MetalLookAndFeel.getPrimaryControlDarkShadow()); + + g.drawRect(0, 0, middleOfThumb - 1, h - 1); + } + + if (middleOfThumb < w) { + g.setColor(drawInverted ? MetalLookAndFeel.getPrimaryControlDarkShadow() : + MetalLookAndFeel.getControlDarkShadow()); + + g.drawRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1); + } + + if (filledSlider) { + g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); + if (drawInverted) { + fillMinX = middleOfThumb; + fillMaxX = w - 2; + g.drawLine(1, 1, middleOfThumb, 1); + } else { + fillMinX = 1; + fillMaxX = middleOfThumb; + g.drawLine(middleOfThumb, 1, w - 1, 1); + } + if (h == 6) { + g.setColor(MetalLookAndFeel.getWhite()); + g.drawLine(fillMinX, 1, fillMaxX, 1); + g.setColor(sliderAltTrackColor); + g.drawLine(fillMinX, 2, fillMaxX, 2); + g.setColor(MetalLookAndFeel.getControlShadow()); + g.drawLine(fillMinX, 3, fillMaxX, 3); + g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); + g.drawLine(fillMinX, 4, fillMaxX, 4); + } + } + } else { g.setColor(MetalLookAndFeel.getControlShadow()); - g.drawLine(fillMinX, 3, fillMaxX, 3); - g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); - g.drawLine(fillMinX, 4, fillMaxX, 4); - } - } - else { - int middleOfThumb = thumbRect.y + (thumbRect.height / 2) - - paintRect.y; - int fillMinY; - int fillMaxY; - if (middleOfThumb > 0) { - g.setColor(chooseColor(drawInverted, - MetalLookAndFeel.getControlDarkShadow(), - MetalLookAndFeel.getPrimaryControlDarkShadow())); - g.drawRect(0, 0, w - 1, middleOfThumb - 1); - } - if (middleOfThumb < h) { - g.setColor(chooseColor(drawInverted, - MetalLookAndFeel.getPrimaryControlDarkShadow(), - MetalLookAndFeel.getControlDarkShadow())); - g.drawRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1); - } - g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); - if (drawInverted()) { - fillMinY = 1; - fillMaxY = middleOfThumb; - if (leftToRight) { - g.drawLine(1, middleOfThumb, 1, h - 1); + if (middleOfThumb > 0) { + if (!drawInverted && filledSlider) { + g.fillRect(0, 0, middleOfThumb - 1, h - 1); + } else { + g.drawRect(0, 0, middleOfThumb - 1, h - 1); + } } - else { - g.drawLine(w - 2, middleOfThumb, w - 2, h - 1); + + if (middleOfThumb < w) { + if (drawInverted && filledSlider) { + g.fillRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1); + } else { + g.drawRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1); + } } } - else { - fillMinY = middleOfThumb; - fillMaxY = h - 2; - if (leftToRight) { - g.drawLine(1, 1, 1, middleOfThumb); + } else { + int middleOfThumb = thumbRect.y + (thumbRect.height / 2) - paintRect.y; + + if (slider.isEnabled()) { + int fillMinY; + int fillMaxY; + + if (middleOfThumb > 0) { + g.setColor(drawInverted ? MetalLookAndFeel.getPrimaryControlDarkShadow() : + MetalLookAndFeel.getControlDarkShadow()); + + g.drawRect(0, 0, w - 1, middleOfThumb - 1); } - else { - g.drawLine(w - 2, 1, w - 2, middleOfThumb); + + if (middleOfThumb < h) { + g.setColor(drawInverted ? MetalLookAndFeel.getControlDarkShadow() : + MetalLookAndFeel.getPrimaryControlDarkShadow()); + + g.drawRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1); + } + + if (filledSlider) { + g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); + if (drawInverted()) { + fillMinY = 1; + fillMaxY = middleOfThumb; + if (leftToRight) { + g.drawLine(1, middleOfThumb, 1, h - 1); + } else { + g.drawLine(w - 2, middleOfThumb, w - 2, h - 1); + } + } else { + fillMinY = middleOfThumb; + fillMaxY = h - 2; + if (leftToRight) { + g.drawLine(1, 1, 1, middleOfThumb); + } else { + g.drawLine(w - 2, 1, w - 2, middleOfThumb); + } + } + if (w == 6) { + g.setColor(leftToRight ? MetalLookAndFeel.getWhite() : MetalLookAndFeel.getPrimaryControlShadow()); + g.drawLine(1, fillMinY, 1, fillMaxY); + g.setColor(leftToRight ? sliderAltTrackColor : MetalLookAndFeel.getControlShadow()); + g.drawLine(2, fillMinY, 2, fillMaxY); + g.setColor(leftToRight ? MetalLookAndFeel.getControlShadow() : sliderAltTrackColor); + g.drawLine(3, fillMinY, 3, fillMaxY); + g.setColor(leftToRight ? MetalLookAndFeel.getPrimaryControlShadow() : MetalLookAndFeel.getWhite()); + g.drawLine(4, fillMinY, 4, fillMaxY); + } + } + } else { + g.setColor(MetalLookAndFeel.getControlShadow()); + + if (middleOfThumb > 0) { + if (drawInverted && filledSlider) { + g.fillRect(0, 0, w - 1, middleOfThumb - 1); + } else { + g.drawRect(0, 0, w - 1, middleOfThumb - 1); + } + } + + if (middleOfThumb < h) { + if (!drawInverted && filledSlider) { + g.fillRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1); + } else { + g.drawRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1); + } } - } - if (w == 6) { - g.setColor(chooseColor(!leftToRight, - MetalLookAndFeel.getWhite(), - MetalLookAndFeel.getPrimaryControlShadow())); - g.drawLine(1, fillMinY, 1, fillMaxY); - g.setColor(chooseColor(!leftToRight, sliderAltTrackColor, - MetalLookAndFeel.getControlShadow())); - g.drawLine(2, fillMinY, 2, fillMaxY); - g.setColor(chooseColor(!leftToRight, - MetalLookAndFeel.getControlShadow(), - sliderAltTrackColor)); - g.drawLine(3, fillMinY, 3, fillMaxY); - g.setColor(chooseColor(!leftToRight, - MetalLookAndFeel.getPrimaryControlShadow(), - MetalLookAndFeel.getWhite())); - g.drawLine(4, fillMinY, 4, fillMaxY); } } diff --git a/jdk/test/javax/swing/JSlider/6587742/bug6587742.html b/jdk/test/javax/swing/JSlider/6587742/bug6587742.html new file mode 100644 index 00000000000..ceda9f921c7 --- /dev/null +++ b/jdk/test/javax/swing/JSlider/6587742/bug6587742.html @@ -0,0 +1,13 @@ + + + +Select every theme and check that all sliders looks good. +Note that every slider has a tooltip text with information about +slider configuration. +There is a small difference in sliders with property "filled = null" (it's +default behaviour when property JSlider.isFilled is not setted) +for themes: +1. OceanTheme - sliders look like filled +2. DefaultMetalTheme - sliders look like NOT filled + + diff --git a/jdk/test/javax/swing/JSlider/6587742/bug6587742.java b/jdk/test/javax/swing/JSlider/6587742/bug6587742.java new file mode 100644 index 00000000000..e5282e3cedb --- /dev/null +++ b/jdk/test/javax/swing/JSlider/6587742/bug6587742.java @@ -0,0 +1,130 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6587742 + * @summary filling half of a JSlider's track is no longer optional + * @author Pavel Porvatov + * @run applet/manual=done bug6587742.html + */ + +import javax.swing.*; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalLookAndFeel; +import javax.swing.plaf.metal.MetalTheme; +import javax.swing.plaf.metal.OceanTheme; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +public class bug6587742 extends JApplet { + public void init() { + TestPanel panel = new TestPanel(); + + setContentPane(panel); + } + + private class TestPanel extends JPanel { + private final JComboBox cbThemes = new JComboBox(); + + private TestPanel() { + // Fill cbThemes + cbThemes.addItem(new OceanTheme()); + cbThemes.addItem(new DefaultMetalTheme()); + + cbThemes.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + MetalTheme theme = (MetalTheme) cbThemes.getSelectedItem(); + + if (theme != null) { + MetalLookAndFeel.setCurrentTheme(theme); + + // re-install the Metal Look and Feel + try { + UIManager.setLookAndFeel(new MetalLookAndFeel()); + } catch (UnsupportedLookAndFeelException e1) { + JOptionPane.showMessageDialog(TestPanel.this, "Can't change theme: " + e1.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + + return; + } + + SwingUtilities.updateComponentTreeUI(bug6587742.this); + } + } + }); + + JPanel pnVertical = new JPanel(); + + pnVertical.setLayout(new BoxLayout(pnVertical, BoxLayout.Y_AXIS)); + + for (int i = 0; i < 12; i++) { + int filled = i >> 2; + + pnVertical.add(createSlider(false, filled > 1 ? null : Boolean.valueOf(filled == 1), (i & 2) == 0, + (i & 1) != 0)); + } + + JPanel pnHorizontal = new JPanel(); + + pnHorizontal.setLayout(new BoxLayout(pnHorizontal, BoxLayout.X_AXIS)); + + for (int i = 0; i < 12; i++) { + int filled = i >> 2; + + pnHorizontal.add(createSlider(true, filled > 1 ? null : Boolean.valueOf(filled == 1), (i & 2) == 0, + (i & 1) != 0)); + } + + JTabbedPane tpSliders = new JTabbedPane(); + + tpSliders.add("Vertical sliders", pnVertical); + tpSliders.add("Horizontal sliders", pnHorizontal); + + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + + add(new JLabel("Select theme:")); + add(cbThemes); + add(tpSliders); + } + } + + private static JSlider createSlider(boolean vertical, Boolean filled, boolean enabled, boolean inverted) { + JSlider result = new JSlider(vertical ? SwingConstants.VERTICAL : SwingConstants.HORIZONTAL, 0, 100, 50); + + result.setMajorTickSpacing(20); + result.setMinorTickSpacing(5); + result.setPaintTicks(true); + result.setPaintLabels(true); + result.setEnabled(enabled); + + if (filled != null) { + result.putClientProperty("JSlider.isFilled", filled); + } + + result.setInverted(inverted); + result.setToolTipText("vertical = " + vertical + "
enabled = " + enabled + "
filled = " + filled + + "
inverted = " + inverted + ""); + + return result; + } +}