code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.OptionPaneUI;
import javax.swing.JOptionPane;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>OptionPaneUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiOptionPaneUI extends OptionPaneUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// OptionPaneUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>selectInitialValue</code> method on each UI handled by this object.
*/
public void selectInitialValue(JOptionPane a) {
for (int i = 0; i < uis.size(); i++) {
((OptionPaneUI) (uis.elementAt(i))).selectInitialValue(a);
}
}
/** {@collect.stats}
* Invokes the <code>containsCustomComponents</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean containsCustomComponents(JOptionPane a) {
boolean returnValue =
((OptionPaneUI) (uis.elementAt(0))).containsCustomComponents(a);
for (int i = 1; i < uis.size(); i++) {
((OptionPaneUI) (uis.elementAt(i))).containsCustomComponents(a);
}
return returnValue;
}
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiOptionPaneUI();
return MultiLookAndFeel.createUIs(mui,
((MultiOptionPaneUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.TableHeaderUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>TableHeaderUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiTableHeaderUI extends TableHeaderUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// TableHeaderUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiTableHeaderUI();
return MultiLookAndFeel.createUIs(mui,
((MultiTableHeaderUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.RootPaneUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>RootPaneUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
* @since 1.4
*/
public class MultiRootPaneUI extends RootPaneUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// RootPaneUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiRootPaneUI();
return MultiLookAndFeel.createUIs(mui,
((MultiRootPaneUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.ColorChooserUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>ColorChooserUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiColorChooserUI extends ColorChooserUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// ColorChooserUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiColorChooserUI();
return MultiLookAndFeel.createUIs(mui,
((MultiColorChooserUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.ComboBoxUI;
import javax.swing.JComboBox;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>ComboBoxUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiComboBoxUI extends ComboBoxUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// ComboBoxUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>isFocusTraversable</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean isFocusTraversable(JComboBox a) {
boolean returnValue =
((ComboBoxUI) (uis.elementAt(0))).isFocusTraversable(a);
for (int i = 1; i < uis.size(); i++) {
((ComboBoxUI) (uis.elementAt(i))).isFocusTraversable(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>setPopupVisible</code> method on each UI handled by this object.
*/
public void setPopupVisible(JComboBox a, boolean b) {
for (int i = 0; i < uis.size(); i++) {
((ComboBoxUI) (uis.elementAt(i))).setPopupVisible(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>isPopupVisible</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean isPopupVisible(JComboBox a) {
boolean returnValue =
((ComboBoxUI) (uis.elementAt(0))).isPopupVisible(a);
for (int i = 1; i < uis.size(); i++) {
((ComboBoxUI) (uis.elementAt(i))).isPopupVisible(a);
}
return returnValue;
}
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiComboBoxUI();
return MultiLookAndFeel.createUIs(mui,
((MultiComboBoxUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.ToolTipUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>ToolTipUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiToolTipUI extends ToolTipUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// ToolTipUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiToolTipUI();
return MultiLookAndFeel.createUIs(mui,
((MultiToolTipUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.ListUI;
import javax.swing.JList;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>ListUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiListUI extends ListUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// ListUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>locationToIndex</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int locationToIndex(JList a, Point b) {
int returnValue =
((ListUI) (uis.elementAt(0))).locationToIndex(a,b);
for (int i = 1; i < uis.size(); i++) {
((ListUI) (uis.elementAt(i))).locationToIndex(a,b);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>indexToLocation</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Point indexToLocation(JList a, int b) {
Point returnValue =
((ListUI) (uis.elementAt(0))).indexToLocation(a,b);
for (int i = 1; i < uis.size(); i++) {
((ListUI) (uis.elementAt(i))).indexToLocation(a,b);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getCellBounds</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Rectangle getCellBounds(JList a, int b, int c) {
Rectangle returnValue =
((ListUI) (uis.elementAt(0))).getCellBounds(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ListUI) (uis.elementAt(i))).getCellBounds(a,b,c);
}
return returnValue;
}
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiListUI();
return MultiLookAndFeel.createUIs(mui,
((MultiListUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import java.lang.reflect.Method;
import javax.swing.*;
import javax.swing.plaf.*;
/** {@collect.stats}
* <p>A multiplexing look and feel that allows more than one UI
* to be associated with a component at the same time.
* The primary look and feel is called
* the <em>default</em> look and feel,
* and the other look and feels are called <em>auxiliary</em>.
* <p>
*
* For further information, see
* <a href="doc-files/multi_tsc.html" target="_top">Using the
* Multiplexing Look and Feel.</a>
*
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see UIManager#addAuxiliaryLookAndFeel
* @see javax.swing.plaf.multi
*
* @author Willie Walker
*/
public class MultiLookAndFeel extends LookAndFeel {
//////////////////////////////
// LookAndFeel methods
//////////////////////////////
/** {@collect.stats}
* Returns a string, suitable for use in menus,
* that identifies this look and feel.
*
* @return a string such as "Multiplexing Look and Feel"
*/
public String getName() {
return "Multiplexing Look and Feel";
}
/** {@collect.stats}
* Returns a string, suitable for use by applications/services,
* that identifies this look and feel.
*
* @return "Multiplex"
*/
public String getID() {
return "Multiplex";
}
/** {@collect.stats}
* 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";
}
/** {@collect.stats}
* Returns <code>false</code>;
* this look and feel is not native to any platform.
*
* @return <code>false</code>
*/
public boolean isNativeLookAndFeel() {
return false;
}
/** {@collect.stats}
* Returns <code>true</code>;
* every platform permits this look and feel.
*
* @return <code>true</code>
*/
public boolean isSupportedLookAndFeel() {
return true;
}
/** {@collect.stats}
* Creates, initializes, and returns
* the look and feel specific defaults.
* For this look and feel,
* the defaults consist solely of
* mappings of UI class IDs
* (such as "ButtonUI")
* to <code>ComponentUI</code> class names
* (such as "javax.swing.plaf.multi.MultiButtonUI").
*
* @return an initialized <code>UIDefaults</code> object
* @see javax.swing.JComponent#getUIClassID
*/
public UIDefaults getDefaults() {
String packageName = "javax.swing.plaf.multi.Multi";
Object[] uiDefaults = {
"ButtonUI", packageName + "ButtonUI",
"CheckBoxMenuItemUI", packageName + "MenuItemUI",
"CheckBoxUI", packageName + "ButtonUI",
"ColorChooserUI", packageName + "ColorChooserUI",
"ComboBoxUI", packageName + "ComboBoxUI",
"DesktopIconUI", packageName + "DesktopIconUI",
"DesktopPaneUI", packageName + "DesktopPaneUI",
"EditorPaneUI", packageName + "TextUI",
"FileChooserUI", packageName + "FileChooserUI",
"FormattedTextFieldUI", packageName + "TextUI",
"InternalFrameUI", packageName + "InternalFrameUI",
"LabelUI", packageName + "LabelUI",
"ListUI", packageName + "ListUI",
"MenuBarUI", packageName + "MenuBarUI",
"MenuItemUI", packageName + "MenuItemUI",
"MenuUI", packageName + "MenuItemUI",
"OptionPaneUI", packageName + "OptionPaneUI",
"PanelUI", packageName + "PanelUI",
"PasswordFieldUI", packageName + "TextUI",
"PopupMenuSeparatorUI", packageName + "SeparatorUI",
"PopupMenuUI", packageName + "PopupMenuUI",
"ProgressBarUI", packageName + "ProgressBarUI",
"RadioButtonMenuItemUI", packageName + "MenuItemUI",
"RadioButtonUI", packageName + "ButtonUI",
"RootPaneUI", packageName + "RootPaneUI",
"ScrollBarUI", packageName + "ScrollBarUI",
"ScrollPaneUI", packageName + "ScrollPaneUI",
"SeparatorUI", packageName + "SeparatorUI",
"SliderUI", packageName + "SliderUI",
"SpinnerUI", packageName + "SpinnerUI",
"SplitPaneUI", packageName + "SplitPaneUI",
"TabbedPaneUI", packageName + "TabbedPaneUI",
"TableHeaderUI", packageName + "TableHeaderUI",
"TableUI", packageName + "TableUI",
"TextAreaUI", packageName + "TextUI",
"TextFieldUI", packageName + "TextUI",
"TextPaneUI", packageName + "TextUI",
"ToggleButtonUI", packageName + "ButtonUI",
"ToolBarSeparatorUI", packageName + "SeparatorUI",
"ToolBarUI", packageName + "ToolBarUI",
"ToolTipUI", packageName + "ToolTipUI",
"TreeUI", packageName + "TreeUI",
"ViewportUI", packageName + "ViewportUI",
};
UIDefaults table = new MultiUIDefaults(uiDefaults.length / 2, 0.75f);
table.putDefaults(uiDefaults);
return table;
}
///////////////////////////////
// Utility methods for the UI's
///////////////////////////////
/** {@collect.stats}
* Creates the <code>ComponentUI</code> objects
* required to present
* the <code>target</code> component,
* placing the objects in the <code>uis</code> vector and
* returning the
* <code>ComponentUI</code> object
* that best represents the component's UI.
* This method finds the <code>ComponentUI</code> objects
* by invoking
* <code>getDefaults().getUI(target)</code> on each
* default and auxiliary look and feel currently in use.
* The first UI object this method adds
* to the <code>uis</code> vector
* is for the default look and feel.
* <p>
* This method is invoked by the <code>createUI</code> method
* of <code>MultiXxxxUI</code> classes.
*
* @param mui the <code>ComponentUI</code> object
* that represents the complete UI
* for the <code>target</code> component;
* this should be an instance
* of one of the <code>MultiXxxxUI</code> classes
* @param uis a <code>Vector</code>;
* generally this is the <code>uis</code> field
* of the <code>mui</code> argument
* @param target a component whose UI is represented by <code>mui</code>
*
* @return <code>mui</code> if the component has any auxiliary UI objects;
* otherwise, returns the UI object for the default look and feel
* or <code>null</code> if the default UI object couldn't be found
*
* @see javax.swing.UIManager#getAuxiliaryLookAndFeels
* @see javax.swing.UIDefaults#getUI
* @see MultiButtonUI#uis
* @see MultiButtonUI#createUI
*/
public static ComponentUI createUIs(ComponentUI mui,
Vector uis,
JComponent target) {
ComponentUI ui;
// Make sure we can at least get the default UI
//
ui = UIManager.getDefaults().getUI(target);
if (ui != null) {
uis.addElement(ui);
LookAndFeel[] auxiliaryLookAndFeels;
auxiliaryLookAndFeels = UIManager.getAuxiliaryLookAndFeels();
if (auxiliaryLookAndFeels != null) {
for (int i = 0; i < auxiliaryLookAndFeels.length; i++) {
ui = auxiliaryLookAndFeels[i].getDefaults().getUI(target);
if (ui != null) {
uis.addElement(ui);
}
}
}
} else {
return null;
}
// Don't bother returning the multiplexing UI if all we did was
// get a UI from just the default look and feel.
//
if (uis.size() == 1) {
return (ComponentUI) uis.elementAt(0);
} else {
return mui;
}
}
/** {@collect.stats}
* Creates an array,
* populates it with UI objects from the passed-in vector,
* and returns the array.
* If <code>uis</code> is null,
* this method returns an array with zero elements.
* If <code>uis</code> is an empty vector,
* this method returns <code>null</code>.
* A run-time error occurs if any objects in the <code>uis</code> vector
* are not of type <code>ComponentUI</code>.
*
* @param uis a vector containing <code>ComponentUI</code> objects
* @return an array equivalent to the passed-in vector
*
*/
protected static ComponentUI[] uisToArray(Vector uis) {
if (uis == null) {
return new ComponentUI[0];
} else {
int count = uis.size();
if (count > 0) {
ComponentUI[] u = new ComponentUI[count];
for (int i = 0; i < count; i++) {
u[i] = (ComponentUI)uis.elementAt(i);
}
return u;
} else {
return null;
}
}
}
}
/** {@collect.stats}
* We want the Multiplexing LookAndFeel 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 MultiUIDefaults extends UIDefaults {
MultiUIDefaults(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
protected void getUIError(String msg) {
System.err.println("Multiplexing LAF: " + msg);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.FileChooserUI;
import javax.swing.filechooser.FileFilter;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileView;
import java.lang.String;
import java.io.File;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>FileChooserUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiFileChooserUI extends FileChooserUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// FileChooserUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>getAcceptAllFileFilter</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public FileFilter getAcceptAllFileFilter(JFileChooser a) {
FileFilter returnValue =
((FileChooserUI) (uis.elementAt(0))).getAcceptAllFileFilter(a);
for (int i = 1; i < uis.size(); i++) {
((FileChooserUI) (uis.elementAt(i))).getAcceptAllFileFilter(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getFileView</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public FileView getFileView(JFileChooser a) {
FileView returnValue =
((FileChooserUI) (uis.elementAt(0))).getFileView(a);
for (int i = 1; i < uis.size(); i++) {
((FileChooserUI) (uis.elementAt(i))).getFileView(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getApproveButtonText</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public String getApproveButtonText(JFileChooser a) {
String returnValue =
((FileChooserUI) (uis.elementAt(0))).getApproveButtonText(a);
for (int i = 1; i < uis.size(); i++) {
((FileChooserUI) (uis.elementAt(i))).getApproveButtonText(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getDialogTitle</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public String getDialogTitle(JFileChooser a) {
String returnValue =
((FileChooserUI) (uis.elementAt(0))).getDialogTitle(a);
for (int i = 1; i < uis.size(); i++) {
((FileChooserUI) (uis.elementAt(i))).getDialogTitle(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>rescanCurrentDirectory</code> method on each UI handled by this object.
*/
public void rescanCurrentDirectory(JFileChooser a) {
for (int i = 0; i < uis.size(); i++) {
((FileChooserUI) (uis.elementAt(i))).rescanCurrentDirectory(a);
}
}
/** {@collect.stats}
* Invokes the <code>ensureFileIsVisible</code> method on each UI handled by this object.
*/
public void ensureFileIsVisible(JFileChooser a, File b) {
for (int i = 0; i < uis.size(); i++) {
((FileChooserUI) (uis.elementAt(i))).ensureFileIsVisible(a,b);
}
}
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiFileChooserUI();
return MultiLookAndFeel.createUIs(mui,
((MultiFileChooserUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.ToolBarUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>ToolBarUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiToolBarUI extends ToolBarUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// ToolBarUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiToolBarUI();
return MultiLookAndFeel.createUIs(mui,
((MultiToolBarUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.DesktopIconUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>DesktopIconUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiDesktopIconUI extends DesktopIconUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// DesktopIconUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiDesktopIconUI();
return MultiLookAndFeel.createUIs(mui,
((MultiDesktopIconUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.PanelUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>PanelUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiPanelUI extends PanelUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// PanelUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiPanelUI();
return MultiLookAndFeel.createUIs(mui,
((MultiPanelUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.InternalFrameUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>InternalFrameUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiInternalFrameUI extends InternalFrameUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// InternalFrameUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiInternalFrameUI();
return MultiLookAndFeel.createUIs(mui,
((MultiInternalFrameUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.TabbedPaneUI;
import javax.swing.JTabbedPane;
import java.awt.Rectangle;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>TabbedPaneUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiTabbedPaneUI extends TabbedPaneUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// TabbedPaneUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>tabForCoordinate</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int tabForCoordinate(JTabbedPane a, int b, int c) {
int returnValue =
((TabbedPaneUI) (uis.elementAt(0))).tabForCoordinate(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((TabbedPaneUI) (uis.elementAt(i))).tabForCoordinate(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getTabBounds</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Rectangle getTabBounds(JTabbedPane a, int b) {
Rectangle returnValue =
((TabbedPaneUI) (uis.elementAt(0))).getTabBounds(a,b);
for (int i = 1; i < uis.size(); i++) {
((TabbedPaneUI) (uis.elementAt(i))).getTabBounds(a,b);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getTabRunCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getTabRunCount(JTabbedPane a) {
int returnValue =
((TabbedPaneUI) (uis.elementAt(0))).getTabRunCount(a);
for (int i = 1; i < uis.size(); i++) {
((TabbedPaneUI) (uis.elementAt(i))).getTabRunCount(a);
}
return returnValue;
}
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiTabbedPaneUI();
return MultiLookAndFeel.createUIs(mui,
((MultiTabbedPaneUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>ButtonUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiButtonUI extends ButtonUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// ButtonUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiButtonUI();
return MultiLookAndFeel.createUIs(mui,
((MultiButtonUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.ScrollBarUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>ScrollBarUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiScrollBarUI extends ScrollBarUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// ScrollBarUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiScrollBarUI();
return MultiLookAndFeel.createUIs(mui,
((MultiScrollBarUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.SplitPaneUI;
import javax.swing.JSplitPane;
import java.awt.Graphics;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>SplitPaneUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiSplitPaneUI extends SplitPaneUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// SplitPaneUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>resetToPreferredSizes</code> method on each UI handled by this object.
*/
public void resetToPreferredSizes(JSplitPane a) {
for (int i = 0; i < uis.size(); i++) {
((SplitPaneUI) (uis.elementAt(i))).resetToPreferredSizes(a);
}
}
/** {@collect.stats}
* Invokes the <code>setDividerLocation</code> method on each UI handled by this object.
*/
public void setDividerLocation(JSplitPane a, int b) {
for (int i = 0; i < uis.size(); i++) {
((SplitPaneUI) (uis.elementAt(i))).setDividerLocation(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getDividerLocation</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getDividerLocation(JSplitPane a) {
int returnValue =
((SplitPaneUI) (uis.elementAt(0))).getDividerLocation(a);
for (int i = 1; i < uis.size(); i++) {
((SplitPaneUI) (uis.elementAt(i))).getDividerLocation(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumDividerLocation</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getMinimumDividerLocation(JSplitPane a) {
int returnValue =
((SplitPaneUI) (uis.elementAt(0))).getMinimumDividerLocation(a);
for (int i = 1; i < uis.size(); i++) {
((SplitPaneUI) (uis.elementAt(i))).getMinimumDividerLocation(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumDividerLocation</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getMaximumDividerLocation(JSplitPane a) {
int returnValue =
((SplitPaneUI) (uis.elementAt(0))).getMaximumDividerLocation(a);
for (int i = 1; i < uis.size(); i++) {
((SplitPaneUI) (uis.elementAt(i))).getMaximumDividerLocation(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>finishedPaintingChildren</code> method on each UI handled by this object.
*/
public void finishedPaintingChildren(JSplitPane a, Graphics b) {
for (int i = 0; i < uis.size(); i++) {
((SplitPaneUI) (uis.elementAt(i))).finishedPaintingChildren(a,b);
}
}
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiSplitPaneUI();
return MultiLookAndFeel.createUIs(mui,
((MultiSplitPaneUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 2001, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.SpinnerUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/** {@collect.stats}
* A multiplexing UI used to combine <code>SpinnerUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
* @since 1.4
*/
public class MultiSpinnerUI extends SpinnerUI {
/** {@collect.stats}
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/** {@collect.stats}
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// SpinnerUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/** {@collect.stats}
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/** {@collect.stats}
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiSpinnerUI();
return MultiLookAndFeel.createUIs(mui,
((MultiSpinnerUI) mui).uis,
a);
}
/** {@collect.stats}
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/** {@collect.stats}
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/** {@collect.stats}
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/** {@collect.stats}
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf;
/** {@collect.stats}
* Pluggable look and feel interface for JProgressBar.
*
* @author Rob Davis
*/
public abstract class ProgressBarUI extends ComponentUI {
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf;
import java.awt.Rectangle;
import javax.swing.JTabbedPane;
/** {@collect.stats}
* Pluggable look and feel interface for JTabbedPane.
*
* @author Dave Moore
* @author Amy Fowler
*/
public abstract class TabbedPaneUI extends ComponentUI {
public abstract int tabForCoordinate(JTabbedPane pane, int x, int y);
public abstract Rectangle getTabBounds(JTabbedPane pane, int index);
public abstract int getTabRunCount(JTabbedPane pane);
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf;
import javax.swing.JOptionPane;
/** {@collect.stats}
* Pluggable look and feel interface for JOptionPane.
*
* @author Scott Violet
*/
public abstract class OptionPaneUI extends ComponentUI
{
/** {@collect.stats}
* Requests the component representing the default value to have
* focus.
*/
public abstract void selectInitialValue(JOptionPane op);
/** {@collect.stats}
* Returns true if the user has supplied instances of Component for
* either the options or message.
*/
public abstract boolean containsCustomComponents(JOptionPane op);
}
|
Java
|
/*
* Copyright (c) 1997, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileView;
import java.io.File;
/** {@collect.stats}
* Pluggable look and feel interface for <code>JFileChooser</code>.
*
* @author Jeff Dinkins
*/
public abstract class FileChooserUI extends ComponentUI
{
public abstract FileFilter getAcceptAllFileFilter(JFileChooser fc);
public abstract FileView getFileView(JFileChooser fc);
public abstract String getApproveButtonText(JFileChooser fc);
public abstract String getDialogTitle(JFileChooser fc);
public abstract void rescanCurrentDirectory(JFileChooser fc);
public abstract void ensureFileIsVisible(JFileChooser fc, File f);
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf;
import java.awt.Insets;
import javax.swing.plaf.UIResource;
/*
* A subclass of Insets that implements UIResource. UI
* classes that use Insets values for default properties
* should use this class.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see javax.swing.plaf.UIResource
* @author Amy Fowler
*
*/
public class InsetsUIResource extends Insets implements UIResource
{
public InsetsUIResource(int top, int left, int bottom, int right) {
super(top, left, bottom, right);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* An implementation of a check box -- an item that can be selected or
* deselected, and which displays its state to the user.
* By convention, any number of check boxes in a group can be selected.
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/button.html">How to Use Buttons, Check Boxes, and Radio Buttons</a>
* in <em>The Java Tutorial</em>
* for examples and information on using check boxes.
* <p>
* Buttons can be configured, and to some degree controlled, by
* <code><a href="Action.html">Action</a></code>s. Using an
* <code>Action</code> with a button has many benefits beyond directly
* configuring a button. Refer to <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for more
* details, and you can find more information in <a
* href="http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html">How
* to Use Actions</a>, a section in <em>The Java Tutorial</em>.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see JRadioButton
*
* @beaninfo
* attribute: isContainer false
* description: A component which can be selected or deselected.
*
* @author Jeff Dinkins
*/
public class JCheckBox extends JToggleButton implements Accessible {
/** {@collect.stats} Identifies a change to the flat property. */
public static final String BORDER_PAINTED_FLAT_CHANGED_PROPERTY = "borderPaintedFlat";
private boolean flat = false;
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "CheckBoxUI";
/** {@collect.stats}
* Creates an initially unselected check box button with no text, no icon.
*/
public JCheckBox () {
this(null, null, false);
}
/** {@collect.stats}
* Creates an initially unselected check box with an icon.
*
* @param icon the Icon image to display
*/
public JCheckBox(Icon icon) {
this(null, icon, false);
}
/** {@collect.stats}
* Creates a check box with an icon and specifies whether
* or not it is initially selected.
*
* @param icon the Icon image to display
* @param selected a boolean value indicating the initial selection
* state. If <code>true</code> the check box is selected
*/
public JCheckBox(Icon icon, boolean selected) {
this(null, icon, selected);
}
/** {@collect.stats}
* Creates an initially unselected check box with text.
*
* @param text the text of the check box.
*/
public JCheckBox (String text) {
this(text, null, false);
}
/** {@collect.stats}
* Creates a check box where properties are taken from the
* Action supplied.
*
* @since 1.3
*/
public JCheckBox(Action a) {
this();
setAction(a);
}
/** {@collect.stats}
* Creates a check box with text and specifies whether
* or not it is initially selected.
*
* @param text the text of the check box.
* @param selected a boolean value indicating the initial selection
* state. If <code>true</code> the check box is selected
*/
public JCheckBox (String text, boolean selected) {
this(text, null, selected);
}
/** {@collect.stats}
* Creates an initially unselected check box with
* the specified text and icon.
*
* @param text the text of the check box.
* @param icon the Icon image to display
*/
public JCheckBox(String text, Icon icon) {
this(text, icon, false);
}
/** {@collect.stats}
* Creates a check box with text and icon,
* and specifies whether or not it is initially selected.
*
* @param text the text of the check box.
* @param icon the Icon image to display
* @param selected a boolean value indicating the initial selection
* state. If <code>true</code> the check box is selected
*/
public JCheckBox (String text, Icon icon, boolean selected) {
super(text, icon, selected);
setUIProperty("borderPainted", Boolean.FALSE);
setHorizontalAlignment(LEADING);
}
/** {@collect.stats}
* Sets the <code>borderPaintedFlat</code> property,
* which gives a hint to the look and feel as to the
* appearance of the check box border.
* This is usually set to <code>true</code> when a
* <code>JCheckBox</code> instance is used as a
* renderer in a component such as a <code>JTable</code> or
* <code>JTree</code>. The default value for the
* <code>borderPaintedFlat</code> property is <code>false</code>.
* This method fires a property changed event.
* Some look and feels might not implement flat borders;
* they will ignore this property.
*
* @param b <code>true</code> requests that the border be painted flat;
* <code>false</code> requests normal borders
* @see #isBorderPaintedFlat
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether the border is painted flat.
* @since 1.3
*/
public void setBorderPaintedFlat(boolean b) {
boolean oldValue = flat;
flat = b;
firePropertyChange(BORDER_PAINTED_FLAT_CHANGED_PROPERTY, oldValue, flat);
if (b != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Gets the value of the <code>borderPaintedFlat</code> property.
*
* @return the value of the <code>borderPaintedFlat</code> property
* @see #setBorderPaintedFlat
* @since 1.3
*/
public boolean isBorderPaintedFlat() {
return flat;
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((ButtonUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns a string that specifies the name of the L&F class
* that renders this component.
*
* @return the string "CheckBoxUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
* @beaninfo
* expert: true
* description: A string that specifies the name of the L&F class
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* The icon for checkboxs comes from the look and feel,
* not the Action; this is overriden to do nothing.
*/
void setIconFromAction(Action a) {
}
/*
* See readObject and writeObject in JComponent for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* See JComponent.readObject() for information about serialization
* in Swing.
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
if (getUIClassID().equals(uiClassID)) {
updateUI();
}
}
/** {@collect.stats}
* Returns a string representation of this JCheckBox. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
* specific new aspects of the JFC components.
*
* @return a string representation of this JCheckBox.
*/
protected String paramString() {
return super.paramString();
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JCheckBox.
* For JCheckBoxes, the AccessibleContext takes the form of an
* AccessibleJCheckBox.
* A new AccessibleJCheckBox instance is created if necessary.
*
* @return an AccessibleJCheckBox that serves as the
* AccessibleContext of this JCheckBox
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this CheckBox.
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJCheckBox();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JCheckBox</code> class. It provides an implementation of the
* Java Accessibility API appropriate to check box user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJCheckBox extends AccessibleJToggleButton {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.CHECK_BOX;
}
} // inner class AccessibleJCheckBox
}
|
Java
|
/*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
/** {@collect.stats}
* Any component that can be placed into a menu should implement this interface.
* This interface is used by <code>MenuSelectionManager</code>
* to handle selection and navigation in menu hierarchies.
*
* @author Arnaud Weber
*/
public interface MenuElement {
/** {@collect.stats}
* Processes a mouse event. <code>event</code> is a <code>MouseEvent</code>
* with source being the receiving element's component.
* <code>path</code> is the path of the receiving element in the menu
* hierarchy including the receiving element itself.
* <code>manager</code> is the <code>MenuSelectionManager</code>
* for the menu hierarchy.
* This method should process the <code>MouseEvent</code> and change
* the menu selection if necessary
* by using <code>MenuSelectionManager</code>'s API
* Note: you do not have to forward the event to sub-components.
* This is done automatically by the <code>MenuSelectionManager</code>.
*/
public void processMouseEvent(MouseEvent event,MenuElement path[],MenuSelectionManager manager);
/** {@collect.stats}
* Process a key event.
*/
public void processKeyEvent(KeyEvent event,MenuElement path[],MenuSelectionManager manager);
/** {@collect.stats}
* Call by the <code>MenuSelectionManager</code> when the
* <code>MenuElement</code> is added or remove from
* the menu selection.
*/
public void menuSelectionChanged(boolean isIncluded);
/** {@collect.stats}
* This method should return an array containing the sub-elements for the receiving menu element
*
* @return an array of MenuElements
*/
public MenuElement[] getSubElements();
/** {@collect.stats}
* This method should return the java.awt.Component used to paint the receiving element.
* The returned component will be used to convert events and detect if an event is inside
* a MenuElement's component.
*
* @return the Component value
*/
public Component getComponent();
}
|
Java
|
/*
* Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static javax.swing.ClientPropertyKey.PopupFactory_FORCE_HEAVYWEIGHT_POPUP;
/** {@collect.stats}
* <code>PopupFactory</code>, as the name implies, is used to obtain
* instances of <code>Popup</code>s. <code>Popup</code>s are used to
* display a <code>Component</code> above all other <code>Component</code>s
* in a particular containment hierarchy. The general contract is that
* once you have obtained a <code>Popup</code> from a
* <code>PopupFactory</code>, you must invoke <code>hide</code> on the
* <code>Popup</code>. The typical usage is:
* <pre>
* PopupFactory factory = PopupFactory.getSharedInstance();
* Popup popup = factory.getPopup(owner, contents, x, y);
* popup.show();
* ...
* popup.hide();
* </pre>
*
* @see Popup
*
* @since 1.4
*/
public class PopupFactory {
/** {@collect.stats}
* The shared instanceof <code>PopupFactory</code> is per
* <code>AppContext</code>. This is the key used in the
* <code>AppContext</code> to locate the <code>PopupFactory</code>.
*/
private static final Object SharedInstanceKey = new Object(); // PopupFactory.SharedInstanceKey
/** {@collect.stats}
* Max number of items to store in any one particular cache.
*/
private static final int MAX_CACHE_SIZE = 5;
/** {@collect.stats}
* Key used to indicate a light weight popup should be used.
*/
static final int LIGHT_WEIGHT_POPUP = 0;
/** {@collect.stats}
* Key used to indicate a medium weight Popup should be used.
*/
static final int MEDIUM_WEIGHT_POPUP = 1;
/*
* Key used to indicate a heavy weight Popup should be used.
*/
static final int HEAVY_WEIGHT_POPUP = 2;
/** {@collect.stats}
* Default type of Popup to create.
*/
private int popupType = LIGHT_WEIGHT_POPUP;
/** {@collect.stats}
* Sets the <code>PopupFactory</code> that will be used to obtain
* <code>Popup</code>s.
* This will throw an <code>IllegalArgumentException</code> if
* <code>factory</code> is null.
*
* @param factory Shared PopupFactory
* @exception IllegalArgumentException if <code>factory</code> is null
* @see #getPopup
*/
public static void setSharedInstance(PopupFactory factory) {
if (factory == null) {
throw new IllegalArgumentException("PopupFactory can not be null");
}
SwingUtilities.appContextPut(SharedInstanceKey, factory);
}
/** {@collect.stats}
* Returns the shared <code>PopupFactory</code> which can be used
* to obtain <code>Popup</code>s.
*
* @return Shared PopupFactory
*/
public static PopupFactory getSharedInstance() {
PopupFactory factory = (PopupFactory)SwingUtilities.appContextGet(
SharedInstanceKey);
if (factory == null) {
factory = new PopupFactory();
setSharedInstance(factory);
}
return factory;
}
/** {@collect.stats}
* Provides a hint as to the type of <code>Popup</code> that should
* be created.
*/
void setPopupType(int type) {
popupType = type;
}
/** {@collect.stats}
* Returns the preferred type of Popup to create.
*/
int getPopupType() {
return popupType;
}
/** {@collect.stats}
* Creates a <code>Popup</code> for the Component <code>owner</code>
* containing the Component <code>contents</code>. <code>owner</code>
* is used to determine which <code>Window</code> the new
* <code>Popup</code> will parent the <code>Component</code> the
* <code>Popup</code> creates to. A null <code>owner</code> implies there
* is no valid parent. <code>x</code> and
* <code>y</code> specify the preferred initial location to place
* the <code>Popup</code> at. Based on screen size, or other paramaters,
* the <code>Popup</code> may not display at <code>x</code> and
* <code>y</code>.
*
* @param owner Component mouse coordinates are relative to, may be null
* @param contents Contents of the Popup
* @param x Initial x screen coordinate
* @param y Initial y screen coordinate
* @exception IllegalArgumentException if contents is null
* @return Popup containing Contents
*/
public Popup getPopup(Component owner, Component contents,
int x, int y) throws IllegalArgumentException {
if (contents == null) {
throw new IllegalArgumentException(
"Popup.getPopup must be passed non-null contents");
}
int popupType = getPopupType(owner, contents, x, y);
Popup popup = getPopup(owner, contents, x, y, popupType);
if (popup == null) {
// Didn't fit, force to heavy.
popup = getPopup(owner, contents, x, y, HEAVY_WEIGHT_POPUP);
}
return popup;
}
/** {@collect.stats}
* Returns the popup type to use for the specified parameters.
*/
private int getPopupType(Component owner, Component contents,
int ownerX, int ownerY) {
int popupType = getPopupType();
if (owner == null || invokerInHeavyWeightPopup(owner)) {
popupType = HEAVY_WEIGHT_POPUP;
}
else if (popupType == LIGHT_WEIGHT_POPUP &&
!(contents instanceof JToolTip) &&
!(contents instanceof JPopupMenu)) {
popupType = MEDIUM_WEIGHT_POPUP;
}
// Check if the parent component is an option pane. If so we need to
// force a heavy weight popup in order to have event dispatching work
// correctly.
Component c = owner;
while (c != null) {
if (c instanceof JComponent) {
if (((JComponent)c).getClientProperty(
PopupFactory_FORCE_HEAVYWEIGHT_POPUP) == Boolean.TRUE) {
popupType = HEAVY_WEIGHT_POPUP;
break;
}
}
c = c.getParent();
}
return popupType;
}
/** {@collect.stats}
* Obtains the appropriate <code>Popup</code> based on
* <code>popupType</code>.
*/
private Popup getPopup(Component owner, Component contents,
int ownerX, int ownerY, int popupType) {
if (GraphicsEnvironment.isHeadless()) {
return getHeadlessPopup(owner, contents, ownerX, ownerY);
}
switch(popupType) {
case LIGHT_WEIGHT_POPUP:
return getLightWeightPopup(owner, contents, ownerX, ownerY);
case MEDIUM_WEIGHT_POPUP:
return getMediumWeightPopup(owner, contents, ownerX, ownerY);
case HEAVY_WEIGHT_POPUP:
return getHeavyWeightPopup(owner, contents, ownerX, ownerY);
}
return null;
}
/** {@collect.stats}
* Creates a headless popup
*/
private Popup getHeadlessPopup(Component owner, Component contents,
int ownerX, int ownerY) {
return HeadlessPopup.getHeadlessPopup(owner, contents, ownerX, ownerY);
}
/** {@collect.stats}
* Creates a light weight popup.
*/
private Popup getLightWeightPopup(Component owner, Component contents,
int ownerX, int ownerY) {
return LightWeightPopup.getLightWeightPopup(owner, contents, ownerX,
ownerY);
}
/** {@collect.stats}
* Creates a medium weight popup.
*/
private Popup getMediumWeightPopup(Component owner, Component contents,
int ownerX, int ownerY) {
return MediumWeightPopup.getMediumWeightPopup(owner, contents,
ownerX, ownerY);
}
/** {@collect.stats}
* Creates a heavy weight popup.
*/
private Popup getHeavyWeightPopup(Component owner, Component contents,
int ownerX, int ownerY) {
if (GraphicsEnvironment.isHeadless()) {
return getMediumWeightPopup(owner, contents, ownerX, ownerY);
}
return HeavyWeightPopup.getHeavyWeightPopup(owner, contents, ownerX,
ownerY);
}
/** {@collect.stats}
* Returns true if the Component <code>i</code> inside a heavy weight
* <code>Popup</code>.
*/
private boolean invokerInHeavyWeightPopup(Component i) {
if (i != null) {
Container parent;
for(parent = i.getParent() ; parent != null ; parent =
parent.getParent()) {
if (parent instanceof Popup.HeavyWeightWindow) {
return true;
}
}
}
return false;
}
/** {@collect.stats}
* Popup implementation that uses a Window as the popup.
*/
private static class HeavyWeightPopup extends Popup {
private static final Object heavyWeightPopupCacheKey = new Object(); // PopupFactory.heavyWeightPopupCache
/** {@collect.stats}
* Returns either a new or recycled <code>Popup</code> containing
* the specified children.
*/
static Popup getHeavyWeightPopup(Component owner, Component contents,
int ownerX, int ownerY) {
Window window = (owner != null) ? SwingUtilities.
getWindowAncestor(owner) : null;
HeavyWeightPopup popup = null;
if (window != null) {
popup = getRecycledHeavyWeightPopup(window);
}
boolean focusPopup = false;
if(contents != null && contents.isFocusable()) {
if(contents instanceof JPopupMenu) {
JPopupMenu jpm = (JPopupMenu) contents;
Component popComps[] = jpm.getComponents();
for(int i=0;i<popComps.length;i++) {
if(!(popComps[i] instanceof MenuElement) &&
!(popComps[i] instanceof JSeparator)) {
focusPopup = true;
break;
}
}
}
}
if (popup == null ||
((JWindow) popup.getComponent())
.getFocusableWindowState() != focusPopup) {
if(popup != null) {
// The recycled popup can't serve us well
// dispose it and create new one
popup._dispose();
}
popup = new HeavyWeightPopup();
}
popup.reset(owner, contents, ownerX, ownerY);
if(focusPopup) {
JWindow wnd = (JWindow) popup.getComponent();
wnd.setFocusableWindowState(true);
// Set window name. We need this in BasicPopupMenuUI
// to identify focusable popup window.
wnd.setName("###focusableSwingPopup###");
}
return popup;
}
/** {@collect.stats}
* Returns a previously disposed heavy weight <code>Popup</code>
* associated with <code>window</code>. This will return null if
* there is no <code>HeavyWeightPopup</code> associated with
* <code>window</code>.
*/
private static HeavyWeightPopup getRecycledHeavyWeightPopup(Window w) {
synchronized (HeavyWeightPopup.class) {
List cache;
Map heavyPopupCache = getHeavyWeightPopupCache();
if (heavyPopupCache.containsKey(w)) {
cache = (List)heavyPopupCache.get(w);
} else {
return null;
}
int c;
if ((c = cache.size()) > 0) {
HeavyWeightPopup r = (HeavyWeightPopup)cache.get(0);
cache.remove(0);
return r;
}
return null;
}
}
/** {@collect.stats}
* Returns the cache to use for heavy weight popups. Maps from
* <code>Window</code> to a <code>List</code> of
* <code>HeavyWeightPopup</code>s.
*/
private static Map getHeavyWeightPopupCache() {
synchronized (HeavyWeightPopup.class) {
Map cache = (Map)SwingUtilities.appContextGet(
heavyWeightPopupCacheKey);
if (cache == null) {
cache = new HashMap(2);
SwingUtilities.appContextPut(heavyWeightPopupCacheKey,
cache);
}
return cache;
}
}
/** {@collect.stats}
* Recycles the passed in <code>HeavyWeightPopup</code>.
*/
private static void recycleHeavyWeightPopup(HeavyWeightPopup popup) {
synchronized (HeavyWeightPopup.class) {
List cache;
Object window = SwingUtilities.getWindowAncestor(
popup.getComponent());
Map heavyPopupCache = getHeavyWeightPopupCache();
if (window instanceof Popup.DefaultFrame ||
!((Window)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
// there wasn't a valid Window parent, and thus we don't
// know when to clean up.
popup._dispose();
return;
} else if (heavyPopupCache.containsKey(window)) {
cache = (List)heavyPopupCache.get(window);
} else {
cache = new ArrayList();
heavyPopupCache.put(window, cache);
// Clean up if the Window is closed
final Window w = (Window)window;
w.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
List popups;
synchronized(HeavyWeightPopup.class) {
Map heavyPopupCache2 =
getHeavyWeightPopupCache();
popups = (List)heavyPopupCache2.remove(w);
}
if (popups != null) {
for (int counter = popups.size() - 1;
counter >= 0; counter--) {
((HeavyWeightPopup)popups.get(counter)).
_dispose();
}
}
}
});
}
if(cache.size() < MAX_CACHE_SIZE) {
cache.add(popup);
} else {
popup._dispose();
}
}
}
//
// Popup methods
//
public void hide() {
super.hide();
recycleHeavyWeightPopup(this);
}
/** {@collect.stats}
* As we recycle the <code>Window</code>, we don't want to dispose it,
* thus this method does nothing, instead use <code>_dipose</code>
* which will handle the disposing.
*/
void dispose() {
}
void _dispose() {
super.dispose();
}
}
/** {@collect.stats}
* ContainerPopup consolidates the common code used in the light/medium
* weight implementations of <code>Popup</code>.
*/
private static class ContainerPopup extends Popup {
/** {@collect.stats} Component we are to be added to. */
Component owner;
/** {@collect.stats} Desired x location. */
int x;
/** {@collect.stats} Desired y location. */
int y;
public void hide() {
Component component = getComponent();
if (component != null) {
Container parent = component.getParent();
if (parent != null) {
Rectangle bounds = component.getBounds();
parent.remove(component);
parent.repaint(bounds.x, bounds.y, bounds.width,
bounds.height);
}
}
owner = null;
}
public void pack() {
Component component = getComponent();
if (component != null) {
component.setSize(component.getPreferredSize());
}
}
void reset(Component owner, Component contents, int ownerX,
int ownerY) {
if ((owner instanceof JFrame) || (owner instanceof JDialog) ||
(owner instanceof JWindow)) {
// Force the content to be added to the layered pane, otherwise
// we'll get an exception when adding to the RootPaneContainer.
owner = ((RootPaneContainer)owner).getLayeredPane();
}
super.reset(owner, contents, ownerX, ownerY);
x = ownerX;
y = ownerY;
this.owner = owner;
}
boolean overlappedByOwnedWindow() {
Component component = getComponent();
if(owner != null && component != null) {
Window w = SwingUtilities.getWindowAncestor(owner);
if (w == null) {
return false;
}
Window[] ownedWindows = w.getOwnedWindows();
if(ownedWindows != null) {
Rectangle bnd = component.getBounds();
for(int i=0; i<ownedWindows.length;i++) {
Window owned = ownedWindows[i];
if (owned.isVisible() &&
bnd.intersects(owned.getBounds())) {
return true;
}
}
}
}
return false;
}
/** {@collect.stats}
* Returns true if the Popup can fit on the screen.
*/
boolean fitsOnScreen() {
Component component = getComponent();
if (owner != null && component != null) {
Container parent;
int width = component.getWidth();
int height = component.getHeight();
for(parent = owner.getParent(); parent != null ;
parent = parent.getParent()) {
if (parent instanceof JFrame ||
parent instanceof JDialog ||
parent instanceof JWindow) {
Rectangle r = parent.getBounds();
Insets i = parent.getInsets();
r.x += i.left;
r.y += i.top;
r.width -= (i.left + i.right);
r.height -= (i.top + i.bottom);
GraphicsConfiguration gc = parent.getGraphicsConfiguration();
Rectangle popupArea = getContainerPopupArea(gc);
return r.intersection(popupArea).contains(x, y, width, height);
} else if (parent instanceof JApplet) {
Rectangle r = parent.getBounds();
Point p = parent.getLocationOnScreen();
r.x = p.x;
r.y = p.y;
return r.contains(x, y, width, height);
} else if (parent instanceof Window ||
parent instanceof Applet) {
// No suitable swing component found
break;
}
}
}
return false;
}
Rectangle getContainerPopupArea(GraphicsConfiguration gc) {
Rectangle screenBounds;
Toolkit toolkit = Toolkit.getDefaultToolkit();
Insets insets;
if(gc != null) {
// If we have GraphicsConfiguration use it
// to get screen bounds
screenBounds = gc.getBounds();
insets = toolkit.getScreenInsets(gc);
} else {
// If we don't have GraphicsConfiguration use primary screen
screenBounds = new Rectangle(toolkit.getScreenSize());
insets = new Insets(0, 0, 0, 0);
}
// Take insets into account
screenBounds.x += insets.left;
screenBounds.y += insets.top;
screenBounds.width -= (insets.left + insets.right);
screenBounds.height -= (insets.top + insets.bottom);
return screenBounds;
}
}
/** {@collect.stats}
* Popup implementation that is used in headless environment.
*/
private static class HeadlessPopup extends ContainerPopup {
static Popup getHeadlessPopup(Component owner, Component contents,
int ownerX, int ownerY) {
HeadlessPopup popup = new HeadlessPopup();
popup.reset(owner, contents, ownerX, ownerY);
return popup;
}
Component createComponent(Component owner) {
return new Panel(new BorderLayout());
}
public void show() {
}
public void hide() {
}
}
/** {@collect.stats}
* Popup implementation that uses a JPanel as the popup.
*/
private static class LightWeightPopup extends ContainerPopup {
private static final Object lightWeightPopupCacheKey = new Object(); // PopupFactory.lightPopupCache
/** {@collect.stats}
* Returns a light weight <code>Popup</code> implementation. If
* the <code>Popup</code> needs more space that in available in
* <code>owner</code>, this will return null.
*/
static Popup getLightWeightPopup(Component owner, Component contents,
int ownerX, int ownerY) {
LightWeightPopup popup = getRecycledLightWeightPopup();
if (popup == null) {
popup = new LightWeightPopup();
}
popup.reset(owner, contents, ownerX, ownerY);
if (!popup.fitsOnScreen() ||
popup.overlappedByOwnedWindow()) {
popup.hide();
return null;
}
return popup;
}
/** {@collect.stats}
* Returns the cache to use for heavy weight popups.
*/
private static List getLightWeightPopupCache() {
List cache = (List)SwingUtilities.appContextGet(
lightWeightPopupCacheKey);
if (cache == null) {
cache = new ArrayList();
SwingUtilities.appContextPut(lightWeightPopupCacheKey, cache);
}
return cache;
}
/** {@collect.stats}
* Recycles the LightWeightPopup <code>popup</code>.
*/
private static void recycleLightWeightPopup(LightWeightPopup popup) {
synchronized (LightWeightPopup.class) {
List lightPopupCache = getLightWeightPopupCache();
if (lightPopupCache.size() < MAX_CACHE_SIZE) {
lightPopupCache.add(popup);
}
}
}
/** {@collect.stats}
* Returns a previously used <code>LightWeightPopup</code>, or null
* if none of the popups have been recycled.
*/
private static LightWeightPopup getRecycledLightWeightPopup() {
synchronized (LightWeightPopup.class) {
List lightPopupCache = getLightWeightPopupCache();
int c;
if((c = lightPopupCache.size()) > 0) {
LightWeightPopup r = (LightWeightPopup)lightPopupCache.
get(0);
lightPopupCache.remove(0);
return r;
}
return null;
}
}
//
// Popup methods
//
public void hide() {
super.hide();
Container component = (Container)getComponent();
component.removeAll();
recycleLightWeightPopup(this);
}
public void show() {
Container parent = null;
if (owner != null) {
parent = (owner instanceof Container? (Container)owner : owner.getParent());
}
// Try to find a JLayeredPane and Window to add
for (Container p = parent; p != null; p = p.getParent()) {
if (p instanceof JRootPane) {
if (p.getParent() instanceof JInternalFrame) {
continue;
}
parent = ((JRootPane)p).getLayeredPane();
// Continue, so that if there is a higher JRootPane, we'll
// pick it up.
} else if(p instanceof Window) {
if (parent == null) {
parent = p;
}
break;
} else if (p instanceof JApplet) {
// Painting code stops at Applets, we don't want
// to add to a Component above an Applet otherwise
// you'll never see it painted.
break;
}
}
Point p = SwingUtilities.convertScreenLocationToParent(parent, x,
y);
Component component = getComponent();
component.setLocation(p.x, p.y);
if (parent instanceof JLayeredPane) {
((JLayeredPane)parent).add(component,
JLayeredPane.POPUP_LAYER, 0);
} else {
parent.add(component);
}
}
Component createComponent(Component owner) {
JComponent component = new JPanel(new BorderLayout(), true);
component.setOpaque(true);
return component;
}
//
// Local methods
//
/** {@collect.stats}
* Resets the <code>Popup</code> to an initial state.
*/
void reset(Component owner, Component contents, int ownerX,
int ownerY) {
super.reset(owner, contents, ownerX, ownerY);
JComponent component = (JComponent)getComponent();
component.setOpaque(contents.isOpaque());
component.setLocation(ownerX, ownerY);
component.add(contents, BorderLayout.CENTER);
contents.invalidate();
pack();
}
}
/** {@collect.stats}
* Popup implementation that uses a Panel as the popup.
*/
private static class MediumWeightPopup extends ContainerPopup {
private static final Object mediumWeightPopupCacheKey = new Object(); // PopupFactory.mediumPopupCache
/** {@collect.stats} Child of the panel. The contents are added to this. */
private JRootPane rootPane;
/** {@collect.stats}
* Returns a medium weight <code>Popup</code> implementation. If
* the <code>Popup</code> needs more space that in available in
* <code>owner</code>, this will return null.
*/
static Popup getMediumWeightPopup(Component owner, Component contents,
int ownerX, int ownerY) {
MediumWeightPopup popup = getRecycledMediumWeightPopup();
if (popup == null) {
popup = new MediumWeightPopup();
}
popup.reset(owner, contents, ownerX, ownerY);
if (!popup.fitsOnScreen() ||
popup.overlappedByOwnedWindow()) {
popup.hide();
return null;
}
return popup;
}
/** {@collect.stats}
* Returns the cache to use for medium weight popups.
*/
private static List getMediumWeightPopupCache() {
List cache = (List)SwingUtilities.appContextGet(
mediumWeightPopupCacheKey);
if (cache == null) {
cache = new ArrayList();
SwingUtilities.appContextPut(mediumWeightPopupCacheKey, cache);
}
return cache;
}
/** {@collect.stats}
* Recycles the MediumWeightPopup <code>popup</code>.
*/
private static void recycleMediumWeightPopup(MediumWeightPopup popup) {
synchronized (MediumWeightPopup.class) {
List mediumPopupCache = getMediumWeightPopupCache();
if (mediumPopupCache.size() < MAX_CACHE_SIZE) {
mediumPopupCache.add(popup);
}
}
}
/** {@collect.stats}
* Returns a previously used <code>MediumWeightPopup</code>, or null
* if none of the popups have been recycled.
*/
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);
mediumPopupCache.remove(0);
return r;
}
return null;
}
}
//
// Popup
//
public void hide() {
super.hide();
rootPane.getContentPane().removeAll();
recycleMediumWeightPopup(this);
}
public void show() {
Component component = getComponent();
Container parent = null;
if (owner != null) {
parent = owner.getParent();
}
/*
Find the top level window,
if it has a layered pane,
add to that, otherwise
add to the window. */
while (!(parent instanceof Window || parent instanceof Applet) &&
(parent!=null)) {
parent = parent.getParent();
}
// Set the visibility to false before adding to workaround a
// bug in Solaris in which the Popup gets added at the wrong
// location, which will result in a mouseExit, which will then
// result in the ToolTip being removed.
if (parent instanceof RootPaneContainer) {
parent = ((RootPaneContainer)parent).getLayeredPane();
Point p = SwingUtilities.convertScreenLocationToParent(parent,
x, y);
component.setVisible(false);
component.setLocation(p.x, p.y);
((JLayeredPane)parent).add(component, JLayeredPane.POPUP_LAYER,
0);
} else {
Point p = SwingUtilities.convertScreenLocationToParent(parent,
x, y);
component.setLocation(p.x, p.y);
component.setVisible(false);
parent.add(component);
}
component.setVisible(true);
}
Component createComponent(Component owner) {
Panel component = new MediumWeightComponent();
rootPane = new JRootPane();
// NOTE: this uses setOpaque vs LookAndFeel.installProperty as
// there is NO reason for the RootPane not to be opaque. For
// painting to work the contentPane must be opaque, therefor the
// RootPane can also be opaque.
rootPane.setOpaque(true);
component.add(rootPane, BorderLayout.CENTER);
return component;
}
/** {@collect.stats}
* Resets the <code>Popup</code> to an initial state.
*/
void reset(Component owner, Component contents, int ownerX,
int ownerY) {
super.reset(owner, contents, ownerX, ownerY);
Component component = getComponent();
component.setLocation(ownerX, ownerY);
rootPane.getContentPane().add(contents, BorderLayout.CENTER);
contents.invalidate();
component.validate();
pack();
}
// This implements SwingHeavyWeight so that repaints on it
// are processed by the RepaintManager and SwingPaintEventDispatcher.
private static class MediumWeightComponent extends Panel implements
SwingHeavyWeight {
MediumWeightComponent() {
super(new BorderLayout());
}
}
}
}
|
Java
|
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.lang.reflect.*;
import java.lang.ref.WeakReference;
import java.security.AccessController;
import java.util.*;
import java.util.logging.*;
import sun.awt.SubRegionShowable;
import sun.java2d.SunGraphics2D;
import sun.security.action.GetPropertyAction;
/** {@collect.stats}
* A PaintManager implementation that uses a BufferStrategy for
* rendering.
*
* @author Scott Violet
*/
class BufferStrategyPaintManager extends RepaintManager.PaintManager {
//
// All drawing is done to a BufferStrategy. At the end of painting
// (endPaint) the region that was painted is flushed to the screen
// (using BufferStrategy.show).
//
// PaintManager.show is overriden to show directly from the
// BufferStrategy (when using blit), if successful true is
// returned and a paint event will not be generated. To avoid
// showing from the buffer while painting a locking scheme is
// implemented. When beginPaint is invoked the field painting is
// set to true. If painting is true and show is invoked we
// immediately return false. This is done to avoid blocking the
// toolkit thread while painting happens. In a similar way when
// show is invoked the field showing is set to true, beginPaint
// will then block until showing is true. This scheme ensures we
// only ever have one thread using the BufferStrategy and it also
// ensures the toolkit thread remains as responsive as possible.
//
// If we're using a flip strategy the contents of the backbuffer may
// have changed and so show only attempts to show from the backbuffer
// if we get a blit strategy.
//
//
// Methods used to create BufferStrategy for Applets.
//
private static Method COMPONENT_CREATE_BUFFER_STRATEGY_METHOD;
private static Method COMPONENT_GET_BUFFER_STRATEGY_METHOD;
/** {@collect.stats}
* Indicates whether or not we should try and get a flip buffer strategy
* first, default is false.
*/
private static boolean TRY_FLIP;
private static final Logger LOGGER = Logger.getLogger(
"javax.swing.BufferStrategyPaintManager");
/** {@collect.stats}
* List of BufferInfos. We don't use a Map primarily because
* there are typically only a handful of top level components making
* a Map overkill.
*/
private ArrayList<BufferInfo> bufferInfos;
/** {@collect.stats}
* Indicates <code>beginPaint</code> has been invoked. This is
* set to true for the life of beginPaint/endPaint pair.
*/
private boolean painting;
/** {@collect.stats}
* Indicates we're in the process of showing. All painting, on the EDT,
* is blocked while this is true.
*/
private boolean showing;
//
// Region that we need to flush. When beginPaint is called these are
// reset and any subsequent calls to paint/copyArea then update these
// fields accordingly. When endPaint is called we then try and show
// the accumulated region.
// These fields are in the coordinate system of the root.
//
private int accumulatedX;
private int accumulatedY;
private int accumulatedMaxX;
private int accumulatedMaxY;
//
// The following fields are set by prepare
//
/** {@collect.stats}
* Farthest JComponent ancestor for the current paint/copyArea.
*/
private JComponent rootJ;
/** {@collect.stats}
* Parent Applet/Window for the current paint/copyArea
*/
private Container root;
/** {@collect.stats}
* Location of component being painted relative to root.
*/
private int xOffset;
/** {@collect.stats}
* Location of component being painted relative to root.
*/
private int yOffset;
/** {@collect.stats}
* Graphics from the BufferStrategy.
*/
private Graphics bsg;
/** {@collect.stats}
* BufferStrategy currently being used.
*/
private BufferStrategy bufferStrategy;
/** {@collect.stats}
* BufferInfo corresponding to root.
*/
private BufferInfo bufferInfo;
/** {@collect.stats}
* Set to true if the bufferInfo needs to be disposed when current
* paint loop is done.
*/
private boolean disposeBufferOnEnd;
static {
TRY_FLIP = "true".equals(AccessController.doPrivileged(
new GetPropertyAction("swing.useFlipBufferStrategy", "false")));
}
private static Method getGetBufferStrategyMethod() {
if (COMPONENT_GET_BUFFER_STRATEGY_METHOD == null) {
getMethods();
}
return COMPONENT_GET_BUFFER_STRATEGY_METHOD;
}
private static Method getCreateBufferStrategyMethod() {
if (COMPONENT_CREATE_BUFFER_STRATEGY_METHOD == null) {
getMethods();
}
return COMPONENT_CREATE_BUFFER_STRATEGY_METHOD;
}
private static void getMethods() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Object>() {
public Object run() {
try {
COMPONENT_CREATE_BUFFER_STRATEGY_METHOD = Component.class.
getDeclaredMethod("createBufferStrategy",
new Class[] { int.class,
BufferCapabilities.class });
COMPONENT_CREATE_BUFFER_STRATEGY_METHOD.
setAccessible(true);
COMPONENT_GET_BUFFER_STRATEGY_METHOD = Component.class.
getDeclaredMethod("getBufferStrategy");
COMPONENT_GET_BUFFER_STRATEGY_METHOD.setAccessible(true);
} catch (SecurityException e) {
assert false;
} catch (NoSuchMethodException nsme) {
assert false;
}
return null;
}
});
}
BufferStrategyPaintManager() {
bufferInfos = new ArrayList<BufferInfo>(1);
}
//
// PaintManager methods
//
/** {@collect.stats}
* Cleans up any created BufferStrategies.
*/
protected void dispose() {
// dipose can be invoked at any random time. To avoid
// threading dependancies we do the actual diposing via an
// invokeLater.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
java.util.List<BufferInfo> bufferInfos;
synchronized(BufferStrategyPaintManager.this) {
while (showing) {
try {
wait();
} catch (InterruptedException ie) {
}
}
bufferInfos = BufferStrategyPaintManager.this.bufferInfos;
BufferStrategyPaintManager.this.bufferInfos = null;
}
dispose(bufferInfos);
}
});
}
private void dispose(java.util.List<BufferInfo> bufferInfos) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "BufferStrategyPaintManager disposed",
new RuntimeException());
}
if (bufferInfos != null) {
for (BufferInfo bufferInfo : bufferInfos) {
bufferInfo.dispose();
}
}
}
/** {@collect.stats}
* Shows the specified region of the back buffer. This will return
* true if successful, false otherwise. This is invoked on the
* toolkit thread in response to an expose event.
*/
public boolean show(Container c, int x, int y, int w, int h) {
synchronized(this) {
if (painting) {
// Don't show from backbuffer while in the process of
// painting.
return false;
}
showing = true;
}
try {
BufferInfo info = getBufferInfo(c);
BufferStrategy bufferStrategy;
if (info != null && !info.usingFlip && info.isInSync() &&
(bufferStrategy = info.getBufferStrategy(false)) != null) {
SubRegionShowable bsSubRegion =
(SubRegionShowable)bufferStrategy;
boolean paintAllOnExpose = info.getPaintAllOnExpose();
info.setPaintAllOnExpose(false);
if (bsSubRegion.validateAndShow(x, y, (x + w), (y + h))) {
return !paintAllOnExpose;
}
// Mark the buffer as needing to be repainted. We don't
// immediately do a repaint as this method will return false
// indicating a PaintEvent should be generated which will
// trigger a complete repaint.
bufferInfo.setContentsLostDuringExpose(true);
}
}
finally {
synchronized(this) {
showing = false;
notifyAll();
}
}
return false;
}
public boolean paint(JComponent paintingComponent,
JComponent bufferComponent, Graphics g,
int x, int y, int w, int h) {
if (prepare(paintingComponent, true, x, y, w, h)) {
if ((g instanceof SunGraphics2D) &&
((SunGraphics2D)g).getDestination() == root) {
// BufferStrategy may have already constrained the Graphics. To
// account for that we revert the constrain, then apply a
// constrain for Swing on top of that.
int cx = ((SunGraphics2D)bsg).constrainX;
int cy = ((SunGraphics2D)bsg).constrainY;
if (cx != 0 || cy != 0) {
bsg.translate(-cx, -cy);
}
((SunGraphics2D)bsg).constrain(xOffset + cx, yOffset + cy,
x + w, y + h);
bsg.setClip(x, y, w, h);
paintingComponent.paintToOffscreen(bsg, x, y, w, h,
x + w, y + h);
accumulate(xOffset + x, yOffset + y, w, h);
return true;
} else {
// Assume they are going to eventually render to the screen.
// This disables showing from backbuffer until a complete
// repaint occurs.
bufferInfo.setInSync(false);
// Fall through to old rendering.
}
}
// Invalid root, do what Swing has always done.
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("prepare failed");
}
return super.paint(paintingComponent, bufferComponent, g, x, y, w, h);
}
public void copyArea(JComponent c, Graphics g, int x, int y, int w, int h,
int deltaX, int deltaY, boolean clip) {
// Note: this method is only called internally and we know that
// g is from a heavyweight Component, so no check is necessary as
// it is in paint() above.
//
// If the buffer isn't in sync there is no point in doing a copyArea,
// it has garbage.
if (prepare(c, false, 0, 0, 0, 0) && bufferInfo.isInSync()) {
if (clip) {
Rectangle cBounds = c.getVisibleRect();
int relX = xOffset + x;
int relY = yOffset + y;
bsg.clipRect(xOffset + cBounds.x,
yOffset + cBounds.y,
cBounds.width, cBounds.height);
bsg.copyArea(relX, relY, w, h, deltaX, deltaY);
}
else {
bsg.copyArea(xOffset + x, yOffset + y, w, h, deltaX,
deltaY);
}
accumulate(x + xOffset + deltaX, y + yOffset + deltaY, w, h);
} else {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("copyArea: prepare failed or not in sync");
}
// Prepare failed, or not in sync. By calling super.copyArea
// we'll copy on screen. We need to flush any pending paint to
// the screen otherwise we'll do a copyArea on the wrong thing.
if (!flushAccumulatedRegion()) {
// Flush failed, copyArea will be copying garbage,
// force repaint of all.
rootJ.repaint();
} else {
super.copyArea(c, g, x, y, w, h, deltaX, deltaY, clip);
}
}
}
public void beginPaint() {
synchronized(this) {
painting = true;
// Make sure another thread isn't attempting to show from
// the back buffer.
while(showing) {
try {
wait();
} catch (InterruptedException ie) {
}
}
}
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("beginPaint");
}
// Reset the area that needs to be painted.
resetAccumulated();
}
public void endPaint() {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("endPaint: region " + accumulatedX + " " +
accumulatedY + " " + accumulatedMaxX + " " +
accumulatedMaxY);
}
if (painting) {
if (!flushAccumulatedRegion()) {
if (!isRepaintingRoot()) {
repaintRoot(rootJ);
}
else {
// Contents lost twice in a row, punt.
resetDoubleBufferPerWindow();
// In case we've left junk on the screen, force a repaint.
rootJ.repaint();
}
}
}
BufferInfo toDispose = null;
synchronized(this) {
painting = false;
if (disposeBufferOnEnd) {
disposeBufferOnEnd = false;
toDispose = bufferInfo;
bufferInfos.remove(toDispose);
}
}
if (toDispose != null) {
toDispose.dispose();
}
}
/** {@collect.stats}
* Renders the BufferStrategy to the screen.
*
* @return true if successful, false otherwise.
*/
private boolean flushAccumulatedRegion() {
boolean success = true;
if (accumulatedX != Integer.MAX_VALUE) {
SubRegionShowable bsSubRegion = (SubRegionShowable)bufferStrategy;
boolean contentsLost = bufferStrategy.contentsLost();
if (!contentsLost) {
bsSubRegion.show(accumulatedX, accumulatedY,
accumulatedMaxX, accumulatedMaxY);
contentsLost = bufferStrategy.contentsLost();
}
if (contentsLost) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("endPaint: contents lost");
}
// Shown region was bogus, mark buffer as out of sync.
bufferInfo.setInSync(false);
success = false;
}
}
resetAccumulated();
return success;
}
private void resetAccumulated() {
accumulatedX = Integer.MAX_VALUE;
accumulatedY = Integer.MAX_VALUE;
accumulatedMaxX = 0;
accumulatedMaxY = 0;
}
/** {@collect.stats}
* Invoked when the double buffering or useTrueDoubleBuffering
* changes for a JRootPane. If the rootpane is not double
* buffered, or true double buffering changes we throw out any
* cache we may have.
*/
public void doubleBufferingChanged(final JRootPane rootPane) {
if ((!rootPane.isDoubleBuffered() ||
!rootPane.getUseTrueDoubleBuffering()) &&
rootPane.getParent() != null) {
if (!SwingUtilities.isEventDispatchThread()) {
Runnable updater = new Runnable() {
public void run() {
doubleBufferingChanged0(rootPane);
}
};
SwingUtilities.invokeLater(updater);
}
else {
doubleBufferingChanged0(rootPane);
}
}
}
/** {@collect.stats}
* Does the work for doubleBufferingChanged.
*/
private void doubleBufferingChanged0(JRootPane rootPane) {
// This will only happen on the EDT.
BufferInfo info;
synchronized(this) {
// Make sure another thread isn't attempting to show from
// the back buffer.
while(showing) {
try {
wait();
} catch (InterruptedException ie) {
}
}
info = getBufferInfo(rootPane.getParent());
if (painting && bufferInfo == info) {
// We're in the process of painting and the user grabbed
// the Graphics. If we dispose now, endPaint will attempt
// to show a bogus BufferStrategy. Set a flag so that
// endPaint knows it needs to dispose this buffer.
disposeBufferOnEnd = true;
info = null;
} else if (info != null) {
bufferInfos.remove(info);
}
}
if (info != null) {
info.dispose();
}
}
/** {@collect.stats}
* Calculates information common to paint/copyArea.
*
* @return true if should use buffering per window in painting.
*/
private boolean prepare(JComponent c, boolean isPaint, int x, int y,
int w, int h) {
if (bsg != null) {
bsg.dispose();
bsg = null;
}
bufferStrategy = null;
if (fetchRoot(c)) {
boolean contentsLost = false;
BufferInfo bufferInfo = getBufferInfo(root);
if (bufferInfo == null) {
contentsLost = true;
bufferInfo = new BufferInfo(root);
bufferInfos.add(bufferInfo);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("prepare: new BufferInfo: " + root);
}
}
this.bufferInfo = bufferInfo;
if (!bufferInfo.hasBufferStrategyChanged()) {
bufferStrategy = bufferInfo.getBufferStrategy(true);
if (bufferStrategy != null) {
bsg = bufferStrategy.getDrawGraphics();
if (bufferStrategy.contentsRestored()) {
contentsLost = true;
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(
"prepare: contents restored in prepare");
}
}
}
else {
// Couldn't create BufferStrategy, fallback to normal
// painting.
return false;
}
if (bufferInfo.getContentsLostDuringExpose()) {
contentsLost = true;
bufferInfo.setContentsLostDuringExpose(false);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("prepare: contents lost on expose");
}
}
if (isPaint && c == rootJ && x == 0 && y == 0 &&
c.getWidth() == w && c.getHeight() == h) {
bufferInfo.setInSync(true);
}
else if (contentsLost) {
// We either recreated the BufferStrategy, or the contents
// of the buffer strategy were restored. We need to
// repaint the root pane so that the back buffer is in sync
// again.
bufferInfo.setInSync(false);
if (!isRepaintingRoot()) {
repaintRoot(rootJ);
}
else {
// Contents lost twice in a row, punt
resetDoubleBufferPerWindow();
}
}
return (bufferInfos != null);
}
}
return false;
}
private boolean fetchRoot(JComponent c) {
boolean encounteredHW = false;
rootJ = c;
root = c;
xOffset = yOffset = 0;
while (root != null && (!(root instanceof Window) &&
!(root instanceof Applet))) {
xOffset += root.getX();
yOffset += root.getY();
root = root.getParent();
if (root != null) {
if (root instanceof JComponent) {
rootJ = (JComponent)root;
}
else if (!root.isLightweight()) {
if (!encounteredHW) {
encounteredHW = true;
}
else {
// We've encountered two hws now and may have
// a containment hierarchy with lightweights containing
// heavyweights containing other lightweights.
// Heavyweights poke holes in lightweight
// rendering so that if we call show on the BS
// (which is associated with the Window) you will
// not see the contents over any child
// heavyweights. If we didn't do this when we
// went to show the descendants of the nested hw
// you would see nothing, so, we bail out here.
return false;
}
}
}
}
if ((root instanceof RootPaneContainer) &&
(rootJ instanceof JRootPane)) {
// We're in a Swing heavyeight (JFrame/JWindow...), use double
// buffering if double buffering enabled on the JRootPane and
// the JRootPane wants true double buffering.
if (rootJ.isDoubleBuffered() &&
((JRootPane)rootJ).getUseTrueDoubleBuffering()) {
// Whether or not a component is double buffered is a
// bit tricky with Swing. This gives a good approximation
// of the various ways to turn on double buffering for
// components.
return true;
}
}
// Don't do true double buffering.
return false;
}
/** {@collect.stats}
* Turns off double buffering per window.
*/
private void resetDoubleBufferPerWindow() {
if (bufferInfos != null) {
dispose(bufferInfos);
bufferInfos = null;
repaintManager.setPaintManager(null);
}
}
/** {@collect.stats}
* Returns the BufferInfo for the specified root or null if one
* hasn't been created yet.
*/
private BufferInfo getBufferInfo(Container root) {
for (int counter = bufferInfos.size() - 1; counter >= 0; counter--) {
BufferInfo bufferInfo = bufferInfos.get(counter);
Container biRoot = bufferInfo.getRoot();
if (biRoot == null) {
// Window gc'ed
bufferInfos.remove(counter);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("BufferInfo pruned, root null");
}
}
else if (biRoot == root) {
return bufferInfo;
}
}
return null;
}
private void accumulate(int x, int y, int w, int h) {
accumulatedX = Math.min(x, accumulatedX);
accumulatedY = Math.min(y, accumulatedY);
accumulatedMaxX = Math.max(accumulatedMaxX, x + w);
accumulatedMaxY = Math.max(accumulatedMaxY, y + h);
}
/** {@collect.stats}
* BufferInfo is used to track the BufferStrategy being used for
* a particular Component. In addition to tracking the BufferStrategy
* it will install a WindowListener and ComponentListener. When the
* component is hidden/iconified the buffer is marked as needing to be
* completely repainted.
*/
private class BufferInfo extends ComponentAdapter implements
WindowListener {
// NOTE: This class does NOT hold a direct reference to the root, if it
// did there would be a cycle between the BufferPerWindowPaintManager
// and the Window so that it could never be GC'ed
//
// Reference to BufferStrategy is referenced via WeakReference for
// same reason.
private WeakReference<BufferStrategy> weakBS;
private WeakReference<Container> root;
// Whether or not we're using flip bs or blit.
private boolean usingFlip;
// Indicates whether or not the backbuffer and display are in sync.
// This is set to true when a full repaint on the rootpane is done.
private boolean inSync;
// Indicates the contents were lost during and expose event.
private boolean contentsLostDuringExpose;
// Indicates we need to generate a paint event on expose.
private boolean paintAllOnExpose;
public BufferInfo(Container root) {
this.root = new WeakReference<Container>(root);
root.addComponentListener(this);
if (root instanceof Window) {
((Window)root).addWindowListener(this);
}
}
public void setPaintAllOnExpose(boolean paintAllOnExpose) {
this.paintAllOnExpose = paintAllOnExpose;
}
public boolean getPaintAllOnExpose() {
return paintAllOnExpose;
}
public void setContentsLostDuringExpose(boolean value) {
contentsLostDuringExpose = value;
}
public boolean getContentsLostDuringExpose() {
return contentsLostDuringExpose;
}
public void setInSync(boolean inSync) {
this.inSync = inSync;
}
/** {@collect.stats}
* Whether or not the contents of the buffer strategy
* is in sync with the window. This is set to true when the root
* pane paints all, and false when contents are lost/restored.
*/
public boolean isInSync() {
return inSync;
}
/** {@collect.stats}
* Returns the Root (Window or Applet) that this BufferInfo references.
*/
public Container getRoot() {
return (root == null) ? null : root.get();
}
/** {@collect.stats}
* Returns the BufferStartegy. This will return null if
* the BufferStartegy hasn't been created and <code>create</code> is
* false, or if there is a problem in creating the
* <code>BufferStartegy</code>.
*
* @param create If true, and the BufferStartegy is currently null,
* one will be created.
*/
public BufferStrategy getBufferStrategy(boolean create) {
BufferStrategy bs = (weakBS == null) ? null : weakBS.get();
if (bs == null && create) {
bs = createBufferStrategy();
if (bs != null) {
weakBS = new WeakReference<BufferStrategy>(bs);
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("getBufferStrategy: created bs: " + bs);
}
}
return bs;
}
/** {@collect.stats}
* Returns true if using a flip buffer strategy.
*/
public boolean usingFlip() {
return usingFlip;
}
/** {@collect.stats}
* Returns true if the buffer strategy of the component differs
* from current buffer strategy.
*/
public boolean hasBufferStrategyChanged() {
Container root = getRoot();
if (root != null) {
BufferStrategy ourBS = null;
BufferStrategy componentBS = null;
ourBS = getBufferStrategy(false);
if (root instanceof Window) {
componentBS = ((Window)root).getBufferStrategy();
}
else {
try {
componentBS = (BufferStrategy)
getGetBufferStrategyMethod().invoke(root);
} catch (InvocationTargetException ite) {
assert false;
} catch (IllegalArgumentException iae) {
assert false;
} catch (IllegalAccessException iae2) {
assert false;
}
}
if (componentBS != ourBS) {
// Component has a different BS, dispose ours.
if (ourBS != null) {
ourBS.dispose();
}
weakBS = null;
return true;
}
}
return false;
}
/** {@collect.stats}
* Creates the BufferStrategy. If the appropriate system property
* has been set we'll try for flip first and then we'll try for
* blit.
*/
private BufferStrategy createBufferStrategy() {
BufferCapabilities caps;
Container root = getRoot();
if (root == null) {
return null;
}
BufferStrategy bs = null;
if (TRY_FLIP) {
bs = createBufferStrategy(root,BufferCapabilities.FlipContents.
COPIED);
usingFlip = true;
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("createBufferStrategy: using flip strategy");
}
}
if (bs == null) {
bs = createBufferStrategy(root, null);
usingFlip = false;
}
if (!(bs instanceof SubRegionShowable)) {
// We do this for two reasons:
// 1. So that we know we can cast to SubRegionShowable and
// invoke show with the minimal region to update
// 2. To avoid the possibility of invoking client code
// on the toolkit thread.
bs = null;
}
return bs;
}
// Creates and returns a buffer strategy of the requested type. If
// there is a problem creating the buffer strategy this will
// eat the exception and return null.
private BufferStrategy createBufferStrategy(Container root,
BufferCapabilities.FlipContents type) {
BufferCapabilities caps = new BufferCapabilities(
new ImageCapabilities(true),
new ImageCapabilities(true),
type);
BufferStrategy bs = null;
if (root instanceof Applet) {
try {
getCreateBufferStrategyMethod().invoke(root, 2, caps);
bs = (BufferStrategy)getGetBufferStrategyMethod().
invoke(root);
} catch (InvocationTargetException ite) {
// Type is not supported
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "createBufferStratety failed",
ite);
}
} catch (IllegalArgumentException iae) {
assert false;
} catch (IllegalAccessException iae2) {
assert false;
}
}
else {
try {
((Window)root).createBufferStrategy(2, caps);
bs = ((Window)root).getBufferStrategy();
} catch (AWTException e) {
// Type not supported
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "createBufferStratety failed",
e);
}
}
}
return bs;
}
/** {@collect.stats}
* Cleans up and removes any references.
*/
public void dispose() {
Container root = getRoot();
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "disposed BufferInfo for: " + root);
}
if (root != null) {
root.removeComponentListener(this);
if (root instanceof Window) {
((Window)root).removeWindowListener(this);
}
BufferStrategy bs = getBufferStrategy(false);
if (bs != null) {
bs.dispose();
}
}
this.root = null;
weakBS = null;
}
// We mark the buffer as needing to be painted on a hide/iconify
// because the developer may have conditionalized painting based on
// visibility.
// Ideally we would also move to having the BufferStrategy being
// a SoftReference in Component here, but that requires changes to
// Component and the like.
public void componentHidden(ComponentEvent e) {
Container root = getRoot();
if (root != null && root.isVisible()) {
// This case will only happen if a developer calls
// hide immediately followed by show. In this case
// the event is delivered after show and the window
// will still be visible. If a developer altered the
// contents of the window between the hide/show
// invocations we won't recognize we need to paint and
// the contents would be bogus. Calling repaint here
// fixs everything up.
root.repaint();
}
else {
setPaintAllOnExpose(true);
}
}
public void windowIconified(WindowEvent e) {
setPaintAllOnExpose(true);
}
// On a dispose we chuck everything.
public void windowClosed(WindowEvent e) {
// Make sure we're not showing.
synchronized(BufferStrategyPaintManager.this) {
while (showing) {
try {
BufferStrategyPaintManager.this.wait();
} catch (InterruptedException ie) {
}
}
bufferInfos.remove(this);
}
dispose();
}
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Font;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.Color;
import java.awt.Component;
import java.awt.SystemColor;
import java.awt.Toolkit;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import java.net.URL;
import sun.swing.SwingUtilities2;
import sun.swing.DefaultLayoutStyle;
import sun.swing.ImageIconUIResource;
import java.util.StringTokenizer;
/** {@collect.stats}
* {@code LookAndFeel}, as the name implies, encapsulates a look and
* feel. Beyond installing a look and feel most developers never need to
* interact directly with {@code LookAndFeel}. In general only developers
* creating a custom look and feel need to concern themselves with this class.
* <p>
* Swing is built upon the foundation that each {@code JComponent}
* subclass has an implementation of a specific {@code ComponentUI}
* subclass. The {@code ComponentUI} is often referred to as "the ui",
* "component ui", or "look and feel delegate". The {@code ComponentUI}
* subclass is responsible for providing the look and feel specific
* functionality of the component. For example, {@code JTree} requires
* an implementation of the {@code ComponentUI} subclass {@code
* TreeUI}. The implementation of the specific {@code
* ComponentUI} subclass is provided by the {@code LookAndFeel}. Each
* {@code JComponent} subclass identifies the {@code ComponentUI}
* subclass it requires by way of the {@code JComponent} method {@code
* getUIClassID}.
* <p>
* Each {@code LookAndFeel} implementation must provide
* an implementation of the appropriate {@code ComponentUI} subclass by
* specifying a value for each of Swing's ui class ids in the {@code
* UIDefaults} object returned from {@code getDefaults}. For example,
* {@code BasicLookAndFeel} uses {@code BasicTreeUI} as the concrete
* implementation for {@code TreeUI}. This is accomplished by {@code
* BasicLookAndFeel} providing the key-value pair {@code
* "TreeUI"-"javax.swing.plaf.basic.BasicTreeUI"}, in the
* {@code UIDefaults} returned from {@code getDefaults}. Refer to
* {@link UIDefaults#getUI(JComponent)} for defails on how the implementation
* of the {@code ComponentUI} subclass is obtained.
* <p>
* When a {@code LookAndFeel} is installed the {@code UIManager} does
* not check that an entry exists for all ui class ids. As such,
* random exceptions will occur if the current look and feel has not
* provided a value for a particular ui class id and an instance of
* the {@code JComponent} subclass is created.
*
* <h2>Recommendations for Look and Feels</h2>
*
* As noted in {@code UIManager} each {@code LookAndFeel} has the opportunity
* to provide a set of defaults that are layered in with developer and
* system defaults. Some of Swing's components require the look and feel
* to provide a specific set of defaults. These are documented in the
* classes that require the specific default.
*
* <h3><a name="#defaultRecommendation">ComponentUIs and defaults</a></h2>
*
* All {@code ComponentUIs} typically need to set various properties
* on the {@code JComponent} the {@code ComponentUI} is providing the
* look and feel for. This is typically done when the {@code
* ComponentUI} is installed on the {@code JComponent}. Setting a
* property should only be done if the developer has not set the
* property. For non-primitive values it is recommended that the
* {@code ComponentUI} only change the property on the {@code
* JComponent} if the current value is {@code null} or implements
* {@code UIResource}. If the current value is {@code null} or
* implements {@code UIResource} it indicates the property has not
* been set by the developer, and the ui is free to change it. For
* example, {@code BasicButtonUI.installDefaults} only changes the
* font on the {@code JButton} if the return value from {@code
* button.getFont()} is {@code null} or implements {@code
* UIResource}. On the other hand if {@code button.getFont()} returned
* a {@code non-null} value that did not implement {@code UIResource}
* then {@code BasicButtonUI.installDefaults} would not change the
* {@code JButton}'s font.
* <p>
* For primitive values, such as {@code opaque}, the method {@code
* installProperty} should be invoked. {@code installProperty} only changes
* the correspoding property if the value has not been changed by the
* developer.
* <p>
* {@code ComponentUI} implementations should use the various install methods
* provided by this class as they handle the necessary checking and install
* the property using the recommended guidelines.
* <p>
* <h3><a name="exceptions"></a>Exceptions</h3>
*
* All of the install methods provided by {@code LookAndFeel} need to
* access the defaults if the value of the property being changed is
* {@code null} or a {@code UIResource}. For example, installing the
* font does the following:
* <pre>
* JComponent c;
* Font font = c.getFont();
* if (font == null || (font instanceof UIResource)) {
* c.setFont(UIManager.getFont("fontKey"));
* }
* </pre>
* If the font is {@code null} or a {@code UIResource}, the
* defaults table is queried with the key {@code fontKey}. All of
* {@code UIDefault's} get methods throw a {@code
* NullPointerException} if passed in {@code null}. As such, unless
* otherwise noted each of the various install methods of {@code
* LookAndFeel} throw a {@code NullPointerException} if the current
* value is {@code null} or a {@code UIResource} and the supplied
* defaults key is {@code null}. In addition, unless otherwise specified
* all of the {@code install} methods throw a {@code NullPointerException} if
* a {@code null} component is passed in.
*
* @author Tom Ball
* @author Hans Muller
*/
public abstract class LookAndFeel
{
/** {@collect.stats}
* Convenience method for setting a component's foreground
* and background color properties with values from the
* defaults. The properties are only set if the current
* value is either {@code null} or a {@code UIResource}.
*
* @param c component to set the colors on
* @param defaultBgName key for the background
* @param defaultFgName key for the foreground
*
* @see #installColorsAndFont
* @see UIManager#getColor
* @throws NullPointerException as described in
* <a href="#exceptions">exceptions</a>
*/
public static void installColors(JComponent c,
String defaultBgName,
String defaultFgName)
{
Color bg = c.getBackground();
if (bg == null || bg instanceof UIResource) {
c.setBackground(UIManager.getColor(defaultBgName));
}
Color fg = c.getForeground();
if (fg == null || fg instanceof UIResource) {
c.setForeground(UIManager.getColor(defaultFgName));
}
}
/** {@collect.stats}
* Convenience method for setting a component's foreground,
* background and font properties with values from the
* defaults. The properties are only set if the current
* value is either {@code null} or a {@code UIResource}.
*
* @param c component set to the colors and font on
* @param defaultBgName key for the background
* @param defaultFgName key for the foreground
* @param defaultFontName key for the font
* @throws NullPointerException as described in
* <a href="#exceptions">exceptions</a>
*
* @see #installColors
* @see UIManager#getColor
* @see UIManager#getFont
*/
public static void installColorsAndFont(JComponent c,
String defaultBgName,
String defaultFgName,
String defaultFontName) {
Font f = c.getFont();
if (f == null || f instanceof UIResource) {
c.setFont(UIManager.getFont(defaultFontName));
}
installColors(c, defaultBgName, defaultFgName);
}
/** {@collect.stats}
* Convenience method for setting a component's border property with
* a value from the defaults. The border is only set if the border is
* {@code null} or an instance of {@code UIResource}.
*
* @param c component to set the border on
* @param defaultBorderName key specifying the border
* @throws NullPointerException as described in
* <a href="#exceptions">exceptions</a>
*/
public static void installBorder(JComponent c, String defaultBorderName) {
Border b = c.getBorder();
if (b == null || b instanceof UIResource) {
c.setBorder(UIManager.getBorder(defaultBorderName));
}
}
/** {@collect.stats}
* Convenience method for uninstalling a border. If the border of
* the component is a {@code UIResource}, it is set to {@code
* null}.
*
* @param c component to uninstall the border on
* @throws NullPointerException if {@code c} is {@code null}
*/
public static void uninstallBorder(JComponent c) {
if (c.getBorder() instanceof UIResource) {
c.setBorder(null);
}
}
/** {@collect.stats}
* Convenience method for installing a property with the specified name
* and value on a component if that property has not already been set
* by the developer. This method is intended to be used by
* ui delegate instances that need to specify a default value for a
* property of primitive type (boolean, int, ..), but do not wish
* to override a value set by the client. Since primitive property
* values cannot be wrapped with the {@code UIResource} marker, this method
* uses private state to determine whether the property has been set
* by the client.
*
* @throws IllegalArgumentException if the specified property is not
* one which can be set using this method
* @throws ClassCastException if the property value has not been set
* by the developer and the type does not match the property's type
* @throws NullPointerException if {@code c} is {@code null}, or the
* named property has not been set by the developer and
* {@code propertyValue} is {@code null}
* @param c target component to set the property on
* @param propertyName name of the property to set
* @param propertyValue value of the property
* @since 1.5
*/
public static void installProperty(JComponent c,
String propertyName, Object propertyValue) {
// this is a special case because the JPasswordField's ancestor heirarchy
// includes a class outside of javax.swing, thus we cannot call setUIProperty
// directly.
if (c instanceof JPasswordField) {
if (!((JPasswordField)c).customSetUIProperty(propertyName, propertyValue)) {
c.setUIProperty(propertyName, propertyValue);
}
} else {
c.setUIProperty(propertyName, propertyValue);
}
}
/** {@collect.stats}
* Convenience method for building an array of {@code
* KeyBindings}. While this method is not deprecated, developers
* should instead use {@code ActionMap} and {@code InputMap} for
* supplying key bindings.
* <p>
* This method returns an array of {@code KeyBindings}, one for each
* alternating {@code key-action} pair in {@code keyBindingList}.
* A {@code key} can either be a {@code String} in the format
* specified by the <code>KeyStroke.getKeyStroke</code> method, or
* a {@code KeyStroke}. The {@code action} part of the pair is a
* {@code String} that corresponds to the name of the {@code
* Action}.
* <p>
* The following example illustrates creating a {@code KeyBinding} array
* from six alternating {@code key-action} pairs:
* <pre>
* JTextComponent.KeyBinding[] multilineBindings = makeKeyBindings( new Object[] {
* "UP", DefaultEditorKit.upAction,
* "DOWN", DefaultEditorKit.downAction,
* "PAGE_UP", DefaultEditorKit.pageUpAction,
* "PAGE_DOWN", DefaultEditorKit.pageDownAction,
* "ENTER", DefaultEditorKit.insertBreakAction,
* "TAB", DefaultEditorKit.insertTabAction
* });
* </pre>
* If {@code keyBindingList's} length is odd, the last element is
* ignored.
* <p>
* Supplying a {@code null} value for either the {@code key} or
* {@code action} part of the {@code key-action} pair results in
* creating a {@code KeyBinding} with the corresponding value
* {@code null}. As other parts of Swing's expect {@code non-null} values
* in a {@code KeyBinding}, you should avoid supplying {@code null} as
* either the {@code key} or {@code action} part of the {@code key-action}
* pair.
*
* @param keyBindingList an array of {@code key-action} pairs
* @return an array of {@code KeyBindings}
* @throws NullPointerException if {@code keyBindingList} is {@code null}
* @throws ClassCastException if the {@code key} part of the pair is
* not a {@code KeyStroke} or {@code String}, or the
* {@code action} part of the pair is not a {@code String}
* @see ActionMap
* @see InputMap
* @see KeyStroke#getKeyStroke
*/
public static JTextComponent.KeyBinding[] makeKeyBindings(Object[] keyBindingList)
{
JTextComponent.KeyBinding[] rv = new JTextComponent.KeyBinding[keyBindingList.length / 2];
for(int i = 0; i < keyBindingList.length; i += 2) {
KeyStroke keystroke = (keyBindingList[i] instanceof KeyStroke)
? (KeyStroke)keyBindingList[i]
: KeyStroke.getKeyStroke((String)keyBindingList[i]);
String action = (String)keyBindingList[i+1];
rv[i / 2] = new JTextComponent.KeyBinding(keystroke, action);
}
return rv;
}
/** {@collect.stats}
* Creates a {@code InputMapUIResource} from <code>keys</code>. This is
* a convenience method for creating a new {@code InputMapUIResource},
* invoking {@code loadKeyBindings(map, keys)}, and returning the
* {@code InputMapUIResource}.
*
* @param keys alternating pairs of {@code keystroke-action key}
* pairs as described in {@link #loadKeyBindings}
* @return newly created and populated {@code InputMapUIResource}
* @see #loadKeyBindings
*
* @since 1.3
*/
public static InputMap makeInputMap(Object[] keys) {
InputMap retMap = new InputMapUIResource();
loadKeyBindings(retMap, keys);
return retMap;
}
/** {@collect.stats}
* Creates a {@code ComponentInputMapUIResource} from
* <code>keys</code>. This is a convenience method for creating a
* new {@code ComponentInputMapUIResource}, invoking {@code
* loadKeyBindings(map, keys)}, and returning the {@code
* ComponentInputMapUIResource}.
*
* @param c component to create the {@code ComponentInputMapUIResource}
* with
* @param keys alternating pairs of {@code keystroke-action key}
* pairs as described in {@link #loadKeyBindings}
* @return newly created and populated {@code InputMapUIResource}
* @throws IllegalArgumentException if {@code c} is {@code null}
*
* @see #loadKeyBindings
* @see ComponentInputMapUIResource
*
* @since 1.3
*/
public static ComponentInputMap makeComponentInputMap(JComponent c,
Object[] keys) {
ComponentInputMap retMap = new ComponentInputMapUIResource(c);
loadKeyBindings(retMap, keys);
return retMap;
}
/** {@collect.stats}
* Populates an {@code InputMap} with the specified bindings.
* The bindings are supplied as a list of alternating
* {@code keystroke-action key} pairs. The {@code keystroke} is either
* an instance of {@code KeyStroke}, or a {@code String}
* that identifies the {@code KeyStroke} for the binding. Refer
* to {@code KeyStroke.getKeyStroke(String)} for the specific
* format. The {@code action key} part of the pair is the key
* registered in the {@code InputMap} for the {@code KeyStroke}.
* <p>
* The following illustrates loading an {@code InputMap} with two
* {@code key-action} pairs:
* <pre>
* LookAndFeel.loadKeyBindings(inputMap, new Object[] {
* "control X", "cut",
* "control V", "paste"
* });
* </pre>
* <p>
* Supplying a {@code null} list of bindings ({@code keys}) does not
* change {@code retMap} in any way.
* <p>
* Specifying a {@code null} {@code action key} results in
* removing the {@code keystroke's} entry from the {@code InputMap}.
* A {@code null} {@code keystroke} is ignored.
*
* @param retMap {@code InputMap} to add the {@code key-action}
* pairs to
* @param keys bindings to add to {@code retMap}
* @throws NullPointerException if {@code keys} is
* {@code non-null}, not empty, and {@code retMap} is
* {@code null}
*
* @see KeyStroke#getKeyStroke(String)
* @see InputMap
*
* @since 1.3
*/
public static void loadKeyBindings(InputMap retMap, Object[] keys) {
if (keys != null) {
for (int counter = 0, maxCounter = keys.length;
counter < maxCounter; counter++) {
Object keyStrokeO = keys[counter++];
KeyStroke ks = (keyStrokeO instanceof KeyStroke) ?
(KeyStroke)keyStrokeO :
KeyStroke.getKeyStroke((String)keyStrokeO);
retMap.put(ks, keys[counter]);
}
}
}
/** {@collect.stats}
* Creates and returns a {@code UIDefault.LazyValue} that loads an
* image. The returned value is an implementation of {@code
* UIDefaults.LazyValue}. When {@code createValue} is invoked on
* the returned object, the image is loaded. If the image is {@code
* non-null}, it is then wrapped in an {@code Icon} that implements {@code
* UIResource}. The image is loaded using {@code
* Class.getResourceAsStream(gifFile)}.
* <p>
* This method does not check the arguments in any way. It is
* strongly recommended that {@code non-null} values are supplied else
* exceptions may occur when {@code createValue} is invoked on the
* returned object.
*
* @param baseClass {@code Class} used to load the resource
* @param gifFile path to the image to load
* @return a {@code UIDefaults.LazyValue}; when resolved the
* {@code LazyValue} loads the specified image
* @see UIDefaults.LazyValue
* @see Icon
* @see Class#getResourceAsStream(String)
*/
public static Object makeIcon(final Class<?> baseClass, final String gifFile) {
return SwingUtilities2.makeIcon(baseClass, baseClass, gifFile);
}
/** {@collect.stats}
* Returns the <code>LayoutStyle</code> for this look
* and feel. This never returns {@code null}.
* <p>
* You generally don't use the <code>LayoutStyle</code> from
* the look and feel, instead use the <code>LayoutStyle</code>
* method <code>getInstance</code>.
*
* @see LayoutStyle#getInstance
* @return the <code>LayoutStyle</code> for this look and feel
* @since 1.6
*/
public LayoutStyle getLayoutStyle() {
return DefaultLayoutStyle.getInstance();
}
/** {@collect.stats}
* Invoked when the user attempts an invalid operation,
* such as pasting into an uneditable <code>JTextField</code>
* that has focus. The default implementation beeps. Subclasses
* that wish different behavior should override this and provide
* the additional feedback.
*
* @param component the <code>Component</code> the error occurred in,
* may be <code>null</code>
* indicating the error condition is not directly
* associated with a <code>Component</code>
* @since 1.4
*/
public void provideErrorFeedback(Component component) {
Toolkit toolkit = null;
if (component != null) {
toolkit = component.getToolkit();
} else {
toolkit = Toolkit.getDefaultToolkit();
}
toolkit.beep();
} // provideErrorFeedback()
/** {@collect.stats}
* Returns the value of the specified system desktop property by
* invoking <code>Toolkit.getDefaultToolkit().getDesktopProperty()</code>.
* If the value of the specified property is {@code null},
* {@code fallbackValue} is returned.
*
* @param systemPropertyName the name of the system desktop property being queried
* @param fallbackValue the object to be returned as the value if the system value is null
* @return the current value of the desktop property
*
* @see java.awt.Toolkit#getDesktopProperty
*
* @since 1.4
*/
public static Object getDesktopPropertyValue(String systemPropertyName, Object fallbackValue) {
Object value = Toolkit.getDefaultToolkit().getDesktopProperty(systemPropertyName);
if (value == null) {
return fallbackValue;
} else if (value instanceof Color) {
return new ColorUIResource((Color)value);
} else if (value instanceof Font) {
return new FontUIResource((Font)value);
}
return value;
}
/** {@collect.stats}
* Returns an <code>Icon</code> with a disabled appearance.
* This method is used to generate a disabled <code>Icon</code> when
* one has not been specified. For example, if you create a
* <code>JButton</code> and only specify an <code>Icon</code> via
* <code>setIcon</code> this method will be called to generate the
* disabled <code>Icon</code>. If {@code null} is passed as
* <code>icon</code> this method returns {@code null}.
* <p>
* Some look and feels might not render the disabled {@code Icon}, in which
* case they will ignore this.
*
* @param component {@code JComponent} that will display the {@code Icon},
* may be {@code null}
* @param icon {@code Icon} to generate the disabled icon from
* @return disabled {@code Icon}, or {@code null} if a suitable
* {@code Icon} can not be generated
* @since 1.5
*/
public Icon getDisabledIcon(JComponent component, Icon icon) {
if (icon instanceof ImageIcon) {
return new ImageIconUIResource(GrayFilter.
createDisabledImage(((ImageIcon)icon).getImage()));
}
return null;
}
/** {@collect.stats}
* Returns an <code>Icon</code> for use by disabled
* components that are also selected. This method is used to generate an
* <code>Icon</code> for components that are in both the disabled and
* selected states but do not have a specific <code>Icon</code> for this
* state. For example, if you create a <code>JButton</code> and only
* specify an <code>Icon</code> via <code>setIcon</code> this method
* will be called to generate the disabled and selected
* <code>Icon</code>. If {@code null} is passed as <code>icon</code> this
* methods returns {@code null}.
* <p>
* Some look and feels might not render the disabled and selected
* {@code Icon}, in which case they will ignore this.
*
* @param component {@code JComponent} that will display the {@code Icon},
* may be {@code null}
* @param icon {@code Icon} to generate disabled and selected icon from
* @return disabled and selected icon, or {@code null} if a suitable
* {@code Icon} can not be generated.
* @since 1.5
*/
public Icon getDisabledSelectedIcon(JComponent component, Icon icon) {
return getDisabledIcon(component, icon);
}
/** {@collect.stats}
* Return a short string that identifies this look and feel, e.g.
* "CDE/Motif". This string should be appropriate for a menu item.
* Distinct look and feels should have different names, e.g.
* a subclass of MotifLookAndFeel that changes the way a few components
* are rendered should be called "CDE/Motif My Way"; something
* that would be useful to a user trying to select a L&F from a list
* of names.
*
* @return short identifier for the look and feel
*/
public abstract String getName();
/** {@collect.stats}
* Return a string that identifies this look and feel. This string
* will be used by applications/services that want to recognize
* well known look and feel implementations. Presently
* the well known names are "Motif", "Windows", "Mac", "Metal". Note
* that a LookAndFeel derived from a well known superclass
* that doesn't make any fundamental changes to the look or feel
* shouldn't override this method.
*
* @return identifier for the look and feel
*/
public abstract String getID();
/** {@collect.stats}
* Return a one line description of this look and feel implementation,
* e.g. "The CDE/Motif Look and Feel". This string is intended for
* the user, e.g. in the title of a window or in a ToolTip message.
*
* @return short description for the look and feel
*/
public abstract String getDescription();
/** {@collect.stats}
* Returns {@code true} if the <code>LookAndFeel</code> returned
* <code>RootPaneUI</code> instances support providing {@code Window}
* decorations in a <code>JRootPane</code>.
* <p>
* The default implementation returns {@code false}, subclasses that
* support {@code Window} decorations should override this and return
* {@code true}.
*
* @return {@code true} if the {@code RootPaneUI} instances created by
* this look and feel support client side decorations
* @see JDialog#setDefaultLookAndFeelDecorated
* @see JFrame#setDefaultLookAndFeelDecorated
* @see JRootPane#setWindowDecorationStyle
* @since 1.4
*/
public boolean getSupportsWindowDecorations() {
return false;
}
/** {@collect.stats}
* If the underlying platform has a "native" look and feel, and
* this is an implementation of it, return {@code true}. For
* example, when the underlying platform is Solaris running CDE
* a CDE/Motif look and feel implementation would return {@code
* true}.
*
* @return {@code true} if this look and feel represents the underlying
* platform look and feel
*/
public abstract boolean isNativeLookAndFeel();
/** {@collect.stats}
* Return {@code true} if the underlying platform supports and or permits
* this look and feel. This method returns {@code false} if the look
* and feel depends on special resources or legal agreements that
* aren't defined for the current platform.
*
*
* @return {@code true} if this is a supported look and feel
* @see UIManager#setLookAndFeel
*/
public abstract boolean isSupportedLookAndFeel();
/** {@collect.stats}
* Initializes the look and feel. While this method is public,
* it should only be invoked by the {@code UIManager} when a
* look and feel is installed as the current look and feel. This
* method is invoked before the {@code UIManager} invokes
* {@code getDefaults}. This method is intended to perform any
* initialization for the look and feel. Subclasses
* should do any one-time setup they need here, rather than
* in a static initializer, because look and feel class objects
* may be loaded just to discover that {@code isSupportedLookAndFeel()}
* returns {@code false}.
*
* @see #uninitialize
* @see UIManager#setLookAndFeel
*/
public void initialize() {
}
/** {@collect.stats}
* Uninitializes the look and feel. While this method is public,
* it should only be invoked by the {@code UIManager} when
* the look and feel is uninstalled. For example,
* {@code UIManager.setLookAndFeel} invokes this when the look and
* feel is changed.
* <p>
* Subclasses may choose to free up some resources here.
*
* @see #initialize
* @see UIManager#setLookAndFeel
*/
public void uninitialize() {
}
/** {@collect.stats}
* Returns the look and feel defaults. While this method is public,
* it should only be invoked by the {@code UIManager} when the
* look and feel is set as the current look and feel and after
* {@code initialize} has been invoked.
*
* @return the look and feel defaults
* @see #initialize
* @see #uninitialize
* @see UIManager#setLookAndFeel
*/
public UIDefaults getDefaults() {
return null;
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public String toString() {
return "[" + getDescription() + " - " + getClass().getName() + "]";
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.plaf.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.accessibility.*;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Rectangle;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.Point;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.beans.*;
/** {@collect.stats}
* Provides a scrollable view of a lightweight component.
* A <code>JScrollPane</code> manages a viewport, optional
* vertical and horizontal scroll bars, and optional row and
* column heading viewports.
* You can find task-oriented documentation of <code>JScrollPane</code> in
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html">How to Use Scroll Panes</a>,
* a section in <em>The Java Tutorial</em>. Note that
* <code>JScrollPane</code> does not support heavyweight components.
* <p>
* <TABLE ALIGN="RIGHT" BORDER="0" SUMMARY="layout">
* <TR>
* <TD ALIGN="CENTER">
* <P ALIGN="CENTER"><IMG SRC="doc-files/JScrollPane-1.gif"
* alt="The following text describes this image."
* WIDTH="256" HEIGHT="248" ALIGN="BOTTOM" BORDER="0">
* </TD>
* </TR>
* </TABLE>
* The <code>JViewport</code> provides a window,
* or "viewport" onto a data
* source -- for example, a text file. That data source is the
* "scrollable client" (aka data model) displayed by the
* <code>JViewport</code> view.
* A <code>JScrollPane</code> basically consists of <code>JScrollBar</code>s,
* a <code>JViewport</code>, and the wiring between them,
* as shown in the diagram at right.
* <p>
* In addition to the scroll bars and viewport,
* a <code>JScrollPane</code> can have a
* column header and a row header. Each of these is a
* <code>JViewport</code> object that
* you specify with <code>setRowHeaderView</code>,
* and <code>setColumnHeaderView</code>.
* The column header viewport automatically scrolls left and right, tracking
* the left-right scrolling of the main viewport.
* (It never scrolls vertically, however.)
* The row header acts in a similar fashion.
* <p>
* Where two scroll bars meet, the row header meets the column header,
* or a scroll bar meets one of the headers, both components stop short
* of the corner, leaving a rectangular space which is, by default, empty.
* These spaces can potentially exist in any number of the four corners.
* In the previous diagram, the top right space is present and identified
* by the label "corner component".
* <p>
* Any number of these empty spaces can be replaced by using the
* <code>setCorner</code> method to add a component to a particular corner.
* (Note: The same component cannot be added to multiple corners.)
* This is useful if there's
* some extra decoration or function you'd like to add to the scroll pane.
* The size of each corner component is entirely determined by the size of the
* headers and/or scroll bars that surround it.
* <p>
* A corner component will only be visible if there is an empty space in that
* corner for it to exist in. For example, consider a component set into the
* top right corner of a scroll pane with a column header. If the scroll pane's
* vertical scrollbar is not present, perhaps because the view component hasn't
* grown large enough to require it, then the corner component will not be
* shown (since there is no empty space in that corner created by the meeting
* of the header and vertical scroll bar). Forcing the scroll bar to always be
* shown, using
* <code>setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS)</code>,
* will ensure that the space for the corner component always exists.
* <p>
* To add a border around the main viewport,
* you can use <code>setViewportBorder</code>.
* (Of course, you can also add a border around the whole scroll pane using
* <code>setBorder</code>.)
* <p>
* A common operation to want to do is to set the background color that will
* be used if the main viewport view is smaller than the viewport, or is
* not opaque. This can be accomplished by setting the background color
* of the viewport, via <code>scrollPane.getViewport().setBackground()</code>.
* The reason for setting the color of the viewport and not the scrollpane
* is that by default <code>JViewport</code> is opaque
* which, among other things, means it will completely fill
* in its background using its background color. Therefore when
* <code>JScrollPane</code> draws its background the viewport will
* usually draw over it.
* <p>
* By default <code>JScrollPane</code> uses <code>ScrollPaneLayout</code>
* to handle the layout of its child Components. <code>ScrollPaneLayout</code>
* determines the size to make the viewport view in one of two ways:
* <ol>
* <li>If the view implements <code>Scrollable</code>
* a combination of <code>getPreferredScrollableViewportSize</code>,
* <code>getScrollableTracksViewportWidth</code> and
* <code>getScrollableTracksViewportHeight</code>is used, otherwise
* <li><code>getPreferredSize</code> is used.
* </ol>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see JScrollBar
* @see JViewport
* @see ScrollPaneLayout
* @see Scrollable
* @see Component#getPreferredSize
* @see #setViewportView
* @see #setRowHeaderView
* @see #setColumnHeaderView
* @see #setCorner
* @see #setViewportBorder
*
* @beaninfo
* attribute: isContainer true
* attribute: containerDelegate getViewport
* description: A specialized container that manages a viewport, optional scrollbars and headers
*
* @author Hans Muller
*/
public class JScrollPane extends JComponent implements ScrollPaneConstants, Accessible
{
private Border viewportBorder;
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ScrollPaneUI";
/** {@collect.stats}
* The display policy for the vertical scrollbar.
* The default is
* <code>ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED</code>.
* @see #setVerticalScrollBarPolicy
*/
protected int verticalScrollBarPolicy = VERTICAL_SCROLLBAR_AS_NEEDED;
/** {@collect.stats}
* The display policy for the horizontal scrollbar.
* The default is
* <code>ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED</code>.
* @see #setHorizontalScrollBarPolicy
*/
protected int horizontalScrollBarPolicy = HORIZONTAL_SCROLLBAR_AS_NEEDED;
/** {@collect.stats}
* The scrollpane's viewport child. Default is an empty
* <code>JViewport</code>.
* @see #setViewport
*/
protected JViewport viewport;
/** {@collect.stats}
* The scrollpane's vertical scrollbar child.
* Default is a <code>JScrollBar</code>.
* @see #setVerticalScrollBar
*/
protected JScrollBar verticalScrollBar;
/** {@collect.stats}
* The scrollpane's horizontal scrollbar child.
* Default is a <code>JScrollBar</code>.
* @see #setHorizontalScrollBar
*/
protected JScrollBar horizontalScrollBar;
/** {@collect.stats}
* The row header child. Default is <code>null</code>.
* @see #setRowHeader
*/
protected JViewport rowHeader;
/** {@collect.stats}
* The column header child. Default is <code>null</code>.
* @see #setColumnHeader
*/
protected JViewport columnHeader;
/** {@collect.stats}
* The component to display in the lower left corner.
* Default is <code>null</code>.
* @see #setCorner
*/
protected Component lowerLeft;
/** {@collect.stats}
* The component to display in the lower right corner.
* Default is <code>null</code>.
* @see #setCorner
*/
protected Component lowerRight;
/** {@collect.stats}
* The component to display in the upper left corner.
* Default is <code>null</code>.
* @see #setCorner
*/
protected Component upperLeft;
/** {@collect.stats}
* The component to display in the upper right corner.
* Default is <code>null</code>.
* @see #setCorner
*/
protected Component upperRight;
/*
* State flag for mouse wheel scrolling
*/
private boolean wheelScrollState = true;
/** {@collect.stats}
* Creates a <code>JScrollPane</code> that displays the view
* component in a viewport
* whose view position can be controlled with a pair of scrollbars.
* The scrollbar policies specify when the scrollbars are displayed,
* For example, if <code>vsbPolicy</code> is
* <code>VERTICAL_SCROLLBAR_AS_NEEDED</code>
* then the vertical scrollbar only appears if the view doesn't fit
* vertically. The available policy settings are listed at
* {@link #setVerticalScrollBarPolicy} and
* {@link #setHorizontalScrollBarPolicy}.
*
* @see #setViewportView
*
* @param view the component to display in the scrollpanes viewport
* @param vsbPolicy an integer that specifies the vertical
* scrollbar policy
* @param hsbPolicy an integer that specifies the horizontal
* scrollbar policy
*/
public JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
{
setLayout(new ScrollPaneLayout.UIResource());
setVerticalScrollBarPolicy(vsbPolicy);
setHorizontalScrollBarPolicy(hsbPolicy);
setViewport(createViewport());
setVerticalScrollBar(createVerticalScrollBar());
setHorizontalScrollBar(createHorizontalScrollBar());
if (view != null) {
setViewportView(view);
}
setUIProperty("opaque",true);
updateUI();
if (!this.getComponentOrientation().isLeftToRight()) {
viewport.setViewPosition(new Point(Integer.MAX_VALUE, 0));
}
}
/** {@collect.stats}
* Creates a <code>JScrollPane</code> that displays the
* contents of the specified
* component, where both horizontal and vertical scrollbars appear
* whenever the component's contents are larger than the view.
*
* @see #setViewportView
* @param view the component to display in the scrollpane's viewport
*/
public JScrollPane(Component view) {
this(view, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
/** {@collect.stats}
* Creates an empty (no viewport view) <code>JScrollPane</code>
* with specified
* scrollbar policies. The available policy settings are listed at
* {@link #setVerticalScrollBarPolicy} and
* {@link #setHorizontalScrollBarPolicy}.
*
* @see #setViewportView
*
* @param vsbPolicy an integer that specifies the vertical
* scrollbar policy
* @param hsbPolicy an integer that specifies the horizontal
* scrollbar policy
*/
public JScrollPane(int vsbPolicy, int hsbPolicy) {
this(null, vsbPolicy, hsbPolicy);
}
/** {@collect.stats}
* Creates an empty (no viewport view) <code>JScrollPane</code>
* where both horizontal and vertical scrollbars appear when needed.
*/
public JScrollPane() {
this(null, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
/** {@collect.stats}
* Returns the look and feel (L&F) object that renders this component.
*
* @return the <code>ScrollPaneUI</code> object that renders this
* component
* @see #setUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public ScrollPaneUI getUI() {
return (ScrollPaneUI)ui;
}
/** {@collect.stats}
* Sets the <code>ScrollPaneUI</code> object that provides the
* look and feel (L&F) for this component.
*
* @param ui the <code>ScrollPaneUI</code> L&F object
* @see #getUI
*/
public void setUI(ScrollPaneUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Replaces the current <code>ScrollPaneUI</code> object with a version
* from the current default look and feel.
* To be called when the default look and feel changes.
*
* @see JComponent#updateUI
* @see UIManager#getUI
*/
public void updateUI() {
setUI((ScrollPaneUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the suffix used to construct the name of the L&F class used to
* render this component.
*
* @return the string "ScrollPaneUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*
* @beaninfo
* hidden: true
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Sets the layout manager for this <code>JScrollPane</code>.
* This method overrides <code>setLayout</code> in
* <code>java.awt.Container</code> to ensure that only
* <code>LayoutManager</code>s which
* are subclasses of <code>ScrollPaneLayout</code> can be used in a
* <code>JScrollPane</code>. If <code>layout</code> is non-null, this
* will invoke <code>syncWithScrollPane</code> on it.
*
* @param layout the specified layout manager
* @exception ClassCastException if layout is not a
* <code>ScrollPaneLayout</code>
* @see java.awt.Container#getLayout
* @see java.awt.Container#setLayout
*
* @beaninfo
* hidden: true
*/
public void setLayout(LayoutManager layout) {
if (layout instanceof ScrollPaneLayout) {
super.setLayout(layout);
((ScrollPaneLayout)layout).syncWithScrollPane(this);
}
else if (layout == null) {
super.setLayout(layout);
}
else {
String s = "layout of JScrollPane must be a ScrollPaneLayout";
throw new ClassCastException(s);
}
}
/** {@collect.stats}
* Overridden to return true so that any calls to <code>revalidate</code>
* on any descendants of this <code>JScrollPane</code> will cause the
* entire tree beginning with this <code>JScrollPane</code> to be
* validated.
*
* @return true
* @see java.awt.Container#validate
* @see JComponent#revalidate
* @see JComponent#isValidateRoot
*
* @beaninfo
* hidden: true
*/
public boolean isValidateRoot() {
return true;
}
/** {@collect.stats}
* Returns the vertical scroll bar policy value.
* @return the <code>verticalScrollBarPolicy</code> property
* @see #setVerticalScrollBarPolicy
*/
public int getVerticalScrollBarPolicy() {
return verticalScrollBarPolicy;
}
/** {@collect.stats}
* Determines when the vertical scrollbar appears in the scrollpane.
* Legal values are:
* <ul>
* <li><code>ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED</code>
* <li><code>ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER</code>
* <li><code>ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS</code>
* </ul>
*
* @param policy one of the three values listed above
* @exception IllegalArgumentException if <code>policy</code>
* is not one of the legal values shown above
* @see #getVerticalScrollBarPolicy
*
* @beaninfo
* preferred: true
* bound: true
* description: The scrollpane vertical scrollbar policy
* enum: VERTICAL_SCROLLBAR_AS_NEEDED ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
* VERTICAL_SCROLLBAR_NEVER ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
* VERTICAL_SCROLLBAR_ALWAYS ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
*/
public void setVerticalScrollBarPolicy(int policy) {
switch (policy) {
case VERTICAL_SCROLLBAR_AS_NEEDED:
case VERTICAL_SCROLLBAR_NEVER:
case VERTICAL_SCROLLBAR_ALWAYS:
break;
default:
throw new IllegalArgumentException("invalid verticalScrollBarPolicy");
}
int old = verticalScrollBarPolicy;
verticalScrollBarPolicy = policy;
firePropertyChange("verticalScrollBarPolicy", old, policy);
revalidate();
repaint();
}
/** {@collect.stats}
* Returns the horizontal scroll bar policy value.
* @return the <code>horizontalScrollBarPolicy</code> property
* @see #setHorizontalScrollBarPolicy
*/
public int getHorizontalScrollBarPolicy() {
return horizontalScrollBarPolicy;
}
/** {@collect.stats}
* Determines when the horizontal scrollbar appears in the scrollpane.
* The options are:<ul>
* <li><code>ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED</code>
* <li><code>ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER</code>
* <li><code>ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS</code>
* </ul>
*
* @param policy one of the three values listed above
* @exception IllegalArgumentException if <code>policy</code>
* is not one of the legal values shown above
* @see #getHorizontalScrollBarPolicy
*
* @beaninfo
* preferred: true
* bound: true
* description: The scrollpane scrollbar policy
* enum: HORIZONTAL_SCROLLBAR_AS_NEEDED ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
* HORIZONTAL_SCROLLBAR_NEVER ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
* HORIZONTAL_SCROLLBAR_ALWAYS ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
*/
public void setHorizontalScrollBarPolicy(int policy) {
switch (policy) {
case HORIZONTAL_SCROLLBAR_AS_NEEDED:
case HORIZONTAL_SCROLLBAR_NEVER:
case HORIZONTAL_SCROLLBAR_ALWAYS:
break;
default:
throw new IllegalArgumentException("invalid horizontalScrollBarPolicy");
}
int old = horizontalScrollBarPolicy;
horizontalScrollBarPolicy = policy;
firePropertyChange("horizontalScrollBarPolicy", old, policy);
revalidate();
repaint();
}
/** {@collect.stats}
* Returns the <code>Border</code> object that surrounds the viewport.
*
* @return the <code>viewportBorder</code> property
* @see #setViewportBorder
*/
public Border getViewportBorder() {
return viewportBorder;
}
/** {@collect.stats}
* Adds a border around the viewport. Note that the border isn't
* set on the viewport directly, <code>JViewport</code> doesn't support
* the <code>JComponent</code> border property.
* Similarly setting the <code>JScrollPane</code>s
* viewport doesn't affect the <code>viewportBorder</code> property.
* <p>
* The default value of this property is computed by the look
* and feel implementation.
*
* @param viewportBorder the border to be added
* @see #getViewportBorder
* @see #setViewport
*
* @beaninfo
* preferred: true
* bound: true
* description: The border around the viewport.
*/
public void setViewportBorder(Border viewportBorder) {
Border oldValue = this.viewportBorder;
this.viewportBorder = viewportBorder;
firePropertyChange("viewportBorder", oldValue, viewportBorder);
}
/** {@collect.stats}
* Returns the bounds of the viewport's border.
*
* @return a <code>Rectangle</code> object specifying the viewport border
*/
public Rectangle getViewportBorderBounds()
{
Rectangle borderR = new Rectangle(getSize());
Insets insets = getInsets();
borderR.x = insets.left;
borderR.y = insets.top;
borderR.width -= insets.left + insets.right;
borderR.height -= insets.top + insets.bottom;
boolean leftToRight = SwingUtilities.isLeftToRight(this);
/* If there's a visible column header remove the space it
* needs from the top of borderR.
*/
JViewport colHead = getColumnHeader();
if ((colHead != null) && (colHead.isVisible())) {
int colHeadHeight = colHead.getHeight();
borderR.y += colHeadHeight;
borderR.height -= colHeadHeight;
}
/* If there's a visible row header remove the space it needs
* from the left of borderR.
*/
JViewport rowHead = getRowHeader();
if ((rowHead != null) && (rowHead.isVisible())) {
int rowHeadWidth = rowHead.getWidth();
if ( leftToRight ) {
borderR.x += rowHeadWidth;
}
borderR.width -= rowHeadWidth;
}
/* If there's a visible vertical scrollbar remove the space it needs
* from the width of borderR.
*/
JScrollBar vsb = getVerticalScrollBar();
if ((vsb != null) && (vsb.isVisible())) {
int vsbWidth = vsb.getWidth();
if ( !leftToRight ) {
borderR.x += vsbWidth;
}
borderR.width -= vsbWidth;
}
/* If there's a visible horizontal scrollbar remove the space it needs
* from the height of borderR.
*/
JScrollBar hsb = getHorizontalScrollBar();
if ((hsb != null) && (hsb.isVisible())) {
borderR.height -= hsb.getHeight();
}
return borderR;
}
/** {@collect.stats}
* By default <code>JScrollPane</code> creates scrollbars
* that are instances
* of this class. <code>Scrollbar</code> overrides the
* <code>getUnitIncrement</code> and <code>getBlockIncrement</code>
* methods so that, if the viewport's view is a <code>Scrollable</code>,
* the view is asked to compute these values. Unless
* the unit/block increment have been explicitly set.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see Scrollable
* @see JScrollPane#createVerticalScrollBar
* @see JScrollPane#createHorizontalScrollBar
*/
protected class ScrollBar extends JScrollBar implements UIResource
{
/** {@collect.stats}
* Set to true when the unit increment has been explicitly set.
* If this is false the viewport's view is obtained and if it
* is an instance of <code>Scrollable</code> the unit increment
* from it is used.
*/
private boolean unitIncrementSet;
/** {@collect.stats}
* Set to true when the block increment has been explicitly set.
* If this is false the viewport's view is obtained and if it
* is an instance of <code>Scrollable</code> the block increment
* from it is used.
*/
private boolean blockIncrementSet;
/** {@collect.stats}
* Creates a scrollbar with the specified orientation.
* The options are:
* <ul>
* <li><code>ScrollPaneConstants.VERTICAL</code>
* <li><code>ScrollPaneConstants.HORIZONTAL</code>
* </ul>
*
* @param orientation an integer specifying one of the legal
* orientation values shown above
* @since 1.4
*/
public ScrollBar(int orientation) {
super(orientation);
this.putClientProperty("JScrollBar.fastWheelScrolling",
Boolean.TRUE);
}
/** {@collect.stats}
* Messages super to set the value, and resets the
* <code>unitIncrementSet</code> instance variable to true.
*
* @param unitIncrement the new unit increment value, in pixels
*/
public void setUnitIncrement(int unitIncrement) {
unitIncrementSet = true;
this.putClientProperty("JScrollBar.fastWheelScrolling", null);
super.setUnitIncrement(unitIncrement);
}
/** {@collect.stats}
* Computes the unit increment for scrolling if the viewport's
* view is a <code>Scrollable</code> object.
* Otherwise return <code>super.getUnitIncrement</code>.
*
* @param direction less than zero to scroll up/left,
* greater than zero for down/right
* @return an integer, in pixels, containing the unit increment
* @see Scrollable#getScrollableUnitIncrement
*/
public int getUnitIncrement(int direction) {
JViewport vp = getViewport();
if (!unitIncrementSet && (vp != null) &&
(vp.getView() instanceof Scrollable)) {
Scrollable view = (Scrollable)(vp.getView());
Rectangle vr = vp.getViewRect();
return view.getScrollableUnitIncrement(vr, getOrientation(), direction);
}
else {
return super.getUnitIncrement(direction);
}
}
/** {@collect.stats}
* Messages super to set the value, and resets the
* <code>blockIncrementSet</code> instance variable to true.
*
* @param blockIncrement the new block increment value, in pixels
*/
public void setBlockIncrement(int blockIncrement) {
blockIncrementSet = true;
this.putClientProperty("JScrollBar.fastWheelScrolling", null);
super.setBlockIncrement(blockIncrement);
}
/** {@collect.stats}
* Computes the block increment for scrolling if the viewport's
* view is a <code>Scrollable</code> object. Otherwise
* the <code>blockIncrement</code> equals the viewport's width
* or height. If there's no viewport return
* <code>super.getBlockIncrement</code>.
*
* @param direction less than zero to scroll up/left,
* greater than zero for down/right
* @return an integer, in pixels, containing the block increment
* @see Scrollable#getScrollableBlockIncrement
*/
public int getBlockIncrement(int direction) {
JViewport vp = getViewport();
if (blockIncrementSet || vp == null) {
return super.getBlockIncrement(direction);
}
else if (vp.getView() instanceof Scrollable) {
Scrollable view = (Scrollable)(vp.getView());
Rectangle vr = vp.getViewRect();
return view.getScrollableBlockIncrement(vr, getOrientation(), direction);
}
else if (getOrientation() == VERTICAL) {
return vp.getExtentSize().height;
}
else {
return vp.getExtentSize().width;
}
}
}
/** {@collect.stats}
* Returns a <code>JScrollPane.ScrollBar</code> by default.
* Subclasses may override this method to force <code>ScrollPaneUI</code>
* implementations to use a <code>JScrollBar</code> subclass.
* Used by <code>ScrollPaneUI</code> implementations to
* create the horizontal scrollbar.
*
* @return a <code>JScrollBar</code> with a horizontal orientation
* @see JScrollBar
*/
public JScrollBar createHorizontalScrollBar() {
return new ScrollBar(JScrollBar.HORIZONTAL);
}
/** {@collect.stats}
* Returns the horizontal scroll bar that controls the viewport's
* horizontal view position.
*
* @return the <code>horizontalScrollBar</code> property
* @see #setHorizontalScrollBar
*/
public JScrollBar getHorizontalScrollBar() {
return horizontalScrollBar;
}
/** {@collect.stats}
* Adds the scrollbar that controls the viewport's horizontal view
* position to the scrollpane.
* This is usually unnecessary, as <code>JScrollPane</code> creates
* horizontal and vertical scrollbars by default.
*
* @param horizontalScrollBar the horizontal scrollbar to be added
* @see #createHorizontalScrollBar
* @see #getHorizontalScrollBar
*
* @beaninfo
* expert: true
* bound: true
* description: The horizontal scrollbar.
*/
public void setHorizontalScrollBar(JScrollBar horizontalScrollBar) {
JScrollBar old = getHorizontalScrollBar();
this.horizontalScrollBar = horizontalScrollBar;
if (horizontalScrollBar != null) {
add(horizontalScrollBar, HORIZONTAL_SCROLLBAR);
}
else if (old != null) {
remove(old);
}
firePropertyChange("horizontalScrollBar", old, horizontalScrollBar);
revalidate();
repaint();
}
/** {@collect.stats}
* Returns a <code>JScrollPane.ScrollBar</code> by default. Subclasses
* may override this method to force <code>ScrollPaneUI</code>
* implementations to use a <code>JScrollBar</code> subclass.
* Used by <code>ScrollPaneUI</code> implementations to create the
* vertical scrollbar.
*
* @return a <code>JScrollBar</code> with a vertical orientation
* @see JScrollBar
*/
public JScrollBar createVerticalScrollBar() {
return new ScrollBar(JScrollBar.VERTICAL);
}
/** {@collect.stats}
* Returns the vertical scroll bar that controls the viewports
* vertical view position.
*
* @return the <code>verticalScrollBar</code> property
* @see #setVerticalScrollBar
*/
public JScrollBar getVerticalScrollBar() {
return verticalScrollBar;
}
/** {@collect.stats}
* Adds the scrollbar that controls the viewports vertical view position
* to the scrollpane. This is usually unnecessary,
* as <code>JScrollPane</code> creates vertical and
* horizontal scrollbars by default.
*
* @param verticalScrollBar the new vertical scrollbar to be added
* @see #createVerticalScrollBar
* @see #getVerticalScrollBar
*
* @beaninfo
* expert: true
* bound: true
* description: The vertical scrollbar.
*/
public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
JScrollBar old = getVerticalScrollBar();
this.verticalScrollBar = verticalScrollBar;
add(verticalScrollBar, VERTICAL_SCROLLBAR);
firePropertyChange("verticalScrollBar", old, verticalScrollBar);
revalidate();
repaint();
}
/** {@collect.stats}
* Returns a new <code>JViewport</code> by default.
* Used to create the
* viewport (as needed) in <code>setViewportView</code>,
* <code>setRowHeaderView</code>, and <code>setColumnHeaderView</code>.
* Subclasses may override this method to return a subclass of
* <code>JViewport</code>.
*
* @return a new <code>JViewport</code>
*/
protected JViewport createViewport() {
return new JViewport();
}
/** {@collect.stats}
* Returns the current <code>JViewport</code>.
*
* @see #setViewport
* @return the <code>viewport</code> property
*/
public JViewport getViewport() {
return viewport;
}
/** {@collect.stats}
* Removes the old viewport (if there is one); forces the
* viewPosition of the new viewport to be in the +x,+y quadrant;
* syncs up the row and column headers (if there are any) with the
* new viewport; and finally syncs the scrollbars and
* headers with the new viewport.
* <p>
* Most applications will find it more convenient to use
* <code>setViewportView</code>
* to add a viewport and a view to the scrollpane.
*
* @param viewport the new viewport to be used; if viewport is
* <code>null</code>, the old viewport is still removed
* and the new viewport is set to <code>null</code>
* @see #createViewport
* @see #getViewport
* @see #setViewportView
*
* @beaninfo
* expert: true
* bound: true
* attribute: visualUpdate true
* description: The viewport child for this scrollpane
*
*/
public void setViewport(JViewport viewport) {
JViewport old = getViewport();
this.viewport = viewport;
if (viewport != null) {
add(viewport, VIEWPORT);
}
else if (old != null) {
remove(old);
}
firePropertyChange("viewport", old, viewport);
if (accessibleContext != null) {
((AccessibleJScrollPane)accessibleContext).resetViewPort();
}
revalidate();
repaint();
}
/** {@collect.stats}
* Creates a viewport if necessary and then sets its view. Applications
* that don't provide the view directly to the <code>JScrollPane</code>
* constructor
* should use this method to specify the scrollable child that's going
* to be displayed in the scrollpane. For example:
* <pre>
* JScrollPane scrollpane = new JScrollPane();
* scrollpane.setViewportView(myBigComponentToScroll);
* </pre>
* Applications should not add children directly to the scrollpane.
*
* @param view the component to add to the viewport
* @see #setViewport
* @see JViewport#setView
*/
public void setViewportView(Component view) {
if (getViewport() == null) {
setViewport(createViewport());
}
getViewport().setView(view);
}
/** {@collect.stats}
* Returns the row header.
* @return the <code>rowHeader</code> property
* @see #setRowHeader
*/
public JViewport getRowHeader() {
return rowHeader;
}
/** {@collect.stats}
* Removes the old rowHeader, if it exists; if the new rowHeader
* isn't <code>null</code>, syncs the y coordinate of its
* viewPosition with
* the viewport (if there is one) and then adds it to the scroll pane.
* <p>
* Most applications will find it more convenient to use
* <code>setRowHeaderView</code>
* to add a row header component and its viewport to the scroll pane.
*
* @param rowHeader the new row header to be used; if <code>null</code>
* the old row header is still removed and the new rowHeader
* is set to <code>null</code>
* @see #getRowHeader
* @see #setRowHeaderView
*
* @beaninfo
* bound: true
* expert: true
* description: The row header child for this scrollpane
*/
public void setRowHeader(JViewport rowHeader) {
JViewport old = getRowHeader();
this.rowHeader = rowHeader;
if (rowHeader != null) {
add(rowHeader, ROW_HEADER);
}
else if (old != null) {
remove(old);
}
firePropertyChange("rowHeader", old, rowHeader);
revalidate();
repaint();
}
/** {@collect.stats}
* Creates a row-header viewport if necessary, sets
* its view and then adds the row-header viewport
* to the scrollpane. For example:
* <pre>
* JScrollPane scrollpane = new JScrollPane();
* scrollpane.setViewportView(myBigComponentToScroll);
* scrollpane.setRowHeaderView(myBigComponentsRowHeader);
* </pre>
*
* @see #setRowHeader
* @see JViewport#setView
* @param view the component to display as the row header
*/
public void setRowHeaderView(Component view) {
if (getRowHeader() == null) {
setRowHeader(createViewport());
}
getRowHeader().setView(view);
}
/** {@collect.stats}
* Returns the column header.
* @return the <code>columnHeader</code> property
* @see #setColumnHeader
*/
public JViewport getColumnHeader() {
return columnHeader;
}
/** {@collect.stats}
* Removes the old columnHeader, if it exists; if the new columnHeader
* isn't <code>null</code>, syncs the x coordinate of its viewPosition
* with the viewport (if there is one) and then adds it to the scroll pane.
* <p>
* Most applications will find it more convenient to use
* <code>setColumnHeaderView</code>
* to add a column header component and its viewport to the scroll pane.
*
* @see #getColumnHeader
* @see #setColumnHeaderView
*
* @beaninfo
* bound: true
* description: The column header child for this scrollpane
* attribute: visualUpdate true
*/
public void setColumnHeader(JViewport columnHeader) {
JViewport old = getColumnHeader();
this.columnHeader = columnHeader;
if (columnHeader != null) {
add(columnHeader, COLUMN_HEADER);
}
else if (old != null) {
remove(old);
}
firePropertyChange("columnHeader", old, columnHeader);
revalidate();
repaint();
}
/** {@collect.stats}
* Creates a column-header viewport if necessary, sets
* its view, and then adds the column-header viewport
* to the scrollpane. For example:
* <pre>
* JScrollPane scrollpane = new JScrollPane();
* scrollpane.setViewportView(myBigComponentToScroll);
* scrollpane.setColumnHeaderView(myBigComponentsColumnHeader);
* </pre>
*
* @see #setColumnHeader
* @see JViewport#setView
*
* @param view the component to display as the column header
*/
public void setColumnHeaderView(Component view) {
if (getColumnHeader() == null) {
setColumnHeader(createViewport());
}
getColumnHeader().setView(view);
}
/** {@collect.stats}
* Returns the component at the specified corner. The
* <code>key</code> value specifying the corner is one of:
* <ul>
* <li>ScrollPaneConstants.LOWER_LEFT_CORNER
* <li>ScrollPaneConstants.LOWER_RIGHT_CORNER
* <li>ScrollPaneConstants.UPPER_LEFT_CORNER
* <li>ScrollPaneConstants.UPPER_RIGHT_CORNER
* <li>ScrollPaneConstants.LOWER_LEADING_CORNER
* <li>ScrollPaneConstants.LOWER_TRAILING_CORNER
* <li>ScrollPaneConstants.UPPER_LEADING_CORNER
* <li>ScrollPaneConstants.UPPER_TRAILING_CORNER
* </ul>
*
* @param key one of the values as shown above
* @return the corner component (which may be <code>null</code>)
* identified by the given key, or <code>null</code>
* if the key is invalid
* @see #setCorner
*/
public Component getCorner(String key) {
boolean isLeftToRight = getComponentOrientation().isLeftToRight();
if (key.equals(LOWER_LEADING_CORNER)) {
key = isLeftToRight ? LOWER_LEFT_CORNER : LOWER_RIGHT_CORNER;
} else if (key.equals(LOWER_TRAILING_CORNER)) {
key = isLeftToRight ? LOWER_RIGHT_CORNER : LOWER_LEFT_CORNER;
} else if (key.equals(UPPER_LEADING_CORNER)) {
key = isLeftToRight ? UPPER_LEFT_CORNER : UPPER_RIGHT_CORNER;
} else if (key.equals(UPPER_TRAILING_CORNER)) {
key = isLeftToRight ? UPPER_RIGHT_CORNER : UPPER_LEFT_CORNER;
}
if (key.equals(LOWER_LEFT_CORNER)) {
return lowerLeft;
}
else if (key.equals(LOWER_RIGHT_CORNER)) {
return lowerRight;
}
else if (key.equals(UPPER_LEFT_CORNER)) {
return upperLeft;
}
else if (key.equals(UPPER_RIGHT_CORNER)) {
return upperRight;
}
else {
return null;
}
}
/** {@collect.stats}
* Adds a child that will appear in one of the scroll panes
* corners, if there's room. For example with both scrollbars
* showing (on the right and bottom edges of the scrollpane)
* the lower left corner component will be shown in the space
* between ends of the two scrollbars. Legal values for
* the <b>key</b> are:
* <ul>
* <li>ScrollPaneConstants.LOWER_LEFT_CORNER
* <li>ScrollPaneConstants.LOWER_RIGHT_CORNER
* <li>ScrollPaneConstants.UPPER_LEFT_CORNER
* <li>ScrollPaneConstants.UPPER_RIGHT_CORNER
* <li>ScrollPaneConstants.LOWER_LEADING_CORNER
* <li>ScrollPaneConstants.LOWER_TRAILING_CORNER
* <li>ScrollPaneConstants.UPPER_LEADING_CORNER
* <li>ScrollPaneConstants.UPPER_TRAILING_CORNER
* </ul>
* <p>
* Although "corner" doesn't match any beans property
* signature, <code>PropertyChange</code> events are generated with the
* property name set to the corner key.
*
* @param key identifies which corner the component will appear in
* @param corner one of the following components:
* <ul>
* <li>lowerLeft
* <li>lowerRight
* <li>upperLeft
* <li>upperRight
* </ul>
* @exception IllegalArgumentException if corner key is invalid
*/
public void setCorner(String key, Component corner)
{
Component old;
boolean isLeftToRight = getComponentOrientation().isLeftToRight();
if (key.equals(LOWER_LEADING_CORNER)) {
key = isLeftToRight ? LOWER_LEFT_CORNER : LOWER_RIGHT_CORNER;
} else if (key.equals(LOWER_TRAILING_CORNER)) {
key = isLeftToRight ? LOWER_RIGHT_CORNER : LOWER_LEFT_CORNER;
} else if (key.equals(UPPER_LEADING_CORNER)) {
key = isLeftToRight ? UPPER_LEFT_CORNER : UPPER_RIGHT_CORNER;
} else if (key.equals(UPPER_TRAILING_CORNER)) {
key = isLeftToRight ? UPPER_RIGHT_CORNER : UPPER_LEFT_CORNER;
}
if (key.equals(LOWER_LEFT_CORNER)) {
old = lowerLeft;
lowerLeft = corner;
}
else if (key.equals(LOWER_RIGHT_CORNER)) {
old = lowerRight;
lowerRight = corner;
}
else if (key.equals(UPPER_LEFT_CORNER)) {
old = upperLeft;
upperLeft = corner;
}
else if (key.equals(UPPER_RIGHT_CORNER)) {
old = upperRight;
upperRight = corner;
}
else {
throw new IllegalArgumentException("invalid corner key");
}
if (old != null) {
remove(old);
}
if (corner != null) {
add(corner, key);
}
firePropertyChange(key, old, corner);
revalidate();
repaint();
}
/** {@collect.stats}
* Sets the orientation for the vertical and horizontal
* scrollbars as determined by the
* <code>ComponentOrientation</code> argument.
*
* @param co one of the following values:
* <ul>
* <li>java.awt.ComponentOrientation.LEFT_TO_RIGHT
* <li>java.awt.ComponentOrientation.RIGHT_TO_LEFT
* <li>java.awt.ComponentOrientation.UNKNOWN
* </ul>
* @see java.awt.ComponentOrientation
*/
public void setComponentOrientation( ComponentOrientation co ) {
super.setComponentOrientation( co );
if( verticalScrollBar != null )
verticalScrollBar.setComponentOrientation( co );
if( horizontalScrollBar != null )
horizontalScrollBar.setComponentOrientation( co );
}
/** {@collect.stats}
* Indicates whether or not scrolling will take place in response to the
* mouse wheel. Wheel scrolling is enabled by default.
*
* @see #setWheelScrollingEnabled
* @since 1.4
* @beaninfo
* bound: true
* description: Flag for enabling/disabling mouse wheel scrolling
*/
public boolean isWheelScrollingEnabled() {return wheelScrollState;}
/** {@collect.stats}
* Enables/disables scrolling in response to movement of the mouse wheel.
* Wheel scrolling is enabled by default.
*
* @param handleWheel <code>true</code> if scrolling should be done
* automatically for a MouseWheelEvent,
* <code>false</code> otherwise.
* @see #isWheelScrollingEnabled
* @see java.awt.event.MouseWheelEvent
* @see java.awt.event.MouseWheelListener
* @since 1.4
* @beaninfo
* bound: true
* description: Flag for enabling/disabling mouse wheel scrolling
*/
public void setWheelScrollingEnabled(boolean handleWheel) {
boolean old = wheelScrollState;
wheelScrollState = handleWheel;
firePropertyChange("wheelScrollingEnabled", old, handleWheel);
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JScrollPane</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JScrollPane</code>.
*/
protected String paramString() {
String viewportBorderString = (viewportBorder != null ?
viewportBorder.toString() : "");
String viewportString = (viewport != null ?
viewport.toString() : "");
String verticalScrollBarPolicyString;
if (verticalScrollBarPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) {
verticalScrollBarPolicyString = "VERTICAL_SCROLLBAR_AS_NEEDED";
} else if (verticalScrollBarPolicy == VERTICAL_SCROLLBAR_NEVER) {
verticalScrollBarPolicyString = "VERTICAL_SCROLLBAR_NEVER";
} else if (verticalScrollBarPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
verticalScrollBarPolicyString = "VERTICAL_SCROLLBAR_ALWAYS";
} else verticalScrollBarPolicyString = "";
String horizontalScrollBarPolicyString;
if (horizontalScrollBarPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) {
horizontalScrollBarPolicyString = "HORIZONTAL_SCROLLBAR_AS_NEEDED";
} else if (horizontalScrollBarPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
horizontalScrollBarPolicyString = "HORIZONTAL_SCROLLBAR_NEVER";
} else if (horizontalScrollBarPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
horizontalScrollBarPolicyString = "HORIZONTAL_SCROLLBAR_ALWAYS";
} else horizontalScrollBarPolicyString = "";
String horizontalScrollBarString = (horizontalScrollBar != null ?
horizontalScrollBar.toString()
: "");
String verticalScrollBarString = (verticalScrollBar != null ?
verticalScrollBar.toString() : "");
String columnHeaderString = (columnHeader != null ?
columnHeader.toString() : "");
String rowHeaderString = (rowHeader != null ?
rowHeader.toString() : "");
String lowerLeftString = (lowerLeft != null ?
lowerLeft.toString() : "");
String lowerRightString = (lowerRight != null ?
lowerRight.toString() : "");
String upperLeftString = (upperLeft != null ?
upperLeft.toString() : "");
String upperRightString = (upperRight != null ?
upperRight.toString() : "");
return super.paramString() +
",columnHeader=" + columnHeaderString +
",horizontalScrollBar=" + horizontalScrollBarString +
",horizontalScrollBarPolicy=" + horizontalScrollBarPolicyString +
",lowerLeft=" + lowerLeftString +
",lowerRight=" + lowerRightString +
",rowHeader=" + rowHeaderString +
",upperLeft=" + upperLeftString +
",upperRight=" + upperRightString +
",verticalScrollBar=" + verticalScrollBarString +
",verticalScrollBarPolicy=" + verticalScrollBarPolicyString +
",viewport=" + viewportString +
",viewportBorder=" + viewportBorderString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JScrollPane.
* For scroll panes, the AccessibleContext takes the form of an
* AccessibleJScrollPane.
* A new AccessibleJScrollPane instance is created if necessary.
*
* @return an AccessibleJScrollPane that serves as the
* AccessibleContext of this JScrollPane
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJScrollPane();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JScrollPane</code> class. It provides an implementation of the
* Java Accessibility API appropriate to scroll pane user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJScrollPane extends AccessibleJComponent
implements ChangeListener, PropertyChangeListener {
protected JViewport viewPort = null;
/*
* Resets the viewport ChangeListener and PropertyChangeListener
*/
public void resetViewPort() {
if (viewPort != null) {
viewPort.removeChangeListener(this);
viewPort.removePropertyChangeListener(this);
}
viewPort = JScrollPane.this.getViewport();
if (viewPort != null) {
viewPort.addChangeListener(this);
viewPort.addPropertyChangeListener(this);
}
}
/** {@collect.stats}
* AccessibleJScrollPane constructor
*/
public AccessibleJScrollPane() {
super();
resetViewPort();
// initialize the AccessibleRelationSets for the JScrollPane
// and JScrollBar(s)
JScrollBar scrollBar = getHorizontalScrollBar();
if (scrollBar != null) {
setScrollBarRelations(scrollBar);
}
scrollBar = getVerticalScrollBar();
if (scrollBar != null) {
setScrollBarRelations(scrollBar);
}
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.SCROLL_PANE;
}
/** {@collect.stats}
* Invoked when the target of the listener has changed its state.
*
* @param e a <code>ChangeEvent</code> object. Must not be null.
*
* @throws NullPointerException if the parameter is null.
*/
public void stateChanged(ChangeEvent e) {
if (e == null) {
throw new NullPointerException();
}
firePropertyChange(ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false),
Boolean.valueOf(true));
}
/** {@collect.stats}
* This method gets called when a bound property is changed.
* @param e A <code>PropertyChangeEvent</code> object describing
* the event source and the property that has changed. Must not be null.
*
* @throws NullPointerException if the parameter is null.
* @since 1.5
*/
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if (propertyName == "horizontalScrollBar" ||
propertyName == "verticalScrollBar") {
if (e.getNewValue() instanceof JScrollBar) {
setScrollBarRelations((JScrollBar)e.getNewValue());
}
}
}
/*
* Sets the CONTROLLER_FOR and CONTROLLED_BY AccessibleRelations for
* the JScrollPane and JScrollBar. JScrollBar must not be null.
*/
void setScrollBarRelations(JScrollBar scrollBar) {
/*
* The JScrollBar is a CONTROLLER_FOR the JScrollPane.
* The JScrollPane is CONTROLLED_BY the JScrollBar.
*/
AccessibleRelation controlledBy =
new AccessibleRelation(AccessibleRelation.CONTROLLED_BY,
scrollBar);
AccessibleRelation controllerFor =
new AccessibleRelation(AccessibleRelation.CONTROLLER_FOR,
JScrollPane.this);
// set the relation set for the scroll bar
AccessibleContext ac = scrollBar.getAccessibleContext();
ac.getAccessibleRelationSet().add(controllerFor);
// set the relation set for the scroll pane
getAccessibleRelationSet().add(controlledBy);
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
/** {@collect.stats}
* A class which implements a line border of arbitrary thickness
* and of a single color.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author David Kloba
*/
public class LineBorder extends AbstractBorder
{
private static Border blackLine;
private static Border grayLine;
protected int thickness;
protected Color lineColor;
protected boolean roundedCorners;
/** {@collect.stats} Convenience method for getting the Color.black LineBorder of thickness 1.
*/
public static Border createBlackLineBorder() {
if (blackLine == null) {
blackLine = new LineBorder(Color.black, 1);
}
return blackLine;
}
/** {@collect.stats} Convenience method for getting the Color.gray LineBorder of thickness 1.
*/
public static Border createGrayLineBorder() {
if (grayLine == null) {
grayLine = new LineBorder(Color.gray, 1);
}
return grayLine;
}
/** {@collect.stats}
* Creates a line border with the specified color and a
* thickness = 1.
* @param color the color for the border
*/
public LineBorder(Color color) {
this(color, 1, false);
}
/** {@collect.stats}
* Creates a line border with the specified color and thickness.
* @param color the color of the border
* @param thickness the thickness of the border
*/
public LineBorder(Color color, int thickness) {
this(color, thickness, false);
}
/** {@collect.stats}
* Creates a line border with the specified color, thickness,
* and corner shape.
* @param color the color of the border
* @param thickness the thickness of the border
* @param roundedCorners whether or not border corners should be round
* @since 1.3
*/
public LineBorder(Color color, int thickness, boolean roundedCorners) {
lineColor = color;
this.thickness = thickness;
this.roundedCorners = roundedCorners;
}
/** {@collect.stats}
* Paints the border for the specified component with the
* specified position and size.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if ((this.thickness > 0) && (g instanceof Graphics2D)) {
Graphics2D g2d = (Graphics2D) g;
Color oldColor = g2d.getColor();
g2d.setColor(this.lineColor);
Shape outer;
Shape inner;
int offs = this.thickness;
int size = offs + offs;
if (this.roundedCorners) {
int arc = offs + size;
outer = new RoundRectangle2D.Float(x, y, width, height, arc, arc);
inner = new RoundRectangle2D.Float(x + offs, y + offs, width - size, height - size, arc, arc);
}
else {
outer = new Rectangle2D.Float(x, y, width, height);
inner = new Rectangle2D.Float(x + offs, y + offs, width - size, height - size);
}
Path2D path = new Path2D.Float(Path2D.WIND_EVEN_ODD);
path.append(outer, false);
path.append(inner, false);
g2d.fill(path);
g2d.setColor(oldColor);
}
}
/** {@collect.stats}
* Returns the insets of the border.
* @param c the component for which this border insets value applies
*/
public Insets getBorderInsets(Component c) {
return new Insets(thickness, thickness, thickness, thickness);
}
/** {@collect.stats}
* Reinitialize the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
*/
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = insets.top = insets.right = insets.bottom = thickness;
return insets;
}
/** {@collect.stats}
* Returns the color of the border.
*/
public Color getLineColor() {
return lineColor;
}
/** {@collect.stats}
* Returns the thickness of the border.
*/
public int getThickness() {
return thickness;
}
/** {@collect.stats}
* Returns whether this border will be drawn with rounded corners.
* @since 1.3
*/
public boolean getRoundedCorners() {
return roundedCorners;
}
/** {@collect.stats}
* Returns whether or not the border is opaque.
*/
public boolean isBorderOpaque() {
return !roundedCorners;
}
}
|
Java
|
/*
* Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Component;
/** {@collect.stats}
* Interface describing an object capable of rendering a border
* around the edges of a swing component.
* For examples of using borders see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/border.html">How to Use Borders</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* In the Swing component set, borders supercede Insets as the
* mechanism for creating a (decorated or plain) area around the
* edge of a component.
* <p>
* Usage Notes:
* <ul>
* <li>Use EmptyBorder to create a plain border (this mechanism
* replaces its predecessor, <code>setInsets</code>).
* <li>Use CompoundBorder to nest multiple border objects, creating
* a single, combined border.
* <li>Border instances are designed to be shared. Rather than creating
* a new border object using one of border classes, use the
* BorderFactory methods, which produces a shared instance of the
* common border types.
* <li>Additional border styles include BevelBorder, SoftBevelBorder,
* EtchedBorder, LineBorder, TitledBorder, and MatteBorder.
* <li>To create a new border class, subclass AbstractBorder.
* </ul>
*
* @author David Kloba
* @author Amy Fowler
* @see javax.swing.BorderFactory
* @see EmptyBorder
* @see CompoundBorder
*/
public interface Border
{
/** {@collect.stats}
* Paints the border for the specified component with the specified
* position and size.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
void paintBorder(Component c, Graphics g, int x, int y, int width, int height);
/** {@collect.stats}
* Returns the insets of the border.
* @param c the component for which this border insets value applies
*/
Insets getBorderInsets(Component c);
/** {@collect.stats}
* Returns whether or not the border is opaque. If the border
* is opaque, it is responsible for filling in it's own
* background when painting.
*/
boolean isBorderOpaque();
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Component;
import java.io.Serializable;
/** {@collect.stats}
* A class that implements an empty border with no size.
* This provides a convenient base class from which other border
* classes can be easily derived.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author David Kloba
*/
public abstract class AbstractBorder implements Border, Serializable
{
/** {@collect.stats}
* This default implementation does no painting.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
}
/** {@collect.stats}
* This default implementation returns a new <code>Insets</code>
* instance where the <code>top</code>, <code>left</code>,
* <code>bottom</code>, and
* <code>right</code> fields are set to <code>0</code>.
* @param c the component for which this border insets value applies
* @return the new <code>Insets</code> object initialized to 0
*/
public Insets getBorderInsets(Component c) {
return new Insets(0, 0, 0, 0);
}
/** {@collect.stats}
* Reinitializes the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
* @return the <code>insets</code> object
*/
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = insets.top = insets.right = insets.bottom = 0;
return insets;
}
/** {@collect.stats}
* This default implementation returns false.
* @return false
*/
public boolean isBorderOpaque() { return false; }
/** {@collect.stats}
* This convenience method calls the static method.
* @param c the component for which this border is being computed
* @param x the x position of the border
* @param y the y position of the border
* @param width the width of the border
* @param height the height of the border
* @return a <code>Rectangle</code> containing the interior coordinates
*/
public Rectangle getInteriorRectangle(Component c, int x, int y, int width, int height) {
return getInteriorRectangle(c, this, x, y, width, height);
}
/** {@collect.stats}
* Returns a rectangle using the arguments minus the
* insets of the border. This is useful for determining the area
* that components should draw in that will not intersect the border.
* @param c the component for which this border is being computed
* @param b the <code>Border</code> object
* @param x the x position of the border
* @param y the y position of the border
* @param width the width of the border
* @param height the height of the border
* @return a <code>Rectangle</code> containing the interior coordinates
*/
public static Rectangle getInteriorRectangle(Component c, Border b, int x, int y, int width, int height) {
Insets insets;
if(b != null)
insets = b.getBorderInsets(c);
else
insets = new Insets(0, 0, 0, 0);
return new Rectangle(x + insets.left,
y + insets.top,
width - insets.right - insets.left,
height - insets.top - insets.bottom);
}
/** {@collect.stats}
* Returns the baseline. A return value less than 0 indicates the border
* does not have a reasonable baseline.
* <p>
* The default implementation returns -1. Subclasses that support
* baseline should override appropriately. If a value >= 0 is
* returned, then the component has a valid baseline for any
* size >= the minimum size and <code>getBaselineResizeBehavior</code>
* can be used to determine how the baseline changes with size.
*
* @param c <code>Component</code> baseline is being requested for
* @param width the width to get the baseline for
* @param height the height to get the baseline for
* @return the baseline or < 0 indicating there is no reasonable
* baseline
* @throws IllegalArgumentException if width or height is < 0
* @see java.awt.Component#getBaseline(int,int)
* @see java.awt.Component#getBaselineResizeBehavior()
* @since 1.6
*/
public int getBaseline(Component c, int width, int height) {
if (width < 0 || height < 0) {
throw new IllegalArgumentException(
"Width and height must be >= 0");
}
return -1;
}
/** {@collect.stats}
* Returns an enum indicating how the baseline of a component
* changes as the size changes. This method is primarily meant for
* layout managers and GUI builders.
* <p>
* The default implementation returns
* <code>BaselineResizeBehavior.OTHER</code>, subclasses that support
* baseline should override appropriately. Subclasses should
* never return <code>null</code>; if the baseline can not be
* calculated return <code>BaselineResizeBehavior.OTHER</code>. Callers
* should first ask for the baseline using
* <code>getBaseline</code> and if a value >= 0 is returned use
* this method. It is acceptable for this method to return a
* value other than <code>BaselineResizeBehavior.OTHER</code> even if
* <code>getBaseline</code> returns a value less than 0.
*
* @param c <code>Component</code> to return baseline resize behavior for
* @return an enum indicating how the baseline changes as the border is
* resized
* @see java.awt.Component#getBaseline(int,int)
* @see java.awt.Component#getBaselineResizeBehavior()
* @since 1.6
*/
public Component.BaselineResizeBehavior getBaselineResizeBehavior(
Component c) {
if (c == null) {
throw new NullPointerException("Component must be non-null");
}
return Component.BaselineResizeBehavior.OTHER;
}
/*
* Convenience function for determining ComponentOrientation.
* Helps us avoid having Munge directives throughout the code.
*/
static boolean isLeftToRight( Component c ) {
return c.getComponentOrientation().isLeftToRight();
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Component;
/** {@collect.stats}
* A class which implements a simple two-line bevel border.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author David Kloba
*/
public class BevelBorder extends AbstractBorder
{
/** {@collect.stats} Raised bevel type. */
public static final int RAISED = 0;
/** {@collect.stats} Lowered bevel type. */
public static final int LOWERED = 1;
protected int bevelType;
protected Color highlightOuter;
protected Color highlightInner;
protected Color shadowInner;
protected Color shadowOuter;
/** {@collect.stats}
* Creates a bevel border with the specified type and whose
* colors will be derived from the background color of the
* component passed into the paintBorder method.
* @param bevelType the type of bevel for the border
*/
public BevelBorder(int bevelType) {
this.bevelType = bevelType;
}
/** {@collect.stats}
* Creates a bevel border with the specified type, highlight and
* shadow colors.
* @param bevelType the type of bevel for the border
* @param highlight the color to use for the bevel highlight
* @param shadow the color to use for the bevel shadow
*/
public BevelBorder(int bevelType, Color highlight, Color shadow) {
this(bevelType, highlight.brighter(), highlight, shadow, shadow.brighter());
}
/** {@collect.stats}
* Creates a bevel border with the specified type, highlight and
* shadow colors.
* <p>
* Note: The shadow inner and outer colors are
* switched for a lowered bevel border.
*
* @param bevelType the type of bevel for the border
* @param highlightOuterColor the color to use for the bevel outer highlight
* @param highlightInnerColor the color to use for the bevel inner highlight
* @param shadowOuterColor the color to use for the bevel outer shadow
* @param shadowInnerColor the color to use for the bevel inner shadow
*/
public BevelBorder(int bevelType, Color highlightOuterColor,
Color highlightInnerColor, Color shadowOuterColor,
Color shadowInnerColor) {
this(bevelType);
this.highlightOuter = highlightOuterColor;
this.highlightInner = highlightInnerColor;
this.shadowOuter = shadowOuterColor;
this.shadowInner = shadowInnerColor;
}
/** {@collect.stats}
* Paints the border for the specified component with the specified
* position and size.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if (bevelType == RAISED) {
paintRaisedBevel(c, g, x, y, width, height);
} else if (bevelType == LOWERED) {
paintLoweredBevel(c, g, x, y, width, height);
}
}
/** {@collect.stats}
* Returns the insets of the border.
* @param c the component for which this border insets value applies
*/
public Insets getBorderInsets(Component c) {
return new Insets(2, 2, 2, 2);
}
/** {@collect.stats}
* Reinitialize the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
*/
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = insets.top = insets.right = insets.bottom = 2;
return insets;
}
/** {@collect.stats}
* Returns the outer highlight color of the bevel border
* when rendered on the specified component. If no highlight
* color was specified at instantiation, the highlight color
* is derived from the specified component's background color.
* @param c the component for which the highlight may be derived
* @since 1.3
*/
public Color getHighlightOuterColor(Component c) {
Color highlight = getHighlightOuterColor();
return highlight != null? highlight :
c.getBackground().brighter().brighter();
}
/** {@collect.stats}
* Returns the inner highlight color of the bevel border
* when rendered on the specified component. If no highlight
* color was specified at instantiation, the highlight color
* is derived from the specified component's background color.
* @param c the component for which the highlight may be derived
* @since 1.3
*/
public Color getHighlightInnerColor(Component c) {
Color highlight = getHighlightInnerColor();
return highlight != null? highlight :
c.getBackground().brighter();
}
/** {@collect.stats}
* Returns the inner shadow color of the bevel border
* when rendered on the specified component. If no shadow
* color was specified at instantiation, the shadow color
* is derived from the specified component's background color.
* @param c the component for which the shadow may be derived
* @since 1.3
*/
public Color getShadowInnerColor(Component c) {
Color shadow = getShadowInnerColor();
return shadow != null? shadow :
c.getBackground().darker();
}
/** {@collect.stats}
* Returns the outer shadow color of the bevel border
* when rendered on the specified component. If no shadow
* color was specified at instantiation, the shadow color
* is derived from the specified component's background color.
* @param c the component for which the shadow may be derived
* @since 1.3
*/
public Color getShadowOuterColor(Component c) {
Color shadow = getShadowOuterColor();
return shadow != null? shadow :
c.getBackground().darker().darker();
}
/** {@collect.stats}
* Returns the outer highlight color of the bevel border.
* Will return null if no highlight color was specified
* at instantiation.
* @since 1.3
*/
public Color getHighlightOuterColor() {
return highlightOuter;
}
/** {@collect.stats}
* Returns the inner highlight color of the bevel border.
* Will return null if no highlight color was specified
* at instantiation.
* @since 1.3
*/
public Color getHighlightInnerColor() {
return highlightInner;
}
/** {@collect.stats}
* Returns the inner shadow color of the bevel border.
* Will return null if no shadow color was specified
* at instantiation.
* @since 1.3
*/
public Color getShadowInnerColor() {
return shadowInner;
}
/** {@collect.stats}
* Returns the outer shadow color of the bevel border.
* Will return null if no shadow color was specified
* at instantiation.
* @since 1.3
*/
public Color getShadowOuterColor() {
return shadowOuter;
}
/** {@collect.stats}
* Returns the type of the bevel border.
*/
public int getBevelType() {
return bevelType;
}
/** {@collect.stats}
* Returns whether or not the border is opaque.
*/
public boolean isBorderOpaque() { return true; }
protected void paintRaisedBevel(Component c, Graphics g, int x, int y,
int width, int height) {
Color oldColor = g.getColor();
int h = height;
int w = width;
g.translate(x, y);
g.setColor(getHighlightOuterColor(c));
g.drawLine(0, 0, 0, h-2);
g.drawLine(1, 0, w-2, 0);
g.setColor(getHighlightInnerColor(c));
g.drawLine(1, 1, 1, h-3);
g.drawLine(2, 1, w-3, 1);
g.setColor(getShadowOuterColor(c));
g.drawLine(0, h-1, w-1, h-1);
g.drawLine(w-1, 0, w-1, h-2);
g.setColor(getShadowInnerColor(c));
g.drawLine(1, h-2, w-2, h-2);
g.drawLine(w-2, 1, w-2, h-3);
g.translate(-x, -y);
g.setColor(oldColor);
}
protected void paintLoweredBevel(Component c, Graphics g, int x, int y,
int width, int height) {
Color oldColor = g.getColor();
int h = height;
int w = width;
g.translate(x, y);
g.setColor(getShadowInnerColor(c));
g.drawLine(0, 0, 0, h-1);
g.drawLine(1, 0, w-1, 0);
g.setColor(getShadowOuterColor(c));
g.drawLine(1, 1, 1, h-2);
g.drawLine(2, 1, w-2, 1);
g.setColor(getHighlightOuterColor(c));
g.drawLine(1, h-1, w-1, h-1);
g.drawLine(w-1, 1, w-1, h-2);
g.setColor(getHighlightInnerColor(c));
g.drawLine(2, h-2, w-2, h-2);
g.drawLine(w-2, 2, w-2, h-3);
g.translate(-x, -y);
g.setColor(oldColor);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import sun.swing.SwingUtilities2;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JComponent;
import javax.swing.UIManager;
/** {@collect.stats}
* A class which implements an arbitrary border
* with the addition of a String title in a
* specified position and justification.
* <p>
* If the border, font, or color property values are not
* specified in the constuctor or by invoking the appropriate
* set methods, the property values will be defined by the current
* look and feel, using the following property names in the
* Defaults Table:
* <ul>
* <li>"TitledBorder.border"
* <li>"TitledBorder.font"
* <li>"TitledBorder.titleColor"
* </ul>
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author David Kloba
* @author Amy Fowler
*/
public class TitledBorder extends AbstractBorder
{
protected String title;
protected Border border;
protected int titlePosition;
protected int titleJustification;
protected Font titleFont;
protected Color titleColor;
private Point textLoc = new Point();
/** {@collect.stats}
* Use the default vertical orientation for the title text.
*/
static public final int DEFAULT_POSITION = 0;
/** {@collect.stats} Position the title above the border's top line. */
static public final int ABOVE_TOP = 1;
/** {@collect.stats} Position the title in the middle of the border's top line. */
static public final int TOP = 2;
/** {@collect.stats} Position the title below the border's top line. */
static public final int BELOW_TOP = 3;
/** {@collect.stats} Position the title above the border's bottom line. */
static public final int ABOVE_BOTTOM = 4;
/** {@collect.stats} Position the title in the middle of the border's bottom line. */
static public final int BOTTOM = 5;
/** {@collect.stats} Position the title below the border's bottom line. */
static public final int BELOW_BOTTOM = 6;
/** {@collect.stats}
* Use the default justification for the title text.
*/
static public final int DEFAULT_JUSTIFICATION = 0;
/** {@collect.stats} Position title text at the left side of the border line. */
static public final int LEFT = 1;
/** {@collect.stats} Position title text in the center of the border line. */
static public final int CENTER = 2;
/** {@collect.stats} Position title text at the right side of the border line. */
static public final int RIGHT = 3;
/** {@collect.stats} Position title text at the left side of the border line
* for left to right orientation, at the right side of the
* border line for right to left orientation.
*/
static public final int LEADING = 4;
/** {@collect.stats} Position title text at the right side of the border line
* for left to right orientation, at the left side of the
* border line for right to left orientation.
*/
static public final int TRAILING = 5;
// Space between the border and the component's edge
static protected final int EDGE_SPACING = 2;
// Space between the border and text
static protected final int TEXT_SPACING = 2;
// Horizontal inset of text that is left or right justified
static protected final int TEXT_INSET_H = 5;
/** {@collect.stats}
* Creates a TitledBorder instance.
*
* @param title the title the border should display
*/
public TitledBorder(String title) {
this(null, title, LEADING, DEFAULT_POSITION, null, null);
}
/** {@collect.stats}
* Creates a TitledBorder instance with the specified border
* and an empty title.
*
* @param border the border
*/
public TitledBorder(Border border) {
this(border, "", LEADING, DEFAULT_POSITION, null, null);
}
/** {@collect.stats}
* Creates a TitledBorder instance with the specified border
* and title.
*
* @param border the border
* @param title the title the border should display
*/
public TitledBorder(Border border, String title) {
this(border, title, LEADING, DEFAULT_POSITION, null, null);
}
/** {@collect.stats}
* Creates a TitledBorder instance with the specified border,
* title, title-justification, and title-position.
*
* @param border the border
* @param title the title the border should display
* @param titleJustification the justification for the title
* @param titlePosition the position for the title
*/
public TitledBorder(Border border,
String title,
int titleJustification,
int titlePosition) {
this(border, title, titleJustification,
titlePosition, null, null);
}
/** {@collect.stats}
* Creates a TitledBorder instance with the specified border,
* title, title-justification, title-position, and title-font.
*
* @param border the border
* @param title the title the border should display
* @param titleJustification the justification for the title
* @param titlePosition the position for the title
* @param titleFont the font for rendering the title
*/
public TitledBorder(Border border,
String title,
int titleJustification,
int titlePosition,
Font titleFont) {
this(border, title, titleJustification,
titlePosition, titleFont, null);
}
/** {@collect.stats}
* Creates a TitledBorder instance with the specified border,
* title, title-justification, title-position, title-font, and
* title-color.
*
* @param border the border
* @param title the title the border should display
* @param titleJustification the justification for the title
* @param titlePosition the position for the title
* @param titleFont the font of the title
* @param titleColor the color of the title
*/
public TitledBorder(Border border,
String title,
int titleJustification,
int titlePosition,
Font titleFont,
Color titleColor) {
this.title = title;
this.border = border;
this.titleFont = titleFont;
this.titleColor = titleColor;
setTitleJustification(titleJustification);
setTitlePosition(titlePosition);
}
/** {@collect.stats}
* Paints the border for the specified component with the
* specified position and size.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Border border = getBorder();
if (getTitle() == null || getTitle().equals("")) {
if (border != null) {
border.paintBorder(c, g, x, y, width, height);
}
return;
}
Rectangle grooveRect = new Rectangle(x + EDGE_SPACING, y + EDGE_SPACING,
width - (EDGE_SPACING * 2),
height - (EDGE_SPACING * 2));
Font font = g.getFont();
Color color = g.getColor();
g.setFont(getFont(c));
JComponent jc = (c instanceof JComponent) ? (JComponent)c : null;
FontMetrics fm = SwingUtilities2.getFontMetrics(jc, g);
int fontHeight = fm.getHeight();
int descent = fm.getDescent();
int ascent = fm.getAscent();
int diff;
int stringWidth = SwingUtilities2.stringWidth(jc, fm,
getTitle());
Insets insets;
if (border != null) {
insets = border.getBorderInsets(c);
} else {
insets = new Insets(0, 0, 0, 0);
}
int titlePos = getTitlePosition();
switch (titlePos) {
case ABOVE_TOP:
diff = ascent + descent + (Math.max(EDGE_SPACING,
TEXT_SPACING*2) - EDGE_SPACING);
grooveRect.y += diff;
grooveRect.height -= diff;
textLoc.y = grooveRect.y - (descent + TEXT_SPACING);
break;
case TOP:
case DEFAULT_POSITION:
diff = Math.max(0, ((ascent/2) + TEXT_SPACING) - EDGE_SPACING);
grooveRect.y += diff;
grooveRect.height -= diff;
textLoc.y = (grooveRect.y - descent) +
(insets.top + ascent + descent)/2;
break;
case BELOW_TOP:
textLoc.y = grooveRect.y + insets.top + ascent + TEXT_SPACING;
break;
case ABOVE_BOTTOM:
textLoc.y = (grooveRect.y + grooveRect.height) -
(insets.bottom + descent + TEXT_SPACING);
break;
case BOTTOM:
grooveRect.height -= fontHeight/2;
textLoc.y = ((grooveRect.y + grooveRect.height) - descent) +
((ascent + descent) - insets.bottom)/2;
break;
case BELOW_BOTTOM:
grooveRect.height -= fontHeight;
textLoc.y = grooveRect.y + grooveRect.height + ascent +
TEXT_SPACING;
break;
}
int justification = getTitleJustification();
if(isLeftToRight(c)) {
if(justification==LEADING ||
justification==DEFAULT_JUSTIFICATION) {
justification = LEFT;
}
else if(justification==TRAILING) {
justification = RIGHT;
}
}
else {
if(justification==LEADING ||
justification==DEFAULT_JUSTIFICATION) {
justification = RIGHT;
}
else if(justification==TRAILING) {
justification = LEFT;
}
}
switch (justification) {
case LEFT:
textLoc.x = grooveRect.x + TEXT_INSET_H + insets.left;
break;
case RIGHT:
textLoc.x = (grooveRect.x + grooveRect.width) -
(stringWidth + TEXT_INSET_H + insets.right);
break;
case CENTER:
textLoc.x = grooveRect.x +
((grooveRect.width - stringWidth) / 2);
break;
}
// If title is positioned in middle of border AND its fontsize
// is greater than the border's thickness, we'll need to paint
// the border in sections to leave space for the component's background
// to show through the title.
//
if (border != null) {
if (((titlePos == TOP || titlePos == DEFAULT_POSITION) &&
(grooveRect.y > textLoc.y - ascent)) ||
(titlePos == BOTTOM &&
(grooveRect.y + grooveRect.height < textLoc.y + descent))) {
Rectangle clipRect = new Rectangle();
// save original clip
Rectangle saveClip = g.getClipBounds();
// paint strip left of text
clipRect.setBounds(saveClip);
if (computeIntersection(clipRect, x, y, textLoc.x-1-x, height)) {
g.setClip(clipRect);
border.paintBorder(c, g, grooveRect.x, grooveRect.y,
grooveRect.width, grooveRect.height);
}
// paint strip right of text
clipRect.setBounds(saveClip);
if (computeIntersection(clipRect, textLoc.x+stringWidth+1, y,
x+width-(textLoc.x+stringWidth+1), height)) {
g.setClip(clipRect);
border.paintBorder(c, g, grooveRect.x, grooveRect.y,
grooveRect.width, grooveRect.height);
}
if (titlePos == TOP || titlePos == DEFAULT_POSITION) {
// paint strip below text
clipRect.setBounds(saveClip);
if (computeIntersection(clipRect, textLoc.x-1, textLoc.y+descent,
stringWidth+2, y+height-textLoc.y-descent)) {
g.setClip(clipRect);
border.paintBorder(c, g, grooveRect.x, grooveRect.y,
grooveRect.width, grooveRect.height);
}
} else { // titlePos == BOTTOM
// paint strip above text
clipRect.setBounds(saveClip);
if (computeIntersection(clipRect, textLoc.x-1, y,
stringWidth+2, textLoc.y - ascent - y)) {
g.setClip(clipRect);
border.paintBorder(c, g, grooveRect.x, grooveRect.y,
grooveRect.width, grooveRect.height);
}
}
// restore clip
g.setClip(saveClip);
} else {
border.paintBorder(c, g, grooveRect.x, grooveRect.y,
grooveRect.width, grooveRect.height);
}
}
g.setColor(getTitleColor());
SwingUtilities2.drawString(jc, g, getTitle(), textLoc.x, textLoc.y);
g.setFont(font);
g.setColor(color);
}
/** {@collect.stats}
* Returns the insets of the border.
* @param c the component for which this border insets value applies
*/
public Insets getBorderInsets(Component c) {
return getBorderInsets(c, new Insets(0, 0, 0, 0));
}
/** {@collect.stats}
* Reinitialize the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
*/
public Insets getBorderInsets(Component c, Insets insets) {
FontMetrics fm;
int descent = 0;
int ascent = 16;
int height = 16;
Border border = getBorder();
if (border != null) {
if (border instanceof AbstractBorder) {
((AbstractBorder)border).getBorderInsets(c, insets);
} else {
// Can't reuse border insets because the Border interface
// can't be enhanced.
Insets i = border.getBorderInsets(c);
insets.top = i.top;
insets.right = i.right;
insets.bottom = i.bottom;
insets.left = i.left;
}
} else {
insets.left = insets.top = insets.right = insets.bottom = 0;
}
insets.left += EDGE_SPACING + TEXT_SPACING;
insets.right += EDGE_SPACING + TEXT_SPACING;
insets.top += EDGE_SPACING + TEXT_SPACING;
insets.bottom += EDGE_SPACING + TEXT_SPACING;
if(c == null || getTitle() == null || getTitle().equals("")) {
return insets;
}
Font font = getFont(c);
fm = c.getFontMetrics(font);
if(fm != null) {
descent = fm.getDescent();
ascent = fm.getAscent();
height = fm.getHeight();
}
switch (getTitlePosition()) {
case ABOVE_TOP:
insets.top += ascent + descent
+ (Math.max(EDGE_SPACING, TEXT_SPACING*2)
- EDGE_SPACING);
break;
case TOP:
case DEFAULT_POSITION:
insets.top += ascent + descent;
break;
case BELOW_TOP:
insets.top += ascent + descent + TEXT_SPACING;
break;
case ABOVE_BOTTOM:
insets.bottom += ascent + descent + TEXT_SPACING;
break;
case BOTTOM:
insets.bottom += ascent + descent;
break;
case BELOW_BOTTOM:
insets.bottom += height;
break;
}
return insets;
}
/** {@collect.stats}
* Returns whether or not the border is opaque.
*/
public boolean isBorderOpaque() { return false; }
/** {@collect.stats}
* Returns the title of the titled border.
*/
public String getTitle() { return title; }
/** {@collect.stats}
* Returns the border of the titled border.
*/
public Border getBorder() {
Border b = border;
if (b == null)
b = UIManager.getBorder("TitledBorder.border");
return b;
}
/** {@collect.stats}
* Returns the title-position of the titled border.
*/
public int getTitlePosition() {
if (titlePosition == DEFAULT_POSITION) {
Object value = UIManager.get("TitledBorder.position");
if (value instanceof String) {
String s = (String)value;
if ("ABOVE_TOP".equalsIgnoreCase(s)) {
return ABOVE_TOP;
} else if ("TOP".equalsIgnoreCase(s)) {
return TOP;
} else if ("BELOW_TOP".equalsIgnoreCase(s)) {
return BELOW_TOP;
} else if ("ABOVE_BOTTOM".equalsIgnoreCase(s)) {
return ABOVE_BOTTOM;
} else if ("BOTTOM".equalsIgnoreCase(s)) {
return BOTTOM;
} else if ("BELOW_BOTTOM".equalsIgnoreCase(s)) {
return BELOW_BOTTOM;
}
} else if (value instanceof Integer) {
int i = (Integer)value;
if (i >= 0 && i <= 6) {
return i;
}
}
}
return titlePosition;
}
/** {@collect.stats}
* Returns the title-justification of the titled border.
*/
public int getTitleJustification() { return titleJustification; }
/** {@collect.stats}
* Returns the title-font of the titled border.
*/
public Font getTitleFont() {
Font f = titleFont;
if (f == null)
f = UIManager.getFont("TitledBorder.font");
return f;
}
/** {@collect.stats}
* Returns the title-color of the titled border.
*/
public Color getTitleColor() {
Color c = titleColor;
if (c == null)
c = UIManager.getColor("TitledBorder.titleColor");
return c;
}
// REMIND(aim): remove all or some of these set methods?
/** {@collect.stats}
* Sets the title of the titled border.
* param title the title for the border
*/
public void setTitle(String title) { this.title = title; }
/** {@collect.stats}
* Sets the border of the titled border.
* @param border the border
*/
public void setBorder(Border border) { this.border = border; }
/** {@collect.stats}
* Sets the title-position of the titled border.
* @param titlePosition the position for the border
*/
public void setTitlePosition(int titlePosition) {
switch (titlePosition) {
case ABOVE_TOP:
case TOP:
case BELOW_TOP:
case ABOVE_BOTTOM:
case BOTTOM:
case BELOW_BOTTOM:
case DEFAULT_POSITION:
this.titlePosition = titlePosition;
break;
default:
throw new IllegalArgumentException(titlePosition +
" is not a valid title position.");
}
}
/** {@collect.stats}
* Sets the title-justification of the titled border.
* @param titleJustification the justification for the border
*/
public void setTitleJustification(int titleJustification) {
switch (titleJustification) {
case DEFAULT_JUSTIFICATION:
case LEFT:
case CENTER:
case RIGHT:
case LEADING:
case TRAILING:
this.titleJustification = titleJustification;
break;
default:
throw new IllegalArgumentException(titleJustification +
" is not a valid title justification.");
}
}
/** {@collect.stats}
* Sets the title-font of the titled border.
* @param titleFont the font for the border title
*/
public void setTitleFont(Font titleFont) {
this.titleFont = titleFont;
}
/** {@collect.stats}
* Sets the title-color of the titled border.
* @param titleColor the color for the border title
*/
public void setTitleColor(Color titleColor) {
this.titleColor = titleColor;
}
/** {@collect.stats}
* Returns the minimum dimensions this border requires
* in order to fully display the border and title.
* @param c the component where this border will be drawn
*/
public Dimension getMinimumSize(Component c) {
Insets insets = getBorderInsets(c);
Dimension minSize = new Dimension(insets.right+insets.left,
insets.top+insets.bottom);
Font font = getFont(c);
FontMetrics fm = c.getFontMetrics(font);
JComponent jc = (c instanceof JComponent) ? (JComponent)c : null;
switch (getTitlePosition()) {
case ABOVE_TOP:
case BELOW_BOTTOM:
minSize.width = Math.max(SwingUtilities2.stringWidth(jc, fm,
getTitle()), minSize.width);
break;
case BELOW_TOP:
case ABOVE_BOTTOM:
case TOP:
case BOTTOM:
case DEFAULT_POSITION:
default:
minSize.width += SwingUtilities2.stringWidth(jc, fm, getTitle());
}
return minSize;
}
/** {@collect.stats}
* Returns the baseline.
*
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @see javax.swing.JComponent#getBaseline(int, int)
* @since 1.6
*/
public int getBaseline(Component c, int width, int height) {
if (c == null) {
throw new NullPointerException("Must supply non-null component");
}
if (height < 0) {
throw new IllegalArgumentException("Height must be >= 0");
}
String title = getTitle();
if (title != null && !"".equals(title)) {
Font font = getFont(c);
Border border2 = getBorder();
Insets borderInsets;
if (border2 != null) {
borderInsets = border2.getBorderInsets(c);
}
else {
borderInsets = new Insets(0, 0, 0, 0);
}
FontMetrics fm = c.getFontMetrics(font);
int fontHeight = fm.getHeight();
int descent = fm.getDescent();
int ascent = fm.getAscent();
int y = EDGE_SPACING;
int h = height - EDGE_SPACING * 2;
int diff;
switch (getTitlePosition()) {
case ABOVE_TOP:
diff = ascent + descent + (Math.max(EDGE_SPACING,
TEXT_SPACING * 2) -
EDGE_SPACING);
return y + diff - (descent + TEXT_SPACING);
case TOP:
case DEFAULT_POSITION:
diff = Math.max(0, ((ascent/2) + TEXT_SPACING) -
EDGE_SPACING);
return (y + diff - descent) +
(borderInsets.top + ascent + descent)/2;
case BELOW_TOP:
return y + borderInsets.top + ascent + TEXT_SPACING;
case ABOVE_BOTTOM:
return (y + h) - (borderInsets.bottom + descent +
TEXT_SPACING);
case BOTTOM:
h -= fontHeight / 2;
return ((y + h) - descent) +
((ascent + descent) - borderInsets.bottom)/2;
case BELOW_BOTTOM:
h -= fontHeight;
return y + h + ascent + TEXT_SPACING;
}
}
return -1;
}
/** {@collect.stats}
* Returns an enum indicating how the baseline of the border
* changes as the size changes.
*
* @throws NullPointerException {@inheritDoc}
* @see javax.swing.JComponent#getBaseline(int, int)
* @since 1.6
*/
public Component.BaselineResizeBehavior getBaselineResizeBehavior(
Component c) {
super.getBaselineResizeBehavior(c);
switch(getTitlePosition()) {
case TitledBorder.ABOVE_TOP:
case TitledBorder.TOP:
case TitledBorder.DEFAULT_POSITION:
case TitledBorder.BELOW_TOP:
return Component.BaselineResizeBehavior.CONSTANT_ASCENT;
case TitledBorder.ABOVE_BOTTOM:
case TitledBorder.BOTTOM:
case TitledBorder.BELOW_BOTTOM:
return JComponent.BaselineResizeBehavior.CONSTANT_DESCENT;
}
return Component.BaselineResizeBehavior.OTHER;
}
protected Font getFont(Component c) {
Font font;
if ((font = getTitleFont()) != null) {
return font;
} else if (c != null && (font = c.getFont()) != null) {
return font;
}
return new Font(Font.DIALOG, Font.PLAIN, 12);
}
private static boolean computeIntersection(Rectangle dest,
int rx, int ry, int rw, int rh) {
int x1 = Math.max(rx, dest.x);
int x2 = Math.min(rx + rw, dest.x + dest.width);
int y1 = Math.max(ry, dest.y);
int y2 = Math.min(ry + rh, dest.y + dest.height);
dest.x = x1;
dest.y = y1;
dest.width = x2 - x1;
dest.height = y2 - y1;
if (dest.width <= 0 || dest.height <= 0) {
return false;
}
return true;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Component;
/** {@collect.stats}
* A composite Border class used to compose two Border objects
* into a single border by nesting an inside Border object within
* the insets of an outside Border object.
*
* For example, this class may be used to add blank margin space
* to a component with an existing decorative border:
* <p>
* <code><pre>
* Border border = comp.getBorder();
* Border margin = new EmptyBorder(10,10,10,10);
* comp.setBorder(new CompoundBorder(border, margin));
* </pre></code>
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author David Kloba
*/
public class CompoundBorder extends AbstractBorder {
protected Border outsideBorder;
protected Border insideBorder;
/** {@collect.stats}
* Creates a compound border with null outside and inside borders.
*/
public CompoundBorder() {
this.outsideBorder = null;
this.insideBorder = null;
}
/** {@collect.stats}
* Creates a compound border with the specified outside and
* inside borders. Either border may be null.
* @param outsideBorder the outside border
* @param insideBorder the inside border to be nested
*/
public CompoundBorder(Border outsideBorder, Border insideBorder) {
this.outsideBorder = outsideBorder;
this.insideBorder = insideBorder;
}
/** {@collect.stats}
* 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.
*/
public boolean isBorderOpaque() {
return (outsideBorder == null || outsideBorder.isBorderOpaque()) &&
(insideBorder == null || insideBorder.isBorderOpaque());
}
/** {@collect.stats}
* Paints the compound border by painting the outside border
* with the specified position and size and then painting the
* inside border at the specified position and size offset by
* the insets of the outside border.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Insets nextInsets;
int px, py, pw, ph;
px = x;
py = y;
pw = width;
ph = height;
if(outsideBorder != null) {
outsideBorder.paintBorder(c, g, px, py, pw, ph);
nextInsets = outsideBorder.getBorderInsets(c);
px += nextInsets.left;
py += nextInsets.top;
pw = pw - nextInsets.right - nextInsets.left;
ph = ph - nextInsets.bottom - nextInsets.top;
}
if(insideBorder != null)
insideBorder.paintBorder(c, g, px, py, pw, ph);
}
/** {@collect.stats}
* Reinitialize the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
*/
public Insets getBorderInsets(Component c, Insets insets) {
Insets nextInsets;
insets.top = insets.left = insets.right = insets.bottom = 0;
if(outsideBorder != null) {
nextInsets = outsideBorder.getBorderInsets(c);
insets.top += nextInsets.top;
insets.left += nextInsets.left;
insets.right += nextInsets.right;
insets.bottom += nextInsets.bottom;
}
if(insideBorder != null) {
nextInsets = insideBorder.getBorderInsets(c);
insets.top += nextInsets.top;
insets.left += nextInsets.left;
insets.right += nextInsets.right;
insets.bottom += nextInsets.bottom;
}
return insets;
}
/** {@collect.stats}
* Returns the insets of the composite border by adding
* the insets of the outside border to the insets of the
* inside border.
* @param c the component for which this border insets value applies
*/
public Insets getBorderInsets(Component c) {
return getBorderInsets(c, new Insets(0,0,0,0));
}
/** {@collect.stats}
* Returns the outside border object.
*/
public Border getOutsideBorder() {
return outsideBorder;
}
/** {@collect.stats}
* Returns the inside border object.
*/
public Border getInsideBorder() {
return insideBorder;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Component;
/** {@collect.stats}
* A class which implements a simple etched border which can
* either be etched-in or etched-out. If no highlight/shadow
* colors are initialized when the border is created, then
* these colors will be dynamically derived from the background
* color of the component argument passed into the paintBorder()
* method.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author David Kloba
* @author Amy Fowler
*/
public class EtchedBorder extends AbstractBorder
{
/** {@collect.stats} Raised etched type. */
public static final int RAISED = 0;
/** {@collect.stats} Lowered etched type. */
public static final int LOWERED = 1;
protected int etchType;
protected Color highlight;
protected Color shadow;
/** {@collect.stats}
* Creates a lowered etched border whose colors will be derived
* from the background color of the component passed into
* the paintBorder method.
*/
public EtchedBorder() {
this(LOWERED);
}
/** {@collect.stats}
* Creates an etched border with the specified etch-type
* whose colors will be derived
* from the background color of the component passed into
* the paintBorder method.
* @param etchType the type of etch to be drawn by the border
*/
public EtchedBorder(int etchType) {
this(etchType, null, null);
}
/** {@collect.stats}
* Creates a lowered etched border with the specified highlight and
* shadow colors.
* @param highlight the color to use for the etched highlight
* @param shadow the color to use for the etched shadow
*/
public EtchedBorder(Color highlight, Color shadow) {
this(LOWERED, highlight, shadow);
}
/** {@collect.stats}
* Creates an etched border with the specified etch-type,
* highlight and shadow colors.
* @param etchType the type of etch to be drawn by the border
* @param highlight the color to use for the etched highlight
* @param shadow the color to use for the etched shadow
*/
public EtchedBorder(int etchType, Color highlight, Color shadow) {
this.etchType = etchType;
this.highlight = highlight;
this.shadow = shadow;
}
/** {@collect.stats}
* Paints the border for the specified component with the
* specified position and size.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
int w = width;
int h = height;
g.translate(x, y);
g.setColor(etchType == LOWERED? getShadowColor(c) : getHighlightColor(c));
g.drawRect(0, 0, w-2, h-2);
g.setColor(etchType == LOWERED? getHighlightColor(c) : getShadowColor(c));
g.drawLine(1, h-3, 1, 1);
g.drawLine(1, 1, w-3, 1);
g.drawLine(0, h-1, w-1, h-1);
g.drawLine(w-1, h-1, w-1, 0);
g.translate(-x, -y);
}
/** {@collect.stats}
* Returns the insets of the border.
* @param c the component for which this border insets value applies
*/
public Insets getBorderInsets(Component c) {
return new Insets(2, 2, 2, 2);
}
/** {@collect.stats}
* Reinitialize the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
*/
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = insets.top = insets.right = insets.bottom = 2;
return insets;
}
/** {@collect.stats}
* Returns whether or not the border is opaque.
*/
public boolean isBorderOpaque() { return true; }
/** {@collect.stats}
* Returns which etch-type is set on the etched border.
*/
public int getEtchType() {
return etchType;
}
/** {@collect.stats}
* Returns the highlight color of the etched border
* when rendered on the specified component. If no highlight
* color was specified at instantiation, the highlight color
* is derived from the specified component's background color.
* @param c the component for which the highlight may be derived
* @since 1.3
*/
public Color getHighlightColor(Component c) {
return highlight != null? highlight :
c.getBackground().brighter();
}
/** {@collect.stats}
* Returns the highlight color of the etched border.
* Will return null if no highlight color was specified
* at instantiation.
* @since 1.3
*/
public Color getHighlightColor() {
return highlight;
}
/** {@collect.stats}
* Returns the shadow color of the etched border
* when rendered on the specified component. If no shadow
* color was specified at instantiation, the shadow color
* is derived from the specified component's background color.
* @param c the component for which the shadow may be derived
* @since 1.3
*/
public Color getShadowColor(Component c) {
return shadow != null? shadow : c.getBackground().darker();
}
/** {@collect.stats}
* Returns the shadow color of the etched border.
* Will return null if no shadow color was specified
* at instantiation.
* @since 1.3
*/
public Color getShadowColor() {
return shadow;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Component;
/** {@collect.stats}
* A class which implements a raised or lowered bevel with
* softened corners.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Amy Fowler
* @author Chester Rose
*/
public class SoftBevelBorder extends BevelBorder
{
/** {@collect.stats}
* Creates a bevel border with the specified type and whose
* colors will be derived from the background color of the
* component passed into the paintBorder method.
* @param bevelType the type of bevel for the border
*/
public SoftBevelBorder(int bevelType) {
super(bevelType);
}
/** {@collect.stats}
* Creates a bevel border with the specified type, highlight and
* shadow colors.
* @param bevelType the type of bevel for the border
* @param highlight the color to use for the bevel highlight
* @param shadow the color to use for the bevel shadow
*/
public SoftBevelBorder(int bevelType, Color highlight, Color shadow) {
super(bevelType, highlight, shadow);
}
/** {@collect.stats}
* Creates a bevel border with the specified type, highlight
* shadow colors.
* @param bevelType the type of bevel for the border
* @param highlightOuterColor the color to use for the bevel outer highlight
* @param highlightInnerColor the color to use for the bevel inner highlight
* @param shadowOuterColor the color to use for the bevel outer shadow
* @param shadowInnerColor the color to use for the bevel inner shadow
*/
public SoftBevelBorder(int bevelType, Color highlightOuterColor,
Color highlightInnerColor, Color shadowOuterColor,
Color shadowInnerColor) {
super(bevelType, highlightOuterColor, highlightInnerColor,
shadowOuterColor, shadowInnerColor);
}
/** {@collect.stats}
* Paints the border for the specified component with the specified
* position and size.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Color oldColor = g.getColor();
g.translate(x, y);
if (bevelType == RAISED) {
g.setColor(getHighlightOuterColor(c));
g.drawLine(0, 0, width-2, 0);
g.drawLine(0, 0, 0, height-2);
g.drawLine(1, 1, 1, 1);
g.setColor(getHighlightInnerColor(c));
g.drawLine(2, 1, width-2, 1);
g.drawLine(1, 2, 1, height-2);
g.drawLine(2, 2, 2, 2);
g.drawLine(0, height-1, 0, height-2);
g.drawLine(width-1, 0, width-1, 0);
g.setColor(getShadowOuterColor(c));
g.drawLine(2, height-1, width-1, height-1);
g.drawLine(width-1, 2, width-1, height-1);
g.setColor(getShadowInnerColor(c));
g.drawLine(width-2, height-2, width-2, height-2);
} else if (bevelType == LOWERED) {
g.setColor(getShadowOuterColor(c));
g.drawLine(0, 0, width-2, 0);
g.drawLine(0, 0, 0, height-2);
g.drawLine(1, 1, 1, 1);
g.setColor(getShadowInnerColor(c));
g.drawLine(2, 1, width-2, 1);
g.drawLine(1, 2, 1, height-2);
g.drawLine(2, 2, 2, 2);
g.drawLine(0, height-1, 0, height-2);
g.drawLine(width-1, 0, width-1, 0);
g.setColor(getHighlightOuterColor(c));
g.drawLine(2, height-1, width-1, height-1);
g.drawLine(width-1, 2, width-1, height-1);
g.setColor(getHighlightInnerColor(c));
g.drawLine(width-2, height-2, width-2, height-2);
}
g.translate(-x, -y);
g.setColor(oldColor);
}
/** {@collect.stats}
* Returns the insets of the border.
* @param c the component for which this border insets value applies
*/
public Insets getBorderInsets(Component c) {
return getBorderInsets(c, new Insets(0,0,0,0));
}
/** {@collect.stats}
* Reinitialize the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
*/
public Insets getBorderInsets(Component c, Insets insets) {
insets.top = insets.left = insets.bottom = insets.right = 3;
return insets;
}
/** {@collect.stats}
* Returns whether or not the border is opaque.
*/
public boolean isBorderOpaque() { return false; }
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Component;
import java.awt.Color;
import javax.swing.Icon;
/** {@collect.stats}
* A class which provides a matte-like border of either a solid color
* or a tiled icon.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Amy Fowler
*/
public class MatteBorder extends EmptyBorder
{
protected Color color;
protected Icon tileIcon;
/** {@collect.stats}
* Creates a matte border with the specified insets and color.
* @param top the top inset of the border
* @param left the left inset of the border
* @param bottom the bottom inset of the border
* @param right the right inset of the border
* @param matteColor the color rendered for the border
*/
public MatteBorder(int top, int left, int bottom, int right, Color matteColor) {
super(top, left, bottom, right);
this.color = matteColor;
}
/** {@collect.stats}
* Creates a matte border with the specified insets and color.
* @param borderInsets the insets of the border
* @param matteColor the color rendered for the border
* @since 1.3
*/
public MatteBorder(Insets borderInsets, Color matteColor) {
super(borderInsets);
this.color = matteColor;
}
/** {@collect.stats}
* Creates a matte border with the specified insets and tile icon.
* @param top the top inset of the border
* @param left the left inset of the border
* @param bottom the bottom inset of the border
* @param right the right inset of the border
* @param tileIcon the icon to be used for tiling the border
*/
public MatteBorder(int top, int left, int bottom, int right, Icon tileIcon) {
super(top, left, bottom, right);
this.tileIcon = tileIcon;
}
/** {@collect.stats}
* Creates a matte border with the specified insets and tile icon.
* @param borderInsets the insets of the border
* @param tileIcon the icon to be used for tiling the border
* @since 1.3
*/
public MatteBorder(Insets borderInsets, Icon tileIcon) {
super(borderInsets);
this.tileIcon = tileIcon;
}
/** {@collect.stats}
* Creates a matte border with the specified tile icon. The
* insets will be calculated dynamically based on the size of
* the tile icon, where the top and bottom will be equal to the
* tile icon's height, and the left and right will be equal to
* the tile icon's width.
* @param tileIcon the icon to be used for tiling the border
*/
public MatteBorder(Icon tileIcon) {
this(-1,-1,-1,-1, tileIcon);
}
/** {@collect.stats}
* Paints the matte border.
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Insets insets = getBorderInsets(c);
Color oldColor = g.getColor();
g.translate(x, y);
// If the tileIcon failed loading, paint as gray.
if (tileIcon != null) {
color = (tileIcon.getIconWidth() == -1) ? Color.gray : null;
}
if (color != null) {
g.setColor(color);
g.fillRect(0, 0, width - insets.right, insets.top);
g.fillRect(0, insets.top, insets.left, height - insets.top);
g.fillRect(insets.left, height - insets.bottom, width - insets.left, insets.bottom);
g.fillRect(width - insets.right, 0, insets.right, height - insets.bottom);
} else if (tileIcon != null) {
int tileW = tileIcon.getIconWidth();
int tileH = tileIcon.getIconHeight();
int xpos, ypos, startx, starty;
Graphics cg;
// Paint top matte edge
cg = g.create();
cg.setClip(0, 0, width, insets.top);
for (ypos = 0; insets.top - ypos > 0; ypos += tileH) {
for (xpos = 0; width - xpos > 0; xpos += tileW) {
tileIcon.paintIcon(c, cg, xpos, ypos);
}
}
cg.dispose();
// Paint left matte edge
cg = g.create();
cg.setClip(0, insets.top, insets.left, height - insets.top);
starty = insets.top - (insets.top%tileH);
startx = 0;
for (ypos = starty; height - ypos > 0; ypos += tileH) {
for (xpos = startx; insets.left - xpos > 0; xpos += tileW) {
tileIcon.paintIcon(c, cg, xpos, ypos);
}
}
cg.dispose();
// Paint bottom matte edge
cg = g.create();
cg.setClip(insets.left, height - insets.bottom, width - insets.left, insets.bottom);
starty = (height - insets.bottom) - ((height - insets.bottom)%tileH);
startx = insets.left - (insets.left%tileW);
for (ypos = starty; height - ypos > 0; ypos += tileH) {
for (xpos = startx; width - xpos > 0; xpos += tileW) {
tileIcon.paintIcon(c, cg, xpos, ypos);
}
}
cg.dispose();
// Paint right matte edge
cg = g.create();
cg.setClip(width - insets.right, insets.top, insets.right, height - insets.top - insets.bottom);
starty = insets.top - (insets.top%tileH);
startx = width - insets.right - ((width - insets.right)%tileW);
for (ypos = starty; height - ypos > 0; ypos += tileH) {
for (xpos = startx; width - xpos > 0; xpos += tileW) {
tileIcon.paintIcon(c, cg, xpos, ypos);
}
}
cg.dispose();
}
g.translate(-x, -y);
g.setColor(oldColor);
}
/** {@collect.stats}
* Returns the insets of the border.
* @param c the component for which this border insets value applies
* @since 1.3
*/
public Insets getBorderInsets(Component c) {
return getBorderInsets();
}
/** {@collect.stats}
* Reinitialize the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
* @since 1.3
*/
public Insets getBorderInsets(Component c, Insets insets) {
return computeInsets(insets);
}
/** {@collect.stats}
* Returns the insets of the border.
* @since 1.3
*/
public Insets getBorderInsets() {
return computeInsets(new Insets(0,0,0,0));
}
/* should be protected once api changes area allowed */
private Insets computeInsets(Insets insets) {
if (tileIcon != null && top == -1 && bottom == -1 &&
left == -1 && right == -1) {
int w = tileIcon.getIconWidth();
int h = tileIcon.getIconHeight();
insets.top = h;
insets.right = w;
insets.bottom = h;
insets.left = w;
} else {
insets.left = left;
insets.top = top;
insets.right = right;
insets.bottom = bottom;
}
return insets;
}
/** {@collect.stats}
* Returns the color used for tiling the border or null
* if a tile icon is being used.
* @since 1.3
*/
public Color getMatteColor() {
return color;
}
/** {@collect.stats}
* Returns the icon used for tiling the border or null
* if a solid color is being used.
* @since 1.3
*/
public Icon getTileIcon() {
return tileIcon;
}
/** {@collect.stats}
* Returns whether or not the border is opaque.
*/
public boolean isBorderOpaque() {
// If a tileIcon is set, then it may contain transparent bits
return color != null;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.border;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Component;
import java.io.Serializable;
/** {@collect.stats}
* A class which provides an empty, transparent border which
* takes up space but does no drawing.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author David Kloba
*/
public class EmptyBorder extends AbstractBorder implements Serializable
{
protected int left, right, top, bottom;
/** {@collect.stats}
* Creates an empty border with the specified insets.
* @param top the top inset of the border
* @param left the left inset of the border
* @param bottom the bottom inset of the border
* @param right the right inset of the border
*/
public EmptyBorder(int top, int left, int bottom, int right) {
this.top = top;
this.right = right;
this.bottom = bottom;
this.left = left;
}
/** {@collect.stats}
* Creates an empty border with the specified insets.
* @param borderInsets the insets of the border
*/
public EmptyBorder(Insets borderInsets) {
this.top = borderInsets.top;
this.right = borderInsets.right;
this.bottom = borderInsets.bottom;
this.left = borderInsets.left;
}
/** {@collect.stats}
* Does no drawing by default.
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
}
/** {@collect.stats}
* Returns the insets of the border.
* @param c the component for which this border insets value applies
* @since 1.3
*/
public Insets getBorderInsets(Component c) {
return getBorderInsets();
}
/** {@collect.stats}
* Reinitialize the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
*/
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = left;
insets.top = top;
insets.right = right;
insets.bottom = bottom;
return insets;
}
/** {@collect.stats}
* Returns the insets of the border.
* @since 1.3
*/
public Insets getBorderInsets() {
return new Insets(top, left, bottom, right);
}
/** {@collect.stats}
* Returns whether or not the border is opaque.
* Returns false by default.
*/
public boolean isBorderOpaque() { return false; }
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
/** {@collect.stats}
* A listener implementing all the methods in both the {@code MouseListener} and
* {@code MouseMotionListener} interfaces.
*
* @see MouseInputAdapter
* @author Philip Milne
*/
public interface MouseInputListener extends MouseListener, MouseMotionListener {
}
|
Java
|
/*
* Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* Defines a listener for menu events.
*
* @author Georges Saab
*/
public interface MenuListener extends EventListener {
/** {@collect.stats}
* Invoked when a menu is selected.
*
* @param e a MenuEvent object
*/
void menuSelected(MenuEvent e);
/** {@collect.stats}
* Invoked when the menu is deselected.
*
* @param e a MenuEvent object
*/
void menuDeselected(MenuEvent e);
/** {@collect.stats}
* Invoked when the menu is canceled.
*
* @param e a MenuEvent object
*/
void menuCanceled(MenuEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
import java.net.URL;
import javax.swing.text.Element;
/** {@collect.stats}
* HyperlinkEvent is used to notify interested parties that
* something has happened with respect to a hypertext link.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Timothy Prinzing
*/
public class HyperlinkEvent extends EventObject {
/** {@collect.stats}
* Creates a new object representing a hypertext link event.
* The other constructor is preferred, as it provides more
* information if a URL could not be formed. This constructor
* is primarily for backward compatibility.
*
* @param source the object responsible for the event
* @param type the event type
* @param u the affected URL
*/
public HyperlinkEvent(Object source, EventType type, URL u) {
this(source, type, u, null);
}
/** {@collect.stats}
* Creates a new object representing a hypertext link event.
*
* @param source the object responsible for the event
* @param type the event type
* @param u the affected URL. This may be null if a valid URL
* could not be created.
* @param desc the description of the link. This may be useful
* when attempting to form a URL resulted in a MalformedURLException.
* The description provides the text used when attempting to form the
* URL.
*/
public HyperlinkEvent(Object source, EventType type, URL u, String desc) {
this(source, type, u, desc, null);
}
/** {@collect.stats}
* Creates a new object representing a hypertext link event.
*
* @param source the object responsible for the event
* @param type the event type
* @param u the affected URL. This may be null if a valid URL
* could not be created.
* @param desc the description of the link. This may be useful
* when attempting to form a URL resulted in a MalformedURLException.
* The description provides the text used when attempting to form the
* URL.
* @param sourceElement Element in the Document representing the
* anchor
* @since 1.4
*/
public HyperlinkEvent(Object source, EventType type, URL u, String desc,
Element sourceElement) {
super(source);
this.type = type;
this.u = u;
this.desc = desc;
this.sourceElement = sourceElement;
}
/** {@collect.stats}
* Gets the type of event.
*
* @return the type
*/
public EventType getEventType() {
return type;
}
/** {@collect.stats}
* Get the description of the link as a string.
* This may be useful if a URL can't be formed
* from the description, in which case the associated
* URL would be null.
*/
public String getDescription() {
return desc;
}
/** {@collect.stats}
* Gets the URL that the link refers to.
*
* @return the URL
*/
public URL getURL() {
return u;
}
/** {@collect.stats}
* Returns the <code>Element</code> that corresponds to the source of the
* event. This will typically be an <code>Element</code> representing
* an anchor. If a constructur that is used that does not specify a source
* <code>Element</code>, or null was specified as the source
* <code>Element</code>, this will return null.
*
* @return Element indicating source of event, or null
* @since 1.4
*/
public Element getSourceElement() {
return sourceElement;
}
private EventType type;
private URL u;
private String desc;
private Element sourceElement;
/** {@collect.stats}
* Defines the ENTERED, EXITED, and ACTIVATED event types, along
* with their string representations, returned by toString().
*/
public static final class EventType {
private EventType(String s) {
typeString = s;
}
/** {@collect.stats}
* Entered type.
*/
public static final EventType ENTERED = new EventType("ENTERED");
/** {@collect.stats}
* Exited type.
*/
public static final EventType EXITED = new EventType("EXITED");
/** {@collect.stats}
* Activated type.
*/
public static final EventType ACTIVATED = new EventType("ACTIVATED");
/** {@collect.stats}
* Converts the type to a string.
*
* @return the string
*/
public String toString() {
return typeString;
}
private String typeString;
}
}
|
Java
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* MenuKeyListener
*
* @author Georges Saab
*/
public interface MenuKeyListener extends EventListener {
/** {@collect.stats}
* Invoked when a key has been typed.
* This event occurs when a key press is followed by a key release.
*/
void menuKeyTyped(MenuKeyEvent e);
/** {@collect.stats}
* Invoked when a key has been pressed.
*/
void menuKeyPressed(MenuKeyEvent e);
/** {@collect.stats}
* Invoked when a key has been released.
*/
void menuKeyReleased(MenuKeyEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import javax.swing.event.ChangeEvent;
import java.util.EventListener;
/** {@collect.stats}
* CellEditorListener defines the interface for an object that listens
* to changes in a CellEditor
*
* @author Alan Chung
*/
public interface CellEditorListener extends java.util.EventListener {
/** {@collect.stats} This tells the listeners the editor has ended editing */
public void editingStopped(ChangeEvent e);
/** {@collect.stats} This tells the listeners the editor has canceled editing */
public void editingCanceled(ChangeEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import javax.swing.undo.*;
/** {@collect.stats}
* Interface implemented by a class interested in hearing about
* undoable operations.
*
* @author Ray Ryan
*/
public interface UndoableEditListener extends java.util.EventListener {
/** {@collect.stats}
* An undoable edit happened
*/
void undoableEditHappened(UndoableEditEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener that's notified when the selection in a TreeSelectionModel
* changes.
* For more information and examples see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/events/treeselectionlistener.html">How to Write a Tree Selection Listener</a>,
* a section in <em>The Java Tutorial.</em>
*
* @see javax.swing.tree.TreeSelectionModel
* @see javax.swing.JTree
*
* @author Scott Violet
*/
public interface TreeSelectionListener extends EventListener
{
/** {@collect.stats}
* Called whenever the value of the selection changes.
* @param e the event that characterizes the change.
*/
void valueChanged(TreeSelectionEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener that's notified when a tree expands or collapses
* a node.
* For further documentation and examples see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/events/treeexpansionlistener.html">How to Write a Tree Expansion Listener</a>,
* a section in <em>The Java Tutorial.</em>
*
* @author Scott Violet
*/
public interface TreeExpansionListener extends EventListener
{
/** {@collect.stats}
* Called whenever an item in the tree has been expanded.
*/
public void treeExpanded(TreeExpansionEvent event);
/** {@collect.stats}
* Called whenever an item in the tree has been collapsed.
*/
public void treeCollapsed(TreeExpansionEvent event);
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
/** {@collect.stats}
* ChangeEvent is used to notify interested parties that
* state has changed in the event source.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Jeff Dinkins
*/
public class ChangeEvent extends EventObject {
/** {@collect.stats}
* Constructs a ChangeEvent object.
*
* @param source the Object that is the source of the event
* (typically <code>this</code>)
*/
public ChangeEvent(Object source) {
super(source);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import javax.swing.undo.*;
import javax.swing.text.*;
/** {@collect.stats}
* Interface for document change notifications. This provides
* detailed information to Document observers about how the
* Document changed. It provides high level information such
* as type of change and where it occurred, as well as the more
* detailed structural changes (What Elements were inserted and
* removed).
*
* @author Timothy Prinzing
* @see javax.swing.text.Document
* @see DocumentListener
*/
public interface DocumentEvent {
/** {@collect.stats}
* Returns the offset within the document of the start
* of the change.
*
* @return the offset >= 0
*/
public int getOffset();
/** {@collect.stats}
* Returns the length of the change.
*
* @return the length >= 0
*/
public int getLength();
/** {@collect.stats}
* Gets the document that sourced the change event.
*
* @return the document
*/
public Document getDocument();
/** {@collect.stats}
* Gets the type of event.
*
* @return the type
*/
public EventType getType();
/** {@collect.stats}
* Gets the change information for the given element.
* The change information describes what elements were
* added and removed and the location. If there were
* no changes, null is returned.
* <p>
* This method is for observers to discover the structural
* changes that were made. This means that only elements
* that existed prior to the mutation (and still exist after
* the mutatino) need to have ElementChange records.
* The changes made available need not be recursive.
* <p>
* For example, if the an element is removed from it's
* parent, this method should report that the parent
* changed and provide an ElementChange implementation
* that describes the change to the parent. If the
* child element removed had children, these elements
* do not need to be reported as removed.
* <p>
* If an child element is insert into a parent element,
* the parent element should report a change. If the
* child element also had elements inserted into it
* (grandchildren to the parent) these elements need
* not report change.
*
* @param elem the element
* @return the change information, or null if the
* element was not modified
*/
public ElementChange getChange(Element elem);
/** {@collect.stats}
* Enumeration for document event types
*/
public static final class EventType {
private EventType(String s) {
typeString = s;
}
/** {@collect.stats}
* Insert type.
*/
public static final EventType INSERT = new EventType("INSERT");
/** {@collect.stats}
* Remove type.
*/
public static final EventType REMOVE = new EventType("REMOVE");
/** {@collect.stats}
* Change type.
*/
public static final EventType CHANGE = new EventType("CHANGE");
/** {@collect.stats}
* Converts the type to a string.
*
* @return the string
*/
public String toString() {
return typeString;
}
private String typeString;
}
/** {@collect.stats}
* Describes changes made to a specific element.
*/
public interface ElementChange {
/** {@collect.stats}
* Returns the element represented. This is the element
* that was changed.
*
* @return the element
*/
public Element getElement();
/** {@collect.stats}
* Fetches the index within the element represented.
* This is the location that children were added
* and/or removed.
*
* @return the index >= 0
*/
public int getIndex();
/** {@collect.stats}
* Gets the child elements that were removed from the
* given parent element. The element array returned is
* sorted in the order that the elements used to lie in
* the document, and must be contiguous.
*
* @return the child elements
*/
public Element[] getChildrenRemoved();
/** {@collect.stats}
* Gets the child elements that were added to the given
* parent element. The element array returned is in the
* order that the elements lie in the document, and must
* be contiguous.
*
* @return the child elements
*/
public Element[] getChildrenAdded();
}
}
|
Java
|
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
/** {@collect.stats}
* <code>RowSorterListener</code>s are notified of changes to a
* <code>RowSorter</code>.
*
* @see javax.swing.RowSorter
* @since 1.6
*/
public interface RowSorterListener extends java.util.EventListener {
/** {@collect.stats}
* Notification that the <code>RowSorter</code> has changed. The event
* describes the scope of the change.
*
* @param e the event, will not be null
*/
public void sorterChanged(RowSorterEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* Defines an object which listens for ChangeEvents.
*
* @author Jeff Dinkins
*/
public interface ChangeListener extends EventListener {
/** {@collect.stats}
* Invoked when the target of the listener has changed its state.
*
* @param e a ChangeEvent object
*/
void stateChanged(ChangeEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener that's notified when a lists selection value
* changes.
*
* @see javax.swing.ListSelectionModel
*
* @author Hans Muller
*/
public interface ListSelectionListener extends EventListener
{
/** {@collect.stats}
* Called whenever the value of the selection changes.
* @param e the event that characterizes the change.
*/
void valueChanged(ListSelectionEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* Defines the interface for an object that listens
* to changes in a TreeModel.
* For further information and examples see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/events/treemodellistener.html">How to Write a Tree Model Listener</a>,
* a section in <em>The Java Tutorial.</em>
*
* @author Rob Davis
* @author Ray Ryan
*/
public interface TreeModelListener extends EventListener {
/** {@collect.stats}
* <p>Invoked after a node (or a set of siblings) has changed in some
* way. The node(s) have not changed locations in the tree or
* altered their children arrays, but other attributes have
* changed and may affect presentation. Example: the name of a
* file has changed, but it is in the same location in the file
* system.</p>
* <p>To indicate the root has changed, childIndices and children
* will be null. </p>
*
* <p>Use <code>e.getPath()</code>
* to get the parent of the changed node(s).
* <code>e.getChildIndices()</code>
* returns the index(es) of the changed node(s).</p>
*/
void treeNodesChanged(TreeModelEvent e);
/** {@collect.stats}
* <p>Invoked after nodes have been inserted into the tree.</p>
*
* <p>Use <code>e.getPath()</code>
* to get the parent of the new node(s).
* <code>e.getChildIndices()</code>
* returns the index(es) of the new node(s)
* in ascending order.</p>
*/
void treeNodesInserted(TreeModelEvent e);
/** {@collect.stats}
* <p>Invoked after nodes have been removed from the tree. Note that
* if a subtree is removed from the tree, this method may only be
* invoked once for the root of the removed subtree, not once for
* each individual set of siblings removed.</p>
*
* <p>Use <code>e.getPath()</code>
* to get the former parent of the deleted node(s).
* <code>e.getChildIndices()</code>
* returns, in ascending order, the index(es)
* the node(s) had before being deleted.</p>
*/
void treeNodesRemoved(TreeModelEvent e);
/** {@collect.stats}
* <p>Invoked after the tree has drastically changed structure from a
* given node down. If the path returned by e.getPath() is of length
* one and the first element does not identify the current root node
* the first element should become the new root of the tree.<p>
*
* <p>Use <code>e.getPath()</code>
* to get the path to the node.
* <code>e.getChildIndices()</code>
* returns null.</p>
*/
void treeStructureChanged(TreeModelEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
import javax.swing.tree.TreePath;
/** {@collect.stats}
* An event that characterizes a change in the current
* selection. The change is based on any number of paths.
* TreeSelectionListeners will generally query the source of
* the event for the new selected status of each potentially
* changed row.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see TreeSelectionListener
* @see javax.swing.tree.TreeSelectionModel
*
* @author Scott Violet
*/
public class TreeSelectionEvent extends EventObject
{
/** {@collect.stats} Paths this event represents. */
protected TreePath[] paths;
/** {@collect.stats} For each path identifies if that path is in fact new. */
protected boolean[] areNew;
/** {@collect.stats} leadSelectionPath before the paths changed, may be null. */
protected TreePath oldLeadSelectionPath;
/** {@collect.stats} leadSelectionPath after the paths changed, may be null. */
protected TreePath newLeadSelectionPath;
/** {@collect.stats}
* Represents a change in the selection of a TreeSelectionModel.
* paths identifies the paths that have been either added or
* removed from the selection.
*
* @param source source of event
* @param paths the paths that have changed in the selection
*/
public TreeSelectionEvent(Object source, TreePath[] paths,
boolean[] areNew, TreePath oldLeadSelectionPath,
TreePath newLeadSelectionPath)
{
super(source);
this.paths = paths;
this.areNew = areNew;
this.oldLeadSelectionPath = oldLeadSelectionPath;
this.newLeadSelectionPath = newLeadSelectionPath;
}
/** {@collect.stats}
* Represents a change in the selection of a TreeSelectionModel.
* path identifies the path that have been either added or
* removed from the selection.
*
* @param source source of event
* @param path the path that has changed in the selection
* @param isNew whether or not the path is new to the selection, false
* means path was removed from the selection.
*/
public TreeSelectionEvent(Object source, TreePath path, boolean isNew,
TreePath oldLeadSelectionPath,
TreePath newLeadSelectionPath)
{
super(source);
paths = new TreePath[1];
paths[0] = path;
areNew = new boolean[1];
areNew[0] = isNew;
this.oldLeadSelectionPath = oldLeadSelectionPath;
this.newLeadSelectionPath = newLeadSelectionPath;
}
/** {@collect.stats}
* Returns the paths that have been added or removed from the
* selection.
*/
public TreePath[] getPaths()
{
int numPaths;
TreePath[] retPaths;
numPaths = paths.length;
retPaths = new TreePath[numPaths];
System.arraycopy(paths, 0, retPaths, 0, numPaths);
return retPaths;
}
/** {@collect.stats}
* Returns the first path element.
*/
public TreePath getPath()
{
return paths[0];
}
/** {@collect.stats}
* Returns true if the first path element has been added to the
* selection, a return value of false means the first path has been
* removed from the selection.
*/
public boolean isAddedPath() {
return areNew[0];
}
/** {@collect.stats}
* Returns true if the path identified by path was added to the
* selection. A return value of false means the path was in the
* selection but is no longer in the selection. This will raise if
* path is not one of the paths identified by this event.
*/
public boolean isAddedPath(TreePath path) {
for(int counter = paths.length - 1; counter >= 0; counter--)
if(paths[counter].equals(path))
return areNew[counter];
throw new IllegalArgumentException("path is not a path identified by the TreeSelectionEvent");
}
/** {@collect.stats}
* Returns true if the path identified by <code>index</code> was added to
* the selection. A return value of false means the path was in the
* selection but is no longer in the selection. This will raise if
* index < 0 || >= <code>getPaths</code>.length.
*
* @since 1.3
*/
public boolean isAddedPath(int index) {
if (paths == null || index < 0 || index >= paths.length) {
throw new IllegalArgumentException("index is beyond range of added paths identified by TreeSelectionEvent");
}
return areNew[index];
}
/** {@collect.stats}
* Returns the path that was previously the lead path.
*/
public TreePath getOldLeadSelectionPath() {
return oldLeadSelectionPath;
}
/** {@collect.stats}
* Returns the current lead path.
*/
public TreePath getNewLeadSelectionPath() {
return newLeadSelectionPath;
}
/** {@collect.stats}
* Returns a copy of the receiver, but with the source being newSource.
*/
public Object cloneWithSource(Object newSource) {
// Fix for IE bug - crashing
return new TreeSelectionEvent(newSource, paths,areNew,
oldLeadSelectionPath,
newLeadSelectionPath);
}
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import javax.swing.MenuElement;
import javax.swing.MenuSelectionManager;
import java.util.EventObject;
import java.awt.event.KeyEvent;
import java.awt.Component;
/** {@collect.stats}
* MenuKeyEvent is used to notify interested parties that
* the menu element has received a KeyEvent forwarded to it
* in a menu tree.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Georges Saab
*/
public class MenuKeyEvent extends KeyEvent {
private MenuElement path[];
private MenuSelectionManager manager;
/** {@collect.stats}
* Constructs a MenuKeyEvent object.
*
* @param source the Component that originated the event
* (typically <code>this</code>)
* @param id an int specifying the type of event, as defined
* in {@link java.awt.event.KeyEvent}
* @param when a long identifying the time the event occurred
* @param modifiers an int specifying any modifier keys held down,
* as specified in {@link java.awt.event.InputEvent}
* @param keyCode an int specifying the specific key that was pressed
* @param keyChar a char specifying the key's character value, if any
* -- null if the key has no character value
* @param p an array of MenuElement objects specifying a path
* to a menu item affected by the drag
* @param m a MenuSelectionManager object that handles selections
*/
public MenuKeyEvent(Component source, int id, long when, int modifiers,
int keyCode, char keyChar,
MenuElement p[], MenuSelectionManager m) {
super(source, id, when, modifiers, keyCode, keyChar);
path = p;
manager = m;
}
/** {@collect.stats}
* Returns the path to the menu item referenced by this event.
*
* @return an array of MenuElement objects representing the path value
*/
public MenuElement[] getPath() {
return path;
}
/** {@collect.stats}
* Returns the current menu selection manager.
*
* @return a MenuSelectionManager object
*/
public MenuSelectionManager getMenuSelectionManager() {
return manager;
}
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ChangeEvent;
import java.util.EventListener;
/** {@collect.stats}
* TableColumnModelListener defines the interface for an object that listens
* to changes in a TableColumnModel.
*
* @author Alan Chung
* @see TableColumnModelEvent
*/
public interface TableColumnModelListener extends java.util.EventListener
{
/** {@collect.stats} Tells listeners that a column was added to the model. */
public void columnAdded(TableColumnModelEvent e);
/** {@collect.stats} Tells listeners that a column was removed from the model. */
public void columnRemoved(TableColumnModelEvent e);
/** {@collect.stats} Tells listeners that a column was repositioned. */
public void columnMoved(TableColumnModelEvent e);
/** {@collect.stats} Tells listeners that a column was moved due to a margin change. */
public void columnMarginChanged(ChangeEvent e);
/** {@collect.stats}
* Tells listeners that the selection model of the
* TableColumnModel changed.
*/
public void columnSelectionChanged(ListSelectionEvent e);
}
|
Java
|
/*
* Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving internal frame events.
* This class is functionally equivalent to the WindowListener class
* in the AWT.
* <p>
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/internalframelistener.html">How to Write an Internal Frame Listener</a>
* in <em>The Java Tutorial</em> and
* <a href="http://www.awl.com/cp/javaseries/jcl1_2.html">The Java Class Libraries (update)</a>
* for further documentation.
*
* @see java.awt.event.WindowListener
*
* @author Thomas Ball
*/
public interface InternalFrameListener extends EventListener {
/** {@collect.stats}
* Invoked when a internal frame has been opened.
* @see javax.swing.JInternalFrame#show
*/
public void internalFrameOpened(InternalFrameEvent e);
/** {@collect.stats}
* Invoked when an internal frame is in the process of being closed.
* The close operation can be overridden at this point.
* @see javax.swing.JInternalFrame#setDefaultCloseOperation
*/
public void internalFrameClosing(InternalFrameEvent e);
/** {@collect.stats}
* Invoked when an internal frame has been closed.
* @see javax.swing.JInternalFrame#setClosed
*/
public void internalFrameClosed(InternalFrameEvent e);
/** {@collect.stats}
* Invoked when an internal frame is iconified.
* @see javax.swing.JInternalFrame#setIcon
*/
public void internalFrameIconified(InternalFrameEvent e);
/** {@collect.stats}
* Invoked when an internal frame is de-iconified.
* @see javax.swing.JInternalFrame#setIcon
*/
public void internalFrameDeiconified(InternalFrameEvent e);
/** {@collect.stats}
* Invoked when an internal frame is activated.
* @see javax.swing.JInternalFrame#setSelected
*/
public void internalFrameActivated(InternalFrameEvent e);
/** {@collect.stats}
* Invoked when an internal frame is de-activated.
* @see javax.swing.JInternalFrame#setSelected
*/
public void internalFrameDeactivated(InternalFrameEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* Interface for an observer to register to receive notifications
* of changes to a text document.
* <p>
* The default implementation of
* the Document interface (AbstractDocument) supports asynchronous
* mutations. If this feature is used (i.e. mutations are made
* from a thread other than the Swing event thread), the listeners
* will be notified via the mutating thread. <em>This means that
* if asynchronous updates are made, the implementation of this
* interface must be threadsafe</em>!
* <p>
* The DocumentEvent notification is based upon the JavaBeans
* event model. There is no guarantee about the order of delivery
* to listeners, and all listeners must be notified prior to making
* further mutations to the Document. <em>This means implementations
* of the DocumentListener may not mutate the source of the event
* (i.e. the associated Document)</em>.
*
* @author Timothy Prinzing
* @see javax.swing.text.Document
* @see javax.swing.text.StyledDocument
* @see DocumentEvent
*/
public interface DocumentListener extends EventListener {
/** {@collect.stats}
* Gives notification that there was an insert into the document. The
* range given by the DocumentEvent bounds the freshly inserted region.
*
* @param e the document event
*/
public void insertUpdate(DocumentEvent e);
/** {@collect.stats}
* Gives notification that a portion of the document has been
* removed. The range is given in terms of what the view last
* saw (that is, before updating sticky positions).
*
* @param e the document event
*/
public void removeUpdate(DocumentEvent e);
/** {@collect.stats}
* Gives notification that an attribute or set of attributes changed.
*
* @param e the document event
*/
public void changedUpdate(DocumentEvent e);
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.awt.event.MouseAdapter;
/** {@collect.stats}
* An empty implementation of the {@code MouseInputListener} interface, provided
* as a convenience to simplify the task of creating listeners, by extending
* and implementing only the methods of interest. This class also provides an
* empty implementation of the {@code MouseWheelListener} interface, through
* its extension from AWT's {@code MouseAdapter}.
*
* @author Philip Milne
* @author Shannon Hickey
*/
public abstract class MouseInputAdapter extends MouseAdapter
implements MouseInputListener {
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
/** {@collect.stats}
* MenuEvent is used to notify interested parties that
* the menu which is the event source has been posted,
* selected, or canceled.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Georges Saab
* @author David Karlton
*/
public class MenuEvent extends EventObject {
/** {@collect.stats}
* Constructs a MenuEvent object.
*
* @param source the Object that originated the event
* (typically <code>this</code>)
*/
public MenuEvent(Object source) {
super(source);
}
}
|
Java
|
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import javax.swing.RowSorter;
/** {@collect.stats}
* <code>RowSorterEvent</code> provides notification of changes to
* a <code>RowSorter</code>. Two types of notification are possible:
* <ul>
* <li><code>Type.SORT_ORDER_CHANGED</code>: indicates the sort order has
* changed. This is typically followed by a notification of:
* <li><code>Type.SORTED</code>: indicates the contents of the model have
* been transformed in some way. For example, the contents may have
* been sorted or filtered.
* </ul>
*
* @see javax.swing.RowSorter
* @since 1.6
*/
public class RowSorterEvent extends java.util.EventObject {
private Type type;
private int[] oldViewToModel;
/** {@collect.stats}
* Enumeration of the types of <code>RowSorterEvent</code>s.
*
* @since 1.6
*/
public enum Type {
/** {@collect.stats}
* Indicates the sort order has changed.
*/
SORT_ORDER_CHANGED,
/** {@collect.stats}
* Indicates the contents have been newly sorted or
* transformed in some way.
*/
SORTED
}
/** {@collect.stats}
* Creates a <code>RowSorterEvent</code> of type
* <code>SORT_ORDER_CHANGED</code>.
*
* @param source the source of the change
* @throws IllegalArgumentException if <code>source</code> is
* <code>null</code>
*/
public RowSorterEvent(RowSorter source) {
this(source, Type.SORT_ORDER_CHANGED, null);
}
/** {@collect.stats}
* Creates a <code>RowSorterEvent</code>.
*
* @param source the source of the change
* @param type the type of event
* @param previousRowIndexToModel the mapping from model indices to
* view indices prior to the sort, may be <code>null</code>
* @throws IllegalArgumentException if source or <code>type</code> is
* <code>null</code>
*/
public RowSorterEvent(RowSorter source, Type type,
int[] previousRowIndexToModel) {
super(source);
if (type == null) {
throw new IllegalArgumentException("type must be non-null");
}
this.type = type;
this.oldViewToModel = previousRowIndexToModel;
}
/** {@collect.stats}
* Returns the source of the event as a <code>RowSorter</code>.
*
* @return the source of the event as a <code>RowSorter</code>
*/
public RowSorter getSource() {
return (RowSorter)super.getSource();
}
/** {@collect.stats}
* Returns the type of event.
*
* @return the type of event
*/
public Type getType() {
return type;
}
/** {@collect.stats}
* Returns the location of <code>index</code> in terms of the
* model prior to the sort. This method is only useful for events
* of type <code>SORTED</code>. This method will return -1 if the
* index is not valid, or the locations prior to the sort have not
* been provided.
*
* @param index the index in terms of the view
* @return the index in terms of the model prior to the sort, or -1 if
* the location is not valid or the mapping was not provided.
*/
public int convertPreviousRowIndexToModel(int index) {
if (oldViewToModel != null && index >= 0 &&
index < oldViewToModel.length) {
return oldViewToModel[index];
}
return -1;
}
/** {@collect.stats}
* Returns the number of rows before the sort. This method is only
* useful for events of type <code>SORTED</code> and if the
* last locations have not been provided will return 0.
*
* @return the number of rows in terms of the view prior to the sort
*/
public int getPreviousRowCount() {
return (oldViewToModel == null) ? 0 : oldViewToModel.length;
}
}
|
Java
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* Defines a menu mouse-drag listener.
*
* @author Georges Saab
*/
public interface MenuDragMouseListener extends EventListener {
/** {@collect.stats}
* Invoked when the dragged mouse has entered a menu component's
* display area.
*
* @param e a MenuDragMouseEvent object
*/
void menuDragMouseEntered(MenuDragMouseEvent e);
/** {@collect.stats}
* Invoked when the dragged mouse has left a menu component's
* display area.
*
* @param e a MenuDragMouseEvent object
*/
void menuDragMouseExited(MenuDragMouseEvent e);
/** {@collect.stats}
* Invoked when the mouse is being dragged in a menu component's
* display area.
*
* @param e a MenuDragMouseEvent object
*/
void menuDragMouseDragged(MenuDragMouseEvent e);
/** {@collect.stats}
* Invoked when a dragged mouse is release in a menu component's
* display area.
*
* @param e a MenuDragMouseEvent object
*/
void menuDragMouseReleased(MenuDragMouseEvent e);
}
|
Java
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* Listener for changes in the caret position of a text
* component.
*
* @author Timothy Prinzing
*/
public interface CaretListener extends EventListener {
/** {@collect.stats}
* Called when the caret position is updated.
*
* @param e the caret event
*/
void caretUpdate(CaretEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
import javax.swing.table.*;
/** {@collect.stats}
* TableModelEvent is used to notify listeners that a table model
* has changed. The model event describes changes to a TableModel
* and all references to rows and columns are in the co-ordinate
* system of the model.
* Depending on the parameters used in the constructors, the TableModelevent
* can be used to specify the following types of changes: <p>
*
* <pre>
* TableModelEvent(source); // The data, ie. all rows changed
* TableModelEvent(source, HEADER_ROW); // Structure change, reallocate TableColumns
* TableModelEvent(source, 1); // Row 1 changed
* TableModelEvent(source, 3, 6); // Rows 3 to 6 inclusive changed
* TableModelEvent(source, 2, 2, 6); // Cell at (2, 6) changed
* TableModelEvent(source, 3, 6, ALL_COLUMNS, INSERT); // Rows (3, 6) were inserted
* TableModelEvent(source, 3, 6, ALL_COLUMNS, DELETE); // Rows (3, 6) were deleted
* </pre>
*
* It is possible to use other combinations of the parameters, not all of them
* are meaningful. By subclassing, you can add other information, for example:
* whether the event WILL happen or DID happen. This makes the specification
* of rows in DELETE events more useful but has not been included in
* the swing package as the JTable only needs post-event notification.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Alan Chung
* @author Philip Milne
* @see TableModel
*/
public class TableModelEvent extends java.util.EventObject
{
/** {@collect.stats} Identifies the addtion of new rows or columns. */
public static final int INSERT = 1;
/** {@collect.stats} Identifies a change to existing data. */
public static final int UPDATE = 0;
/** {@collect.stats} Identifies the removal of rows or columns. */
public static final int DELETE = -1;
/** {@collect.stats} Identifies the header row. */
public static final int HEADER_ROW = -1;
/** {@collect.stats} Specifies all columns in a row or rows. */
public static final int ALL_COLUMNS = -1;
//
// Instance Variables
//
protected int type;
protected int firstRow;
protected int lastRow;
protected int column;
//
// Constructors
//
/** {@collect.stats}
* All row data in the table has changed, listeners should discard any state
* that was based on the rows and requery the <code>TableModel</code>
* to get the new row count and all the appropriate values.
* The <code>JTable</code> will repaint the entire visible region on
* receiving this event, querying the model for the cell values that are visible.
* The structure of the table ie, the column names, types and order
* have not changed.
*/
public TableModelEvent(TableModel source) {
// Use Integer.MAX_VALUE instead of getRowCount() in case rows were deleted.
this(source, 0, Integer.MAX_VALUE, ALL_COLUMNS, UPDATE);
}
/** {@collect.stats}
* This row of data has been updated.
* To denote the arrival of a completely new table with a different structure
* use <code>HEADER_ROW</code> as the value for the <code>row</code>.
* When the <code>JTable</code> receives this event and its
* <code>autoCreateColumnsFromModel</code>
* flag is set it discards any TableColumns that it had and reallocates
* default ones in the order they appear in the model. This is the
* same as calling <code>setModel(TableModel)</code> on the <code>JTable</code>.
*/
public TableModelEvent(TableModel source, int row) {
this(source, row, row, ALL_COLUMNS, UPDATE);
}
/** {@collect.stats}
* The data in rows [<I>firstRow</I>, <I>lastRow</I>] have been updated.
*/
public TableModelEvent(TableModel source, int firstRow, int lastRow) {
this(source, firstRow, lastRow, ALL_COLUMNS, UPDATE);
}
/** {@collect.stats}
* The cells in column <I>column</I> in the range
* [<I>firstRow</I>, <I>lastRow</I>] have been updated.
*/
public TableModelEvent(TableModel source, int firstRow, int lastRow, int column) {
this(source, firstRow, lastRow, column, UPDATE);
}
/** {@collect.stats}
* The cells from (firstRow, column) to (lastRow, column) have been changed.
* The <I>column</I> refers to the column index of the cell in the model's
* co-ordinate system. When <I>column</I> is ALL_COLUMNS, all cells in the
* specified range of rows are considered changed.
* <p>
* The <I>type</I> should be one of: INSERT, UPDATE and DELETE.
*/
public TableModelEvent(TableModel source, int firstRow, int lastRow, int column, int type) {
super(source);
this.firstRow = firstRow;
this.lastRow = lastRow;
this.column = column;
this.type = type;
}
//
// Querying Methods
//
/** {@collect.stats} Returns the first row that changed. HEADER_ROW means the meta data,
* ie. names, types and order of the columns.
*/
public int getFirstRow() { return firstRow; };
/** {@collect.stats} Returns the last row that changed. */
public int getLastRow() { return lastRow; };
/** {@collect.stats}
* Returns the column for the event. If the return
* value is ALL_COLUMNS; it means every column in the specified
* rows changed.
*/
public int getColumn() { return column; };
/** {@collect.stats}
* Returns the type of event - one of: INSERT, UPDATE and DELETE.
*/
public int getType() { return type; }
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.awt.AWTEvent;
import javax.swing.JInternalFrame;
/** {@collect.stats}
* An <code>AWTEvent</code> that adds support for
* <code>JInternalFrame</code> objects as the event source. This class has the
* same event types as <code>WindowEvent</code>,
* although different IDs are used.
* Help on handling internal frame events
* is in
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/internalframelistener.html" target="_top">How to Write an Internal Frame Listener</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see java.awt.event.WindowEvent
* @see java.awt.event.WindowListener
* @see JInternalFrame
* @see InternalFrameListener
*
* @author Thomas Ball
*/
public class InternalFrameEvent extends AWTEvent {
/** {@collect.stats}
* The first number in the range of IDs used for internal frame events.
*/
public static final int INTERNAL_FRAME_FIRST = 25549;
/** {@collect.stats}
* The last number in the range of IDs used for internal frame events.
*/
public static final int INTERNAL_FRAME_LAST = 25555;
/** {@collect.stats}
* The "window opened" event. This event is delivered only
* the first time the internal frame is made visible.
*
* @see JInternalFrame#show
*/
public static final int INTERNAL_FRAME_OPENED = INTERNAL_FRAME_FIRST;
/** {@collect.stats}
* The "window is closing" event. This event is delivered when
* the user attempts to close the internal frame, such as by
* clicking the internal frame's close button,
* or when a program attempts to close the internal frame
* by invoking the <code>setClosed</code> method.
*
* @see JInternalFrame#setDefaultCloseOperation
* @see JInternalFrame#doDefaultCloseAction
* @see JInternalFrame#setClosed
*/
public static final int INTERNAL_FRAME_CLOSING = 1 + INTERNAL_FRAME_FIRST;
/** {@collect.stats}
* The "window closed" event. This event is delivered after
* the internal frame has been closed as the result of a call to
* the <code>setClosed</code> or
* <code>dispose</code> method.
*
* @see JInternalFrame#setClosed
* @see JInternalFrame#dispose
*/
public static final int INTERNAL_FRAME_CLOSED = 2 + INTERNAL_FRAME_FIRST;
/** {@collect.stats}
* The "window iconified" event.
* This event indicates that the internal frame
* was shrunk down to a small icon.
*
* @see JInternalFrame#setIcon
*/
public static final int INTERNAL_FRAME_ICONIFIED = 3 + INTERNAL_FRAME_FIRST;
/** {@collect.stats}
* The "window deiconified" event type. This event indicates that the
* internal frame has been restored to its normal size.
*
* @see JInternalFrame#setIcon
*/
public static final int INTERNAL_FRAME_DEICONIFIED = 4 + INTERNAL_FRAME_FIRST;
/** {@collect.stats}
* The "window activated" event type. This event indicates that keystrokes
* and mouse clicks are directed towards this internal frame.
*
* @see JInternalFrame#show
* @see JInternalFrame#setSelected
*/
public static final int INTERNAL_FRAME_ACTIVATED = 5 + INTERNAL_FRAME_FIRST;
/** {@collect.stats}
* The "window deactivated" event type. This event indicates that keystrokes
* and mouse clicks are no longer directed to the internal frame.
*
* @see JInternalFrame#setSelected
*/
public static final int INTERNAL_FRAME_DEACTIVATED = 6 + INTERNAL_FRAME_FIRST;
/** {@collect.stats}
* Constructs an <code>InternalFrameEvent</code> object.
* @param source the <code>JInternalFrame</code> object that originated the event
* @param id an integer indicating the type of event
*/
public InternalFrameEvent(JInternalFrame source, int id) {
super(source, id);
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
switch(id) {
case INTERNAL_FRAME_OPENED:
typeStr = "INTERNAL_FRAME_OPENED";
break;
case INTERNAL_FRAME_CLOSING:
typeStr = "INTERNAL_FRAME_CLOSING";
break;
case INTERNAL_FRAME_CLOSED:
typeStr = "INTERNAL_FRAME_CLOSED";
break;
case INTERNAL_FRAME_ICONIFIED:
typeStr = "INTERNAL_FRAME_ICONIFIED";
break;
case INTERNAL_FRAME_DEICONIFIED:
typeStr = "INTERNAL_FRAME_DEICONIFIED";
break;
case INTERNAL_FRAME_ACTIVATED:
typeStr = "INTERNAL_FRAME_ACTIVATED";
break;
case INTERNAL_FRAME_DEACTIVATED:
typeStr = "INTERNAL_FRAME_DEACTIVATED";
break;
default:
typeStr = "unknown type";
}
return typeStr;
}
/** {@collect.stats}
* Returns the originator of the event.
*
* @return the <code>JInternalFrame</code> object that originated the event
* @since 1.3
*/
public JInternalFrame getInternalFrame () {
return (source instanceof JInternalFrame)? (JInternalFrame)source : null;
}
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeEvent;
import javax.swing.SwingUtilities;
/** {@collect.stats}
* This subclass of {@code java.beans.PropertyChangeSupport} is almost
* identical in functionality. The only difference is if constructed with
* {@code SwingPropertyChangeSupport(sourceBean, true)} it ensures
* listeners are only ever notified on the <i>Event Dispatch Thread</i>.
*
* @author Igor Kushnirskiy
*/
public final class SwingPropertyChangeSupport extends PropertyChangeSupport {
/** {@collect.stats}
* Constructs a SwingPropertyChangeSupport object.
*
* @param sourceBean The bean to be given as the source for any
* events.
* @throws NullPointerException if {@code sourceBean} is
* {@code null}
*/
public SwingPropertyChangeSupport(Object sourceBean) {
this(sourceBean, false);
}
/** {@collect.stats}
* Constructs a SwingPropertyChangeSupport object.
*
* @param sourceBean the bean to be given as the source for any events
* @param notifyOnEDT whether to notify listeners on the <i>Event
* Dispatch Thread</i> only
*
* @throws NullPointerException if {@code sourceBean} is
* {@code null}
* @since 1.6
*/
public SwingPropertyChangeSupport(Object sourceBean, boolean notifyOnEDT) {
super(sourceBean);
this.notifyOnEDT = notifyOnEDT;
}
/** {@collect.stats}
* {@inheritDoc}
*
* <p>
* If {@link #isNotifyOnEDT} is {@code true} and called off the
* <i>Event Dispatch Thread</i> this implementation uses
* {@code SwingUtilities.invokeLater} to send out the notification
* on the <i>Event Dispatch Thread</i>. This ensures listeners
* are only ever notified on the <i>Event Dispatch Thread</i>.
*
* @throws NullPointerException if {@code evt} is
* {@code null}
* @since 1.6
*/
public void firePropertyChange(final PropertyChangeEvent evt) {
if (evt == null) {
throw new NullPointerException();
}
if (! isNotifyOnEDT()
|| SwingUtilities.isEventDispatchThread()) {
super.firePropertyChange(evt);
} else {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
firePropertyChange(evt);
}
});
}
}
/** {@collect.stats}
* Returns {@code notifyOnEDT} property.
*
* @return {@code notifyOnEDT} property
* @see #SwingPropertyChangeSupport(Object sourceBean, boolean notifyOnEDT)
* @since 1.6
*/
public final boolean isNotifyOnEDT() {
return notifyOnEDT;
}
// Serialization version ID
static final long serialVersionUID = 7162625831330845068L;
/** {@collect.stats}
* whether to notify listeners on EDT
*
* @serial
* @since 1.6
*/
private final boolean notifyOnEDT;
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* A popup menu listener
*
* @author Arnaud Weber
*/
public interface PopupMenuListener extends EventListener {
/** {@collect.stats}
* This method is called before the popup menu becomes visible
*/
void popupMenuWillBecomeVisible(PopupMenuEvent e);
/** {@collect.stats}
* This method is called before the popup menu becomes invisible
* Note that a JPopupMenu can become invisible any time
*/
void popupMenuWillBecomeInvisible(PopupMenuEvent e);
/** {@collect.stats}
* This method is called when the popup menu is canceled
*/
void popupMenuCanceled(PopupMenuEvent e);
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
/** {@collect.stats}
* CaretEvent is used to notify interested parties that
* the text caret has changed in the event source.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Timothy Prinzing
*/
public abstract class CaretEvent extends EventObject {
/** {@collect.stats}
* Creates a new CaretEvent object.
*
* @param source the object responsible for the event
*/
public CaretEvent(Object source) {
super(source);
}
/** {@collect.stats}
* Fetches the location of the caret.
*
* @return the dot >= 0
*/
public abstract int getDot();
/** {@collect.stats}
* Fetches the location of other end of a logical
* selection. If there is no selection, this
* will be the same as dot.
*
* @return the mark >= 0
*/
public abstract int getMark();
}
|
Java
|
/*
* Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
/** {@collect.stats}
* An abstract adapter class for receiving internal frame events.
* The methods in this class are empty. This class exists as
* convenience for creating listener objects, and is functionally
* equivalent to the WindowAdapter class in the AWT.
* <p>
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/internalframelistener.html">How to Write an Internal Frame Listener</a>
* in <em>The Java Tutorial</em> and
* <a href="http://www.awl.com/cp/javaseries/jcl1_2.html">The Java Class Libraries (update)</a>
*
* @see InternalFrameEvent
* @see InternalFrameListener
* @see java.awt.event.WindowListener
*
* @author Thomas Ball
*/
public abstract class InternalFrameAdapter implements InternalFrameListener {
/** {@collect.stats}
* Invoked when an internal frame has been opened.
*/
public void internalFrameOpened(InternalFrameEvent e) {}
/** {@collect.stats}
* Invoked when an internal frame is in the process of being closed.
* The close operation can be overridden at this point.
*/
public void internalFrameClosing(InternalFrameEvent e) {}
/** {@collect.stats}
* Invoked when an internal frame has been closed.
*/
public void internalFrameClosed(InternalFrameEvent e) {}
/** {@collect.stats}
* Invoked when an internal frame is iconified.
*/
public void internalFrameIconified(InternalFrameEvent e) {}
/** {@collect.stats}
* Invoked when an internal frame is de-iconified.
*/
public void internalFrameDeiconified(InternalFrameEvent e) {}
/** {@collect.stats}
* Invoked when an internal frame is activated.
*/
public void internalFrameActivated(InternalFrameEvent e) {}
/** {@collect.stats}
* Invoked when an internal frame is de-activated.
*/
public void internalFrameDeactivated(InternalFrameEvent e) {}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
import javax.swing.tree.TreePath;
/** {@collect.stats}
* An event used to identify a single path in a tree. The source
* returned by <b>getSource</b> will be an instance of JTree.
* <p>
* For further documentation and examples see
* the following sections in <em>The Java Tutorial</em>:
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/treeexpansionlistener.html">How to Write a Tree Expansion Listener</a> and
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/treewillexpandlistener.html">How to Write a Tree-Will-Expand Listener</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Scott Violet
*/
public class TreeExpansionEvent extends EventObject
{
/** {@collect.stats}
* Path to the value this event represents.
*/
protected TreePath path;
/** {@collect.stats}
* Constructs a TreeExpansionEvent object.
*
* @param source the Object that originated the event
* (typically <code>this</code>)
* @param path a TreePath object identifying the newly expanded
* node
*/
public TreeExpansionEvent(Object source, TreePath path) {
super(source);
this.path = path;
}
/** {@collect.stats}
* Returns the path to the value that has been expanded/collapsed.
*/
public TreePath getPath() { return path; }
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
/** {@collect.stats}
* PopupMenuEvent only contains the source of the event which is the JPoupMenu
* sending the event
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Arnaud Weber
*/
public class PopupMenuEvent extends EventObject {
/** {@collect.stats}
* Constructs a PopupMenuEvent object.
*
* @param source the Object that originated the event
* (typically <code>this</code>)
*/
public PopupMenuEvent(Object source) {
super(source);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.io.*;
import java.util.*;
import java.lang.reflect.Array;
/** {@collect.stats}
* A class that holds a list of EventListeners. A single instance
* can be used to hold all listeners (of all types) for the instance
* using the list. It is the responsiblity of the class using the
* EventListenerList to provide type-safe API (preferably conforming
* to the JavaBeans spec) and methods which dispatch event notification
* methods to appropriate Event Listeners on the list.
*
* The main benefits that this class provides are that it is relatively
* cheap in the case of no listeners, and it provides serialization for
* event-listener lists in a single place, as well as a degree of MT safety
* (when used correctly).
*
* Usage example:
* Say one is defining a class that sends out FooEvents, and one wants
* to allow users of the class to register FooListeners and receive
* notification when FooEvents occur. The following should be added
* to the class definition:
* <pre>
* EventListenerList listenerList = new EventListenerList();
* FooEvent fooEvent = null;
*
* public void addFooListener(FooListener l) {
* listenerList.add(FooListener.class, l);
* }
*
* public void removeFooListener(FooListener l) {
* listenerList.remove(FooListener.class, l);
* }
*
*
* // Notify all listeners that have registered interest for
* // notification on this event type. The event instance
* // is lazily created using the parameters passed into
* // the fire method.
*
* protected void fireFooXXX() {
* // Guaranteed to return a non-null array
* Object[] listeners = listenerList.getListenerList();
* // Process the listeners last to first, notifying
* // those that are interested in this event
* for (int i = listeners.length-2; i>=0; i-=2) {
* if (listeners[i]==FooListener.class) {
* // Lazily create the event:
* if (fooEvent == null)
* fooEvent = new FooEvent(this);
* ((FooListener)listeners[i+1]).fooXXX(fooEvent);
* }
* }
* }
* </pre>
* foo should be changed to the appropriate name, and fireFooXxx to the
* appropriate method name. One fire method should exist for each
* notification method in the FooListener interface.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Georges Saab
* @author Hans Muller
* @author James Gosling
*/
public class EventListenerList implements Serializable {
/* A null array to be shared by all empty listener lists*/
private final static Object[] NULL_ARRAY = new Object[0];
/* The list of ListenerType - Listener pairs */
protected transient Object[] listenerList = NULL_ARRAY;
/** {@collect.stats}
* Passes back the event listener list as an array
* of ListenerType-listener pairs. Note that for
* performance reasons, this implementation passes back
* the actual data structure in which the listener data
* is stored internally!
* This method is guaranteed to pass back a non-null
* array, so that no null-checking is required in
* fire methods. A zero-length array of Object should
* be returned if there are currently no listeners.
*
* WARNING!!! Absolutely NO modification of
* the data contained in this array should be made -- if
* any such manipulation is necessary, it should be done
* on a copy of the array returned rather than the array
* itself.
*/
public Object[] getListenerList() {
return listenerList;
}
/** {@collect.stats}
* Return an array of all the listeners of the given type.
* @return all of the listeners of the specified type.
* @exception ClassCastException if the supplied class
* is not assignable to EventListener
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> t) {
Object[] lList = listenerList;
int n = getListenerCount(lList, t);
T[] result = (T[])Array.newInstance(t, n);
int j = 0;
for (int i = lList.length-2; i>=0; i-=2) {
if (lList[i] == t) {
result[j++] = (T)lList[i+1];
}
}
return result;
}
/** {@collect.stats}
* Returns the total number of listeners for this listener list.
*/
public int getListenerCount() {
return listenerList.length/2;
}
/** {@collect.stats}
* Returns the total number of listeners of the supplied type
* for this listener list.
*/
public int getListenerCount(Class<?> t) {
Object[] lList = listenerList;
return getListenerCount(lList, t);
}
private int getListenerCount(Object[] list, Class t) {
int count = 0;
for (int i = 0; i < list.length; i+=2) {
if (t == (Class)list[i])
count++;
}
return count;
}
/** {@collect.stats}
* Adds the listener as a listener of the specified type.
* @param t the type of the listener to be added
* @param l the listener to be added
*/
public synchronized <T extends EventListener> void add(Class<T> t, T l) {
if (l==null) {
// In an ideal world, we would do an assertion here
// to help developers know they are probably doing
// something wrong
return;
}
if (!t.isInstance(l)) {
throw new IllegalArgumentException("Listener " + l +
" is not of type " + t);
}
if (listenerList == NULL_ARRAY) {
// if this is the first listener added,
// initialize the lists
listenerList = new Object[] { t, l };
} else {
// Otherwise copy the array and add the new listener
int i = listenerList.length;
Object[] tmp = new Object[i+2];
System.arraycopy(listenerList, 0, tmp, 0, i);
tmp[i] = t;
tmp[i+1] = l;
listenerList = tmp;
}
}
/** {@collect.stats}
* Removes the listener as a listener of the specified type.
* @param t the type of the listener to be removed
* @param l the listener to be removed
*/
public synchronized <T extends EventListener> void remove(Class<T> t, T l) {
if (l ==null) {
// In an ideal world, we would do an assertion here
// to help developers know they are probably doing
// something wrong
return;
}
if (!t.isInstance(l)) {
throw new IllegalArgumentException("Listener " + l +
" is not of type " + t);
}
// Is l on the list?
int index = -1;
for (int i = listenerList.length-2; i>=0; i-=2) {
if ((listenerList[i]==t) && (listenerList[i+1].equals(l) == true)) {
index = i;
break;
}
}
// If so, remove it
if (index != -1) {
Object[] tmp = new Object[listenerList.length-2];
// Copy the list up to index
System.arraycopy(listenerList, 0, tmp, 0, index);
// Copy from two past the index, up to
// the end of tmp (which is two elements
// shorter than the old list)
if (index < tmp.length)
System.arraycopy(listenerList, index+2, tmp, index,
tmp.length - index);
// set the listener array to the new array or null
listenerList = (tmp.length == 0) ? NULL_ARRAY : tmp;
}
}
// Serialization support.
private void writeObject(ObjectOutputStream s) throws IOException {
Object[] lList = listenerList;
s.defaultWriteObject();
// Save the non-null event listeners:
for (int i = 0; i < lList.length; i+=2) {
Class t = (Class)lList[i];
EventListener l = (EventListener)lList[i+1];
if ((l!=null) && (l instanceof Serializable)) {
s.writeObject(t.getName());
s.writeObject(l);
}
}
s.writeObject(null);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
listenerList = NULL_ARRAY;
s.defaultReadObject();
Object listenerTypeOrNull;
while (null != (listenerTypeOrNull = s.readObject())) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
EventListener l = (EventListener)s.readObject();
add((Class<EventListener>)Class.forName((String)listenerTypeOrNull, true, cl), l);
}
}
/** {@collect.stats}
* Returns a string representation of the EventListenerList.
*/
public String toString() {
Object[] lList = listenerList;
String s = "EventListenerList: ";
s += lList.length/2 + " listeners: ";
for (int i = 0 ; i <= lList.length-2 ; i+=2) {
s += " type " + ((Class)lList[i]).getName();
s += " listener " + lList[i+1];
}
return s;
}
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import javax.swing.MenuElement;
import javax.swing.MenuSelectionManager;
import java.util.EventObject;
import java.awt.event.MouseEvent;
import java.awt.Component;
/** {@collect.stats}
* MenuDragMouseEvent is used to notify interested parties that
* the menu element has received a MouseEvent forwarded to it
* under drag conditions.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Georges Saab
*/
public class MenuDragMouseEvent extends MouseEvent {
private MenuElement path[];
private MenuSelectionManager manager;
/** {@collect.stats}
* Constructs a MenuDragMouseEvent object.
* <p>Absolute coordinates xAbs and yAbs are set to source's location on screen plus
* relative coordinates x and y. xAbs and yAbs are set to zero if the source is not showing.
*
* @param source the Component that originated the event
* (typically <code>this</code>)
* @param id an int specifying the type of event, as defined
* in {@link java.awt.event.MouseEvent}
* @param when a long identifying the time the event occurred
* @param modifiers an int specifying any modifier keys held down,
* as specified in {@link java.awt.event.InputEvent}
* @param x an int specifying the horizontal position at which
* the event occurred, in pixels
* @param y an int specifying the vertical position at which
* the event occurred, in pixels
* @param clickCount an int specifying the number of mouse-clicks
* @param popupTrigger a boolean -- true if the event {should?/did?}
* trigger a popup
* @param p an array of MenuElement objects specifying a path
* to a menu item affected by the drag
* @param m a MenuSelectionManager object that handles selections
* @see MouseEvent#MouseEvent(java.awt.Component, int, long, int, int, int, int, int, int, boolean, int)
*/
public MenuDragMouseEvent(Component source, int id, long when,
int modifiers, int x, int y, int clickCount,
boolean popupTrigger, MenuElement p[],
MenuSelectionManager m) {
super(source, id, when, modifiers, x, y, clickCount, popupTrigger);
path = p;
manager = m;
}
/** {@collect.stats}
* Constructs a MenuDragMouseEvent object.
* <p>Even if inconsistent values for relative and absolute coordinates are
* passed to the constructor, the MenuDragMouseEvent instance is still
* created.
* @param source the Component that originated the event
* (typically <code>this</code>)
* @param id an int specifying the type of event, as defined
* in {@link java.awt.event.MouseEvent}
* @param when a long identifying the time the event occurred
* @param modifiers an int specifying any modifier keys held down,
* as specified in {@link java.awt.event.InputEvent}
* @param x an int specifying the horizontal position at which
* the event occurred, in pixels
* @param y an int specifying the vertical position at which
* the event occurred, in pixels
* @param xAbs an int specifying the horizontal absolute position at which
* the event occurred, in pixels
* @param yAbs an int specifying the vertical absolute position at which
* the event occurred, in pixels
* @param clickCount an int specifying the number of mouse-clicks
* @param popupTrigger a boolean -- true if the event {should?/did?}
* trigger a popup
* @param p an array of MenuElement objects specifying a path
* to a menu item affected by the drag
* @param m a MenuSelectionManager object that handles selections
* @see MouseEvent#MouseEvent(java.awt.Component, int, long, int, int, int, int, int, int, boolean, int)
* @since 1.6
*/
public MenuDragMouseEvent(Component source, int id, long when,
int modifiers, int x, int y, int xAbs,
int yAbs, int clickCount,
boolean popupTrigger, MenuElement p[],
MenuSelectionManager m) {
super(source, id, when, modifiers, x, y, xAbs, yAbs, clickCount,
popupTrigger, MouseEvent.NOBUTTON);
path = p;
manager = m;
}
/** {@collect.stats}
* Returns the path to the selected menu item.
*
* @return an array of MenuElement objects representing the path value
*/
public MenuElement[] getPath() {
return path;
}
/** {@collect.stats}
* Returns the current menu selection manager.
*
* @return a MenuSelectionManager object
*/
public MenuSelectionManager getMenuSelectionManager() {
return manager;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
import javax.swing.tree.TreePath;
/** {@collect.stats}
* Encapsulates information describing changes to a tree model, and
* used to notify tree model listeners of the change.
* For more information and examples see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/events/treemodellistener.html">How to Write a Tree Model Listener</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Rob Davis
* @author Ray Ryan
* @author Scott Violet
*/
public class TreeModelEvent extends EventObject {
/** {@collect.stats} Path to the parent of the nodes that have changed. */
protected TreePath path;
/** {@collect.stats} Indices identifying the position of where the children were. */
protected int[] childIndices;
/** {@collect.stats} Children that have been removed. */
protected Object[] children;
/** {@collect.stats}
* Used to create an event when nodes have been changed, inserted, or
* removed, identifying the path to the parent of the modified items as
* an array of Objects. All of the modified objects are siblings which are
* direct descendents (not grandchildren) of the specified parent.
* The positions at which the inserts, deletes, or changes occurred are
* specified by an array of <code>int</code>. The indexes in that array
* must be in order, from lowest to highest.
* <p>
* For changes, the indexes in the model correspond exactly to the indexes
* of items currently displayed in the UI. As a result, it is not really
* critical if the indexes are not in their exact order. But after multiple
* inserts or deletes, the items currently in the UI no longer correspond
* to the items in the model. It is therefore critical to specify the
* indexes properly for inserts and deletes.
* <p>
* For inserts, the indexes represent the <i>final</i> state of the tree,
* after the inserts have occurred. Since the indexes must be specified in
* order, the most natural processing methodology is to do the inserts
* starting at the lowest index and working towards the highest. Accumulate
* a Vector of <code>Integer</code> objects that specify the
* insert-locations as you go, then convert the Vector to an
* array of <code>int</code> to create the event. When the postition-index
* equals zero, the node is inserted at the beginning of the list. When the
* position index equals the size of the list, the node is "inserted" at
* (appended to) the end of the list.
* <p>
* For deletes, the indexes represent the <i>initial</i> state of the tree,
* before the deletes have occurred. Since the indexes must be specified in
* order, the most natural processing methodology is to use a delete-counter.
* Start by initializing the counter to zero and start work through the
* list from lowest to higest. Every time you do a delete, add the current
* value of the delete-counter to the index-position where the delete occurred,
* and append the result to a Vector of delete-locations, using
* <code>addElement()</code>. Then increment the delete-counter. The index
* positions stored in the Vector therefore reflect the effects of all previous
* deletes, so they represent each object's position in the initial tree.
* (You could also start at the highest index and working back towards the
* lowest, accumulating a Vector of delete-locations as you go using the
* <code>insertElementAt(Integer, 0)</code>.) However you produce the Vector
* of initial-positions, you then need to convert the Vector of <code>Integer</code>
* objects to an array of <code>int</code> to create the event.
* <p>
* <b>Notes:</b><ul>
* <li>Like the <code>insertNodeInto</code> method in the
* <code>DefaultTreeModel</code> class, <code>insertElementAt</code>
* appends to the <code>Vector</code> when the index matches the size
* of the vector. So you can use <code>insertElementAt(Integer, 0)</code>
* even when the vector is empty.
* <ul>To create a node changed event for the root node, specify the parent
* and the child indices as <code>null</code>.
* </ul>
*
* @param source the Object responsible for generating the event (typically
* the creator of the event object passes <code>this</code>
* for its value)
* @param path an array of Object identifying the path to the
* parent of the modified item(s), where the first element
* of the array is the Object stored at the root node and
* the last element is the Object stored at the parent node
* @param childIndices an array of <code>int</code> that specifies the
* index values of the removed items. The indices must be
* in sorted order, from lowest to highest
* @param children an array of Object containing the inserted, removed, or
* changed objects
* @see TreePath
*/
public TreeModelEvent(Object source, Object[] path, int[] childIndices,
Object[] children)
{
this(source, new TreePath(path), childIndices, children);
}
/** {@collect.stats}
* Used to create an event when nodes have been changed, inserted, or
* removed, identifying the path to the parent of the modified items as
* a TreePath object. For more information on how to specify the indexes
* and objects, see
* <code>TreeModelEvent(Object,Object[],int[],Object[])</code>.
*
* @param source the Object responsible for generating the event (typically
* the creator of the event object passes <code>this</code>
* for its value)
* @param path a TreePath object that identifies the path to the
* parent of the modified item(s)
* @param childIndices an array of <code>int</code> that specifies the
* index values of the modified items
* @param children an array of Object containing the inserted, removed, or
* changed objects
*
* @see #TreeModelEvent(Object,Object[],int[],Object[])
*/
public TreeModelEvent(Object source, TreePath path, int[] childIndices,
Object[] children)
{
super(source);
this.path = path;
this.childIndices = childIndices;
this.children = children;
}
/** {@collect.stats}
* Used to create an event when the node structure has changed in some way,
* identifying the path to the root of a modified subtree as an array of
* Objects. A structure change event might involve nodes swapping position,
* for example, or it might encapsulate multiple inserts and deletes in the
* subtree stemming from the node, where the changes may have taken place at
* different levels of the subtree.
* <blockquote>
* <b>Note:</b><br>
* JTree collapses all nodes under the specified node, so that only its
* immediate children are visible.
* </blockquote>
*
* @param source the Object responsible for generating the event (typically
* the creator of the event object passes <code>this</code>
* for its value)
* @param path an array of Object identifying the path to the root of the
* modified subtree, where the first element of the array is
* the object stored at the root node and the last element
* is the object stored at the changed node
* @see TreePath
*/
public TreeModelEvent(Object source, Object[] path)
{
this(source, new TreePath(path));
}
/** {@collect.stats}
* Used to create an event when the node structure has changed in some way,
* identifying the path to the root of the modified subtree as a TreePath
* object. For more information on this event specification, see
* <code>TreeModelEvent(Object,Object[])</code>.
*
* @param source the Object responsible for generating the event (typically
* the creator of the event object passes <code>this</code>
* for its value)
* @param path a TreePath object that identifies the path to the
* change. In the DefaultTreeModel,
* this object contains an array of user-data objects,
* but a subclass of TreePath could use some totally
* different mechanism -- for example, a node ID number
*
* @see #TreeModelEvent(Object,Object[])
*/
public TreeModelEvent(Object source, TreePath path)
{
super(source);
this.path = path;
this.childIndices = new int[0];
}
/** {@collect.stats}
* For all events, except treeStructureChanged,
* returns the parent of the changed nodes.
* For treeStructureChanged events, returns the ancestor of the
* structure that has changed. This and
* <code>getChildIndices</code> are used to get a list of the effected
* nodes.
* <p>
* The one exception to this is a treeNodesChanged event that is to
* identify the root, in which case this will return the root
* and <code>getChildIndices</code> will return null.
*
* @return the TreePath used in identifying the changed nodes.
* @see TreePath#getLastPathComponent
*/
public TreePath getTreePath() { return path; }
/** {@collect.stats}
* Convenience method to get the array of objects from the TreePath
* instance that this event wraps.
*
* @return an array of Objects, where the first Object is the one
* stored at the root and the last object is the one
* stored at the node identified by the path
*/
public Object[] getPath() {
if(path != null)
return path.getPath();
return null;
}
/** {@collect.stats}
* Returns the objects that are children of the node identified by
* <code>getPath</code> at the locations specified by
* <code>getChildIndices</code>. If this is a removal event the
* returned objects are no longer children of the parent node.
*
* @return an array of Object containing the children specified by
* the event
* @see #getPath
* @see #getChildIndices
*/
public Object[] getChildren() {
if(children != null) {
int cCount = children.length;
Object[] retChildren = new Object[cCount];
System.arraycopy(children, 0, retChildren, 0, cCount);
return retChildren;
}
return null;
}
/** {@collect.stats}
* Returns the values of the child indexes. If this is a removal event
* the indexes point to locations in the initial list where items
* were removed. If it is an insert, the indices point to locations
* in the final list where the items were added. For node changes,
* the indices point to the locations of the modified nodes.
*
* @return an array of <code>int</code> containing index locations for
* the children specified by the event
*/
public int[] getChildIndices() {
if(childIndices != null) {
int cCount = childIndices.length;
int[] retArray = new int[cCount];
System.arraycopy(childIndices, 0, retArray, 0, cCount);
return retArray;
}
return null;
}
/** {@collect.stats}
* Returns a string that displays and identifies this object's
* properties.
*
* @return a String representation of this object
*/
public String toString() {
StringBuffer retBuffer = new StringBuffer();
retBuffer.append(getClass().getName() + " " +
Integer.toString(hashCode()));
if(path != null)
retBuffer.append(" path " + path);
if(childIndices != null) {
retBuffer.append(" indices [ ");
for(int counter = 0; counter < childIndices.length; counter++)
retBuffer.append(Integer.toString(childIndices[counter])+ " ");
retBuffer.append("]");
}
if(children != null) {
retBuffer.append(" children [ ");
for(int counter = 0; counter < children.length; counter++)
retBuffer.append(children[counter] + " ");
retBuffer.append("]");
}
return retBuffer.toString();
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
import javax.swing.table.*;
/** {@collect.stats}
* <B>TableColumnModelEvent</B> is used to notify listeners that a table
* column model has changed, such as a column was added, removed, or
* moved.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Alan Chung
* @see TableColumnModelListener
*/
public class TableColumnModelEvent extends java.util.EventObject
{
//
// Instance Variables
//
/** {@collect.stats} The index of the column from where it was moved or removed */
protected int fromIndex;
/** {@collect.stats} The index of the column to where it was moved or added */
protected int toIndex;
//
// Constructors
//
/** {@collect.stats}
* Constructs a {@code TableColumnModelEvent} object.
*
* @param source the {@code TableColumnModel} that originated the event
* @param from an int specifying the index from where the column was
* moved or removed
* @param to an int specifying the index to where the column was
* moved or added
* @see #getFromIndex
* @see #getToIndex
*/
public TableColumnModelEvent(TableColumnModel source, int from, int to) {
super(source);
fromIndex = from;
toIndex = to;
}
//
// Querying Methods
//
/** {@collect.stats} Returns the fromIndex. Valid for removed or moved events */
public int getFromIndex() { return fromIndex; };
/** {@collect.stats} Returns the toIndex. Valid for add and moved events */
public int getToIndex() { return toIndex; };
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import javax.swing.undo.*;
/** {@collect.stats}
* An event indicating that an operation which can be undone has occurred.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Ray Ryan
*/
public class UndoableEditEvent extends java.util.EventObject {
private UndoableEdit myEdit;
/** {@collect.stats}
* Constructs an UndoableEditEvent object.
*
* @param source the Object that originated the event
* (typically <code>this</code>)
* @param edit an UndoableEdit object
*/
public UndoableEditEvent(Object source, UndoableEdit edit) {
super(source);
myEdit = edit;
}
/** {@collect.stats}
* Returns the edit value.
*
* @return the UndoableEdit object encapsulating the edit
*/
public UndoableEdit getEdit() {
return myEdit;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
import javax.swing.*;
/** {@collect.stats}
* An event that characterizes a change in selection. The change is limited to a
* a single inclusive interval. The selection of at least one index within the
* range will have changed. A decent {@code ListSelectionModel} implementation
* will keep the range as small as possible. {@code ListSelectionListeners} will
* generally query the source of the event for the new selected status of each
* potentially changed row.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Hans Muller
* @author Ray Ryan
* @see ListSelectionModel
*/
public class ListSelectionEvent extends EventObject
{
private int firstIndex;
private int lastIndex;
private boolean isAdjusting;
/** {@collect.stats}
* Represents a change in selection status between {@code firstIndex} and
* {@code lastIndex}, inclusive. {@code firstIndex} is less than or equal to
* {@code lastIndex}. The selection of at least one index within the range will
* have changed.
*
* @param firstIndex the first index in the range, <= lastIndex
* @param lastIndex the last index in the range, >= firstIndex
* @param isAdjusting whether or not this is one in a series of
* multiple events, where changes are still being made
*/
public ListSelectionEvent(Object source, int firstIndex, int lastIndex,
boolean isAdjusting)
{
super(source);
this.firstIndex = firstIndex;
this.lastIndex = lastIndex;
this.isAdjusting = isAdjusting;
}
/** {@collect.stats}
* Returns the index of the first row whose selection may have changed.
* {@code getFirstIndex() <= getLastIndex()}
*
* @return the first row whose selection value may have changed,
* where zero is the first row
*/
public int getFirstIndex() { return firstIndex; }
/** {@collect.stats}
* Returns the index of the last row whose selection may have changed.
* {@code getLastIndex() >= getFirstIndex()}
*
* @return the last row whose selection value may have changed,
* where zero is the first row
*/
public int getLastIndex() { return lastIndex; }
/** {@collect.stats}
* Returns whether or not this is one in a series of multiple events,
* where changes are still being made. See the documentation for
* {@link javax.swing.ListSelectionModel#setValueIsAdjusting} for
* more details on how this is used.
*
* @return {@code true} if this is one in a series of multiple events,
* where changes are still being made
*/
public boolean getValueIsAdjusting() { return isAdjusting; }
/** {@collect.stats}
* Returns a {@code String} that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public String toString() {
String properties =
" source=" + getSource() +
" firstIndex= " + firstIndex +
" lastIndex= " + lastIndex +
" isAdjusting= " + isAdjusting +
" ";
return getClass().getName() + "[" + properties + "]";
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* ListDataListener
*
* @author Hans Muller
*/
public interface ListDataListener extends EventListener {
/** {@collect.stats}
* Sent after the indices in the index0,index1
* interval have been inserted in the data model.
* The new interval includes both index0 and index1.
*
* @param e a <code>ListDataEvent</code> encapsulating the
* event information
*/
void intervalAdded(ListDataEvent e);
/** {@collect.stats}
* Sent after the indices in the index0,index1 interval
* have been removed from the data model. The interval
* includes both index0 and index1.
*
* @param e a <code>ListDataEvent</code> encapsulating the
* event information
*/
void intervalRemoved(ListDataEvent e);
/** {@collect.stats}
* Sent when the contents of the list has changed in a way
* that's too complex to characterize with the previous
* methods. For example, this is sent when an item has been
* replaced. Index0 and index1 bracket the change.
*
* @param e a <code>ListDataEvent</code> encapsulating the
* event information
*/
void contentsChanged(ListDataEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* HyperlinkListener
*
* @author Timothy Prinzing
*/
public interface HyperlinkListener extends EventListener {
/** {@collect.stats}
* Called when a hypertext link is updated.
*
* @param e the event responsible for the update
*/
void hyperlinkUpdate(HyperlinkEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
/** {@collect.stats}
* AncestorListener
*
* Interface to support notification when changes occur to a JComponent or one
* of its ancestors. These include movement and when the component becomes
* visible or invisible, either by the setVisible() method or by being added
* or removed from the component hierarchy.
*
* @author Dave Moore
*/
public interface AncestorListener extends EventListener {
/** {@collect.stats}
* Called when the source or one of its ancestors is made visible
* either by setVisible(true) being called or by its being
* added to the component hierarchy. The method is only called
* if the source has actually become visible. For this to be true
* all its parents must be visible and it must be in a hierarchy
* rooted at a Window
*/
public void ancestorAdded(AncestorEvent event);
/** {@collect.stats}
* Called when the source or one of its ancestors is made invisible
* either by setVisible(false) being called or by its being
* remove from the component hierarchy. The method is only called
* if the source has actually become invisible. For this to be true
* at least one of its parents must by invisible or it is not in
* a hierarchy rooted at a Window
*/
public void ancestorRemoved(AncestorEvent event);
/** {@collect.stats}
* Called when either the source or one of its ancestors is moved.
*/
public void ancestorMoved(AncestorEvent event);
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
/** {@collect.stats}
* TableModelListener defines the interface for an object that listens
* to changes in a TableModel.
*
* @author Alan Chung
* @see javax.swing.table.TableModel
*/
public interface TableModelListener extends java.util.EventListener
{
/** {@collect.stats}
* This fine grain notification tells listeners the exact range
* of cells, rows, or columns that changed.
*/
public void tableChanged(TableModelEvent e);
}
|
Java
|
/*
* Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventListener;
import javax.swing.tree.ExpandVetoException;
/** {@collect.stats}
* The listener that's notified when a tree expands or collapses
* a node.
* For further information and examples see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/treewillexpandlistener.html">How to Write a Tree-Will-Expand Listener</a>,
* a section in <em>The Java Tutorial.</em>
*
* @author Scott Violet
*/
public interface TreeWillExpandListener extends EventListener {
/** {@collect.stats}
* Invoked whenever a node in the tree is about to be expanded.
*/
public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException;
/** {@collect.stats}
* Invoked whenever a node in the tree is about to be collapsed.
*/
public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException;
}
|
Java
|
/*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.util.EventObject;
/** {@collect.stats}
* Defines an event that encapsulates changes to a list.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Hans Muller
*/
public class ListDataEvent extends EventObject
{
/** {@collect.stats} Identifies one or more changes in the lists contents. */
public static final int CONTENTS_CHANGED = 0;
/** {@collect.stats} Identifies the addition of one or more contiguous items to the list */
public static final int INTERVAL_ADDED = 1;
/** {@collect.stats} Identifies the removal of one or more contiguous items from the list */
public static final int INTERVAL_REMOVED = 2;
private int type;
private int index0;
private int index1;
/** {@collect.stats}
* Returns the event type. The possible values are:
* <ul>
* <li> {@link #CONTENTS_CHANGED}
* <li> {@link #INTERVAL_ADDED}
* <li> {@link #INTERVAL_REMOVED}
* </ul>
*
* @return an int representing the type value
*/
public int getType() { return type; }
/** {@collect.stats}
* Returns the lower index of the range. For a single
* element, this value is the same as that returned by {@link #getIndex1}.
*
* @return an int representing the lower index value
*/
public int getIndex0() { return index0; }
/** {@collect.stats}
* Returns the upper index of the range. For a single
* element, this value is the same as that returned by {@link #getIndex0}.
*
* @return an int representing the upper index value
*/
public int getIndex1() { return index1; }
/** {@collect.stats}
* Constructs a ListDataEvent object. If index0 is >
* index1, index0 and index1 will be swapped such that
* index0 will always be <= index1.
*
* @param source the source Object (typically <code>this</code>)
* @param type an int specifying {@link #CONTENTS_CHANGED},
* {@link #INTERVAL_ADDED}, or {@link #INTERVAL_REMOVED}
* @param index0 one end of the new interval
* @param index1 the other end of the new interval
*/
public ListDataEvent(Object source, int type, int index0, int index1) {
super(source);
this.type = type;
this.index0 = Math.min(index0, index1);
this.index1 = Math.max(index0, index1);
}
/** {@collect.stats}
* Returns a string representation of this ListDataEvent. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @since 1.4
* @return a string representation of this ListDataEvent.
*/
public String toString() {
return getClass().getName() +
"[type=" + type +
",index0=" + index0 +
",index1=" + index1 + "]";
}
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.event;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
/** {@collect.stats}
* An event reported to a child component that originated from an
* ancestor in the component hierarchy.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Dave Moore
*/
public class AncestorEvent extends AWTEvent {
/** {@collect.stats}
* An ancestor-component was added to the hierarchy of
* visible objects (made visible), and is currently being displayed.
*/
public static final int ANCESTOR_ADDED = 1;
/** {@collect.stats}
* An ancestor-component was removed from the hierarchy
* of visible objects (hidden) and is no longer being displayed.
*/
public static final int ANCESTOR_REMOVED = 2;
/** {@collect.stats} An ancestor-component changed its position on the screen. */
public static final int ANCESTOR_MOVED = 3;
Container ancestor;
Container ancestorParent;
/** {@collect.stats}
* Constructs an AncestorEvent object to identify a change
* in an ancestor-component's display-status.
*
* @param source the JComponent that originated the event
* (typically <code>this</code>)
* @param id an int specifying {@link #ANCESTOR_ADDED},
* {@link #ANCESTOR_REMOVED} or {@link #ANCESTOR_MOVED}
* @param ancestor a Container object specifying the ancestor-component
* whose display-status changed
* @param ancestorParent a Container object specifying the ancestor's parent
*/
public AncestorEvent(JComponent source, int id, Container ancestor, Container ancestorParent) {
super(source, id);
this.ancestor = ancestor;
this.ancestorParent = ancestorParent;
}
/** {@collect.stats}
* Returns the ancestor that the event actually occurred on.
*/
public Container getAncestor() {
return ancestor;
}
/** {@collect.stats}
* Returns the parent of the ancestor the event actually occurred on.
* This is most interesting in an ANCESTOR_REMOVED event, as
* the ancestor may no longer be in the component hierarchy.
*/
public Container getAncestorParent() {
return ancestorParent;
}
/** {@collect.stats}
* Returns the component that the listener was added to.
*/
public JComponent getComponent() {
return (JComponent)getSource();
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.io.Serializable;
/** {@collect.stats}
* A layout manager to arrange components over the top
* of each other. The requested size of the container
* will be the largest requested size of the children,
* taking alignment needs into consideration.
*
* The alignment is based upon what is needed to properly
* fit the children in the allocation area. The children
* will be placed such that their alignment points are all
* on top of each other.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Timothy Prinzing
*/
public class OverlayLayout implements LayoutManager2,Serializable {
/** {@collect.stats}
* Constructs a layout manager that performs overlay
* arrangement of the children. The layout manager
* created is dedicated to the given container.
*
* @param target the container to do layout against
*/
public OverlayLayout(Container target) {
this.target = target;
}
/** {@collect.stats}
* Returns the container that uses this layout manager.
*
* @return the container that uses this layout manager
*
* @since 1.6
*/
public final Container getTarget() {
return this.target;
}
/** {@collect.stats}
* Indicates a child has changed its layout related information,
* which causes any cached calculations to be flushed.
*
* @param target the container
*/
public void invalidateLayout(Container target) {
checkContainer(target);
xChildren = null;
yChildren = null;
xTotal = null;
yTotal = null;
}
/** {@collect.stats}
* Adds the specified component to the layout. Used by
* this class to know when to invalidate layout.
*
* @param name the name of the component
* @param comp the the component to be added
*/
public void addLayoutComponent(String name, Component comp) {
invalidateLayout(comp.getParent());
}
/** {@collect.stats}
* Removes the specified component from the layout. Used by
* this class to know when to invalidate layout.
*
* @param comp the component to remove
*/
public void removeLayoutComponent(Component comp) {
invalidateLayout(comp.getParent());
}
/** {@collect.stats}
* Adds the specified component to the layout, using the specified
* constraint object. Used by this class to know when to invalidate
* layout.
*
* @param comp the component to be added
* @param constraints where/how the component is added to the layout.
*/
public void addLayoutComponent(Component comp, Object constraints) {
invalidateLayout(comp.getParent());
}
/** {@collect.stats}
* Returns the preferred dimensions for this layout given the components
* in the specified target container. Recomputes the layout if it
* has been invalidated. Factors in the current inset setting returned
* by getInsets().
*
* @param target the component which needs to be laid out
* @return a Dimension object containing the preferred dimensions
* @see #minimumLayoutSize
*/
public Dimension preferredLayoutSize(Container target) {
checkContainer(target);
checkRequests();
Dimension size = new Dimension(xTotal.preferred, yTotal.preferred);
Insets insets = target.getInsets();
size.width += insets.left + insets.right;
size.height += insets.top + insets.bottom;
return size;
}
/** {@collect.stats}
* Returns the minimum dimensions needed to lay out the components
* contained in the specified target container. Recomputes the layout
* if it has been invalidated, and factors in the current inset setting.
*
* @param target the component which needs to be laid out
* @return a Dimension object containing the minimum dimensions
* @see #preferredLayoutSize
*/
public Dimension minimumLayoutSize(Container target) {
checkContainer(target);
checkRequests();
Dimension size = new Dimension(xTotal.minimum, yTotal.minimum);
Insets insets = target.getInsets();
size.width += insets.left + insets.right;
size.height += insets.top + insets.bottom;
return size;
}
/** {@collect.stats}
* Returns the maximum dimensions needed to lay out the components
* contained in the specified target container. Recomputes the
* layout if it has been invalidated, and factors in the inset setting
* returned by <code>getInset</code>.
*
* @param target the component that needs to be laid out
* @return a <code>Dimension</code> object containing the maximum
* dimensions
* @see #preferredLayoutSize
*/
public Dimension maximumLayoutSize(Container target) {
checkContainer(target);
checkRequests();
Dimension size = new Dimension(xTotal.maximum, yTotal.maximum);
Insets insets = target.getInsets();
size.width += insets.left + insets.right;
size.height += insets.top + insets.bottom;
return size;
}
/** {@collect.stats}
* Returns the alignment along the x axis for the container.
*
* @param target the container
* @return the alignment >= 0.0f && <= 1.0f
*/
public float getLayoutAlignmentX(Container target) {
checkContainer(target);
checkRequests();
return xTotal.alignment;
}
/** {@collect.stats}
* Returns the alignment along the y axis for the container.
*
* @param target the container
* @return the alignment >= 0.0f && <= 1.0f
*/
public float getLayoutAlignmentY(Container target) {
checkContainer(target);
checkRequests();
return yTotal.alignment;
}
/** {@collect.stats}
* Called by the AWT when the specified container needs to be laid out.
*
* @param target the container to lay out
*
* @exception AWTError if the target isn't the container specified to the
* constructor
*/
public void layoutContainer(Container target) {
checkContainer(target);
checkRequests();
int nChildren = target.getComponentCount();
int[] xOffsets = new int[nChildren];
int[] xSpans = new int[nChildren];
int[] yOffsets = new int[nChildren];
int[] ySpans = new int[nChildren];
// determine the child placements
Dimension alloc = target.getSize();
Insets in = target.getInsets();
alloc.width -= in.left + in.right;
alloc.height -= in.top + in.bottom;
SizeRequirements.calculateAlignedPositions(alloc.width, xTotal,
xChildren, xOffsets,
xSpans);
SizeRequirements.calculateAlignedPositions(alloc.height, yTotal,
yChildren, yOffsets,
ySpans);
// flush changes to the container
for (int i = 0; i < nChildren; i++) {
Component c = target.getComponent(i);
c.setBounds(in.left + xOffsets[i], in.top + yOffsets[i],
xSpans[i], ySpans[i]);
}
}
void checkContainer(Container target) {
if (this.target != target) {
throw new AWTError("OverlayLayout can't be shared");
}
}
void checkRequests() {
if (xChildren == null || yChildren == null) {
// The requests have been invalidated... recalculate
// the request information.
int n = target.getComponentCount();
xChildren = new SizeRequirements[n];
yChildren = new SizeRequirements[n];
for (int i = 0; i < n; i++) {
Component c = target.getComponent(i);
Dimension min = c.getMinimumSize();
Dimension typ = c.getPreferredSize();
Dimension max = c.getMaximumSize();
xChildren[i] = new SizeRequirements(min.width, typ.width,
max.width,
c.getAlignmentX());
yChildren[i] = new SizeRequirements(min.height, typ.height,
max.height,
c.getAlignmentY());
}
xTotal = SizeRequirements.getAlignedSizeRequirements(xChildren);
yTotal = SizeRequirements.getAlignedSizeRequirements(yChildren);
}
}
private Container target;
private SizeRequirements[] xChildren;
private SizeRequirements[] yChildren;
private SizeRequirements xTotal;
private SizeRequirements yTotal;
}
|
Java
|
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.event.ListDataListener;
/** {@collect.stats}
* This interface defines the methods components like JList use
* to get the value of each cell in a list and the length of the list.
* Logically the model is a vector, indices vary from 0 to
* ListDataModel.getSize() - 1. Any change to the contents or
* length of the data model must be reported to all of the
* ListDataListeners.
*
* @author Hans Muller
* @see JList
*/
public interface ListModel
{
/** {@collect.stats}
* Returns the length of the list.
* @return the length of the list
*/
int getSize();
/** {@collect.stats}
* Returns the value at the specified index.
* @param index the requested index
* @return the value at <code>index</code>
*/
Object getElementAt(int index);
/** {@collect.stats}
* Adds a listener to the list that's notified each time a change
* to the data model occurs.
* @param l the <code>ListDataListener</code> to be added
*/
void addListDataListener(ListDataListener l);
/** {@collect.stats}
* Removes a listener from the list that's notified each time a
* change to the data model occurs.
* @param l the <code>ListDataListener</code> to be removed
*/
void removeListDataListener(ListDataListener l);
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.text.*;
import javax.swing.plaf.*;
import javax.swing.event.*;
import javax.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.Serializable;
/** {@collect.stats}
* <code>JTextField</code> is a lightweight component that allows the editing
* of a single line of text.
* For information on and examples of using text fields,
* see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html">How to Use Text Fields</a>
* in <em>The Java Tutorial.</em>
*
* <p>
* <code>JTextField</code> is intended to be source-compatible
* with <code>java.awt.TextField</code> where it is reasonable to do so. This
* component has capabilities not found in the <code>java.awt.TextField</code>
* class. The superclass should be consulted for additional capabilities.
* <p>
* <code>JTextField</code> has a method to establish the string used as the
* command string for the action event that gets fired. The
* <code>java.awt.TextField</code> used the text of the field as the command
* string for the <code>ActionEvent</code>.
* <code>JTextField</code> will use the command
* string set with the <code>setActionCommand</code> method if not <code>null</code>,
* otherwise it will use the text of the field as a compatibility with
* <code>java.awt.TextField</code>.
* <p>
* The method <code>setEchoChar</code> and <code>getEchoChar</code>
* are not provided directly to avoid a new implementation of a
* pluggable look-and-feel inadvertently exposing password characters.
* To provide password-like services a separate class <code>JPasswordField</code>
* extends <code>JTextField</code> to provide this service with an independently
* pluggable look-and-feel.
* <p>
* The <code>java.awt.TextField</code> could be monitored for changes by adding
* a <code>TextListener</code> for <code>TextEvent</code>'s.
* In the <code>JTextComponent</code> based
* components, changes are broadcasted from the model via a
* <code>DocumentEvent</code> to <code>DocumentListeners</code>.
* The <code>DocumentEvent</code> gives
* the location of the change and the kind of change if desired.
* The code fragment might look something like:
* <pre><code>
* DocumentListener myListener = ??;
* JTextField myArea = ??;
* myArea.getDocument().addDocumentListener(myListener);
* </code></pre>
* <p>
* The horizontal alignment of <code>JTextField</code> can be set to be left
* justified, leading justified, centered, right justified or trailing justified.
* Right/trailing justification is useful if the required size
* of the field text is smaller than the size allocated to it.
* This is determined by the <code>setHorizontalAlignment</code>
* and <code>getHorizontalAlignment</code> methods. The default
* is to be leading justified.
* <p>
* How the text field consumes VK_ENTER events depends
* on whether the text field has any action listeners.
* If so, then VK_ENTER results in the listeners
* getting an ActionEvent,
* and the VK_ENTER event is consumed.
* This is compatible with how AWT text fields handle VK_ENTER events.
* If the text field has no action listeners, then as of v 1.3 the VK_ENTER
* event is not consumed. Instead, the bindings of ancestor components
* are processed, which enables the default button feature of
* JFC/Swing to work.
* <p>
* Customized fields can easily be created by extending the model and
* changing the default model provided. For example, the following piece
* of code will create a field that holds only upper case characters. It
* will work even if text is pasted into from the clipboard or it is altered via
* programmatic changes.
* <pre><code>
public class UpperCaseField extends JTextField {
public UpperCaseField(int cols) {
super(cols);
}
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return;
}
char[] upper = str.toCharArray();
for (int i = 0; i < upper.length; i++) {
upper[i] = Character.toUpperCase(upper[i]);
}
super.insertString(offs, new String(upper), a);
}
}
}
* </code></pre>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: A component which allows for the editing of a single line of text.
*
* @author Timothy Prinzing
* @see #setActionCommand
* @see JPasswordField
* @see #addActionListener
*/
public class JTextField extends JTextComponent implements SwingConstants {
/** {@collect.stats}
* Constructs a new <code>TextField</code>. A default model is created,
* the initial string is <code>null</code>,
* and the number of columns is set to 0.
*/
public JTextField() {
this(null, null, 0);
}
/** {@collect.stats}
* Constructs a new <code>TextField</code> initialized with the
* specified text. A default model is created and the number of
* columns is 0.
*
* @param text the text to be displayed, or <code>null</code>
*/
public JTextField(String text) {
this(null, text, 0);
}
/** {@collect.stats}
* Constructs a new empty <code>TextField</code> with the specified
* number of columns.
* A default model is created and the initial string is set to
* <code>null</code>.
*
* @param columns the number of columns to use to calculate
* the preferred width; if columns is set to zero, the
* preferred width will be whatever naturally results from
* the component implementation
*/
public JTextField(int columns) {
this(null, null, columns);
}
/** {@collect.stats}
* Constructs a new <code>TextField</code> initialized with the
* specified text and columns. A default model is created.
*
* @param text the text to be displayed, or <code>null</code>
* @param columns the number of columns to use to calculate
* the preferred width; if columns is set to zero, the
* preferred width will be whatever naturally results from
* the component implementation
*/
public JTextField(String text, int columns) {
this(null, text, columns);
}
/** {@collect.stats}
* Constructs a new <code>JTextField</code> that uses the given text
* storage model and the given number of columns.
* This is the constructor through which the other constructors feed.
* If the document is <code>null</code>, a default model is created.
*
* @param doc the text storage to use; if this is <code>null</code>,
* a default will be provided by calling the
* <code>createDefaultModel</code> method
* @param text the initial string to display, or <code>null</code>
* @param columns the number of columns to use to calculate
* the preferred width >= 0; if <code>columns</code>
* is set to zero, the preferred width will be whatever
* naturally results from the component implementation
* @exception IllegalArgumentException if <code>columns</code> < 0
*/
public JTextField(Document doc, String text, int columns) {
if (columns < 0) {
throw new IllegalArgumentException("columns less than zero.");
}
visibility = new DefaultBoundedRangeModel();
visibility.addChangeListener(new ScrollRepainter());
this.columns = columns;
if (doc == null) {
doc = createDefaultModel();
}
setDocument(doc);
if (text != null) {
setText(text);
}
}
/** {@collect.stats}
* Gets the class ID for a UI.
*
* @return the string "TextFieldUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Associates the editor with a text document.
* The currently registered factory is used to build a view for
* the document, which gets displayed by the editor after revalidation.
* A PropertyChange event ("document") is propagated to each listener.
*
* @param doc the document to display/edit
* @see #getDocument
* @beaninfo
* description: the text document model
* bound: true
* expert: true
*/
public void setDocument(Document doc) {
if (doc != null) {
doc.putProperty("filterNewlines", Boolean.TRUE);
}
super.setDocument(doc);
}
/** {@collect.stats}
* Calls to <code>revalidate</code> that come from within the
* textfield itself will
* be handled by validating the textfield, unless the textfield
* is contained within a <code>JViewport</code>,
* in which case this returns false.
*
* @return if the parent of this textfield is a <code>JViewPort</code>
* return false, otherwise return true
*
* @see JComponent#revalidate
* @see JComponent#isValidateRoot
*/
public boolean isValidateRoot() {
Component parent = getParent();
if (parent instanceof JViewport) {
return false;
}
return true;
}
/** {@collect.stats}
* Returns the horizontal alignment of the text.
* Valid keys are:
* <ul>
* <li><code>JTextField.LEFT</code>
* <li><code>JTextField.CENTER</code>
* <li><code>JTextField.RIGHT</code>
* <li><code>JTextField.LEADING</code>
* <li><code>JTextField.TRAILING</code>
* </ul>
*
* @return the horizontal alignment
*/
public int getHorizontalAlignment() {
return horizontalAlignment;
}
/** {@collect.stats}
* Sets the horizontal alignment of the text.
* Valid keys are:
* <ul>
* <li><code>JTextField.LEFT</code>
* <li><code>JTextField.CENTER</code>
* <li><code>JTextField.RIGHT</code>
* <li><code>JTextField.LEADING</code>
* <li><code>JTextField.TRAILING</code>
* </ul>
* <code>invalidate</code> and <code>repaint</code> are called when the
* alignment is set,
* and a <code>PropertyChange</code> event ("horizontalAlignment") is fired.
*
* @param alignment the alignment
* @exception IllegalArgumentException if <code>alignment</code>
* is not a valid key
* @beaninfo
* preferred: true
* bound: true
* description: Set the field alignment to LEFT, CENTER, RIGHT,
* LEADING (the default) or TRAILING
* enum: LEFT JTextField.LEFT CENTER JTextField.CENTER RIGHT JTextField.RIGHT
* LEADING JTextField.LEADING TRAILING JTextField.TRAILING
*/
public void setHorizontalAlignment(int alignment) {
if (alignment == horizontalAlignment) return;
int oldValue = horizontalAlignment;
if ((alignment == LEFT) || (alignment == CENTER) ||
(alignment == RIGHT)|| (alignment == LEADING) ||
(alignment == TRAILING)) {
horizontalAlignment = alignment;
} else {
throw new IllegalArgumentException("horizontalAlignment");
}
firePropertyChange("horizontalAlignment", oldValue, horizontalAlignment);
invalidate();
repaint();
}
/** {@collect.stats}
* Creates the default implementation of the model
* to be used at construction if one isn't explicitly
* given. An instance of <code>PlainDocument</code> is returned.
*
* @return the default model implementation
*/
protected Document createDefaultModel() {
return new PlainDocument();
}
/** {@collect.stats}
* Returns the number of columns in this <code>TextField</code>.
*
* @return the number of columns >= 0
*/
public int getColumns() {
return columns;
}
/** {@collect.stats}
* Sets the number of columns in this <code>TextField</code>,
* and then invalidate the layout.
*
* @param columns the number of columns >= 0
* @exception IllegalArgumentException if <code>columns</code>
* is less than 0
* @beaninfo
* description: the number of columns preferred for display
*/
public void setColumns(int columns) {
int oldVal = this.columns;
if (columns < 0) {
throw new IllegalArgumentException("columns less than zero.");
}
if (columns != oldVal) {
this.columns = columns;
invalidate();
}
}
/** {@collect.stats}
* Returns the column width.
* The meaning of what a column is can be considered a fairly weak
* notion for some fonts. This method is used to define the width
* of a column. By default this is defined to be the width of the
* character <em>m</em> for the font used. This method can be
* redefined to be some alternative amount
*
* @return the column width >= 1
*/
protected int getColumnWidth() {
if (columnWidth == 0) {
FontMetrics metrics = getFontMetrics(getFont());
columnWidth = metrics.charWidth('m');
}
return columnWidth;
}
/** {@collect.stats}
* Returns the preferred size <code>Dimensions</code> needed for this
* <code>TextField</code>. If a non-zero number of columns has been
* set, the width is set to the columns multiplied by
* the column width.
*
* @return the dimension of this textfield
*/
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
if (columns != 0) {
Insets insets = getInsets();
size.width = columns * getColumnWidth() +
insets.left + insets.right;
}
return size;
}
/** {@collect.stats}
* Sets the current font. This removes cached row height and column
* width so the new font will be reflected.
* <code>revalidate</code> is called after setting the font.
*
* @param f the new font
*/
public void setFont(Font f) {
super.setFont(f);
columnWidth = 0;
}
/** {@collect.stats}
* Adds the specified action listener to receive
* action events from this textfield.
*
* @param l the action listener to be added
*/
public synchronized void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
/** {@collect.stats}
* Removes the specified action listener so that it no longer
* receives action events from this textfield.
*
* @param l the action listener to be removed
*/
public synchronized void removeActionListener(ActionListener l) {
if ((l != null) && (getAction() == l)) {
setAction(null);
} else {
listenerList.remove(ActionListener.class, l);
}
}
/** {@collect.stats}
* Returns an array of all the <code>ActionListener</code>s added
* to this JTextField with addActionListener().
*
* @return all of the <code>ActionListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public synchronized ActionListener[] getActionListeners() {
return (ActionListener[])listenerList.getListeners(
ActionListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created.
* The listener list is processed in last to
* first order.
* @see EventListenerList
*/
protected void fireActionPerformed() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent) {
modifiers = ((InputEvent)currentEvent).getModifiers();
} else if (currentEvent instanceof ActionEvent) {
modifiers = ((ActionEvent)currentEvent).getModifiers();
}
ActionEvent e =
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
(command != null) ? command : getText(),
EventQueue.getMostRecentEventTime(), modifiers);
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ActionListener.class) {
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
}
/** {@collect.stats}
* Sets the command string used for action events.
*
* @param command the command string
*/
public void setActionCommand(String command) {
this.command = command;
}
private Action action;
private PropertyChangeListener actionPropertyChangeListener;
/** {@collect.stats}
* Sets the <code>Action</code> for the <code>ActionEvent</code> source.
* The new <code>Action</code> replaces
* any previously set <code>Action</code> but does not affect
* <code>ActionListeners</code> independently
* added with <code>addActionListener</code>.
* If the <code>Action</code> is already a registered
* <code>ActionListener</code>
* for the <code>ActionEvent</code> source, it is not re-registered.
* <p>
* Setting the <code>Action</code> results in immediately changing
* all the properties described in <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a>.
* Subsequently, the textfield's properties are automatically updated
* as the <code>Action</code>'s properties change.
* <p>
* This method uses three other methods to set
* and help track the <code>Action</code>'s property values.
* It uses the <code>configurePropertiesFromAction</code> method
* to immediately change the textfield's properties.
* To track changes in the <code>Action</code>'s property values,
* this method registers the <code>PropertyChangeListener</code>
* returned by <code>createActionPropertyChangeListener</code>. The
* default {@code PropertyChangeListener} invokes the
* {@code actionPropertyChanged} method when a property in the
* {@code Action} changes.
*
* @param a the <code>Action</code> for the <code>JTextField</code>,
* or <code>null</code>
* @since 1.3
* @see Action
* @see #getAction
* @see #configurePropertiesFromAction
* @see #createActionPropertyChangeListener
* @see #actionPropertyChanged
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: the Action instance connected with this ActionEvent source
*/
public void setAction(Action a) {
Action oldValue = getAction();
if (action==null || !action.equals(a)) {
action = a;
if (oldValue!=null) {
removeActionListener(oldValue);
oldValue.removePropertyChangeListener(actionPropertyChangeListener);
actionPropertyChangeListener = null;
}
configurePropertiesFromAction(action);
if (action!=null) {
// Don't add if it is already a listener
if (!isListener(ActionListener.class, action)) {
addActionListener(action);
}
// Reverse linkage:
actionPropertyChangeListener = createActionPropertyChangeListener(action);
action.addPropertyChangeListener(actionPropertyChangeListener);
}
firePropertyChange("action", oldValue, action);
}
}
private boolean isListener(Class c, ActionListener a) {
boolean isListener = false;
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==c && listeners[i+1]==a) {
isListener=true;
}
}
return isListener;
}
/** {@collect.stats}
* Returns the currently set <code>Action</code> for this
* <code>ActionEvent</code> source, or <code>null</code>
* if no <code>Action</code> is set.
*
* @return the <code>Action</code> for this <code>ActionEvent</code> source,
* or <code>null</code>
* @since 1.3
* @see Action
* @see #setAction
*/
public Action getAction() {
return action;
}
/** {@collect.stats}
* Sets the properties on this textfield to match those in the specified
* <code>Action</code>. Refer to <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for more
* details as to which properties this sets.
*
* @param a the <code>Action</code> from which to get the properties,
* or <code>null</code>
* @since 1.3
* @see Action
* @see #setAction
*/
protected void configurePropertiesFromAction(Action a) {
AbstractAction.setEnabledFromAction(this, a);
AbstractAction.setToolTipTextFromAction(this, a);
setActionCommandFromAction(a);
}
/** {@collect.stats}
* Updates the textfield's state in response to property changes in
* associated action. This method is invoked from the
* {@code PropertyChangeListener} returned from
* {@code createActionPropertyChangeListener}. Subclasses do not normally
* need to invoke this. Subclasses that support additional {@code Action}
* properties should override this and
* {@code configurePropertiesFromAction}.
* <p>
* Refer to the table at <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for a list of
* the properties this method sets.
*
* @param action the <code>Action</code> associated with this textfield
* @param propertyName the name of the property that changed
* @since 1.6
* @see Action
* @see #configurePropertiesFromAction
*/
protected void actionPropertyChanged(Action action, String propertyName) {
if (propertyName == Action.ACTION_COMMAND_KEY) {
setActionCommandFromAction(action);
} else if (propertyName == "enabled") {
AbstractAction.setEnabledFromAction(this, action);
} else if (propertyName == Action.SHORT_DESCRIPTION) {
AbstractAction.setToolTipTextFromAction(this, action);
}
}
private void setActionCommandFromAction(Action action) {
setActionCommand((action == null) ? null :
(String)action.getValue(Action.ACTION_COMMAND_KEY));
}
/** {@collect.stats}
* Creates and returns a <code>PropertyChangeListener</code> that is
* responsible for listening for changes from the specified
* <code>Action</code> and updating the appropriate properties.
* <p>
* <b>Warning:</b> If you subclass this do not create an anonymous
* inner class. If you do the lifetime of the textfield will be tied to
* that of the <code>Action</code>.
*
* @param a the textfield's action
* @since 1.3
* @see Action
* @see #setAction
*/
protected PropertyChangeListener createActionPropertyChangeListener(Action a) {
return new TextFieldActionPropertyChangeListener(this, a);
}
private static class TextFieldActionPropertyChangeListener extends
ActionPropertyChangeListener<JTextField> {
TextFieldActionPropertyChangeListener(JTextField tf, Action a) {
super(tf, a);
}
protected void actionPropertyChanged(JTextField textField,
Action action,
PropertyChangeEvent e) {
if (AbstractAction.shouldReconfigure(e)) {
textField.configurePropertiesFromAction(action);
} else {
textField.actionPropertyChanged(action, e.getPropertyName());
}
}
}
/** {@collect.stats}
* Fetches the command list for the editor. This is
* the list of commands supported by the plugged-in UI
* augmented by the collection of commands that the
* editor itself supports. These are useful for binding
* to events, such as in a keymap.
*
* @return the command list
*/
public Action[] getActions() {
return TextAction.augmentList(super.getActions(), defaultActions);
}
/** {@collect.stats}
* Processes action events occurring on this textfield by
* dispatching them to any registered <code>ActionListener</code> objects.
* This is normally called by the controller registered with
* textfield.
*/
public void postActionEvent() {
fireActionPerformed();
}
// --- Scrolling support -----------------------------------
/** {@collect.stats}
* Gets the visibility of the text field. This can
* be adjusted to change the location of the visible
* area if the size of the field is greater than
* the area that was allocated to the field.
*
* <p>
* The fields look-and-feel implementation manages
* the values of the minimum, maximum, and extent
* properties on the <code>BoundedRangeModel</code>.
*
* @return the visibility
* @see BoundedRangeModel
*/
public BoundedRangeModel getHorizontalVisibility() {
return visibility;
}
/** {@collect.stats}
* Gets the scroll offset, in pixels.
*
* @return the offset >= 0
*/
public int getScrollOffset() {
return visibility.getValue();
}
/** {@collect.stats}
* Sets the scroll offset, in pixels.
*
* @param scrollOffset the offset >= 0
*/
public void setScrollOffset(int scrollOffset) {
visibility.setValue(scrollOffset);
}
/** {@collect.stats}
* Scrolls the field left or right.
*
* @param r the region to scroll
*/
public void scrollRectToVisible(Rectangle r) {
// convert to coordinate system of the bounded range
Insets i = getInsets();
int x0 = r.x + visibility.getValue() - i.left;
int x1 = x0 + r.width;
if (x0 < visibility.getValue()) {
// Scroll to the left
visibility.setValue(x0);
} else if(x1 > visibility.getValue() + visibility.getExtent()) {
// Scroll to the right
visibility.setValue(x1 - visibility.getExtent());
}
}
/** {@collect.stats}
* Returns true if the receiver has an <code>ActionListener</code>
* installed.
*/
boolean hasActionListener() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ActionListener.class) {
return true;
}
}
return false;
}
// --- variables -------------------------------------------
/** {@collect.stats}
* Name of the action to send notification that the
* contents of the field have been accepted. Typically
* this is bound to a carriage-return.
*/
public static final String notifyAction = "notify-field-accept";
private BoundedRangeModel visibility;
private int horizontalAlignment = LEADING;
private int columns;
private int columnWidth;
private String command;
private static final Action[] defaultActions = {
new NotifyAction()
};
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "TextFieldUI";
// --- Action implementations -----------------------------------
// Note that JFormattedTextField.CommitAction extends this
static class NotifyAction extends TextAction {
NotifyAction() {
super(notifyAction);
}
public void actionPerformed(ActionEvent e) {
JTextComponent target = getFocusedComponent();
if (target instanceof JTextField) {
JTextField field = (JTextField) target;
field.postActionEvent();
}
}
public boolean isEnabled() {
JTextComponent target = getFocusedComponent();
if (target instanceof JTextField) {
return ((JTextField)target).hasActionListener();
}
return false;
}
}
class ScrollRepainter implements ChangeListener, Serializable {
public void stateChanged(ChangeEvent e) {
repaint();
}
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JTextField</code>.
* This method is intended to be used only for debugging purposes,
* and the content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JTextField</code>
*/
protected String paramString() {
String horizontalAlignmentString;
if (horizontalAlignment == LEFT) {
horizontalAlignmentString = "LEFT";
} else if (horizontalAlignment == CENTER) {
horizontalAlignmentString = "CENTER";
} else if (horizontalAlignment == RIGHT) {
horizontalAlignmentString = "RIGHT";
} else if (horizontalAlignment == LEADING) {
horizontalAlignmentString = "LEADING";
} else if (horizontalAlignment == TRAILING) {
horizontalAlignmentString = "TRAILING";
} else horizontalAlignmentString = "";
String commandString = (command != null ?
command : "");
return super.paramString() +
",columns=" + columns +
",columnWidth=" + columnWidth +
",command=" + commandString +
",horizontalAlignment=" + horizontalAlignmentString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with this
* <code>JTextField</code>. For <code>JTextFields</code>,
* the <code>AccessibleContext</code> takes the form of an
* <code>AccessibleJTextField</code>.
* A new <code>AccessibleJTextField</code> instance is created
* if necessary.
*
* @return an <code>AccessibleJTextField</code> that serves as the
* <code>AccessibleContext</code> of this <code>JTextField</code>
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJTextField();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JTextField</code> class. It provides an implementation of the
* Java Accessibility API appropriate to text field user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJTextField extends AccessibleJTextComponent {
/** {@collect.stats}
* Gets the state set of this object.
*
* @return an instance of AccessibleStateSet describing the states
* of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
states.add(AccessibleState.SINGLE_LINE);
return states;
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.plaf.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.text.html.*;
import javax.accessibility.*;
/** {@collect.stats}
* A text component to edit various kinds of content.
* You can find how-to information and examples of using editor panes in
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/text.html">Using Text Components</a>,
* a section in <em>The Java Tutorial.</em>
*
* <p>
* This component uses implementations of the
* <code>EditorKit</code> to accomplish its behavior. It effectively
* morphs into the proper kind of text editor for the kind
* of content it is given. The content type that editor is bound
* to at any given time is determined by the <code>EditorKit</code> currently
* installed. If the content is set to a new URL, its type is used
* to determine the <code>EditorKit</code> that should be used to
* load the content.
* <p>
* By default, the following types of content are known:
* <dl>
* <dt><b>text/plain</b>
* <dd>Plain text, which is the default the type given isn't
* recognized. The kit used in this case is an extension of
* <code>DefaultEditorKit</code> that produces a wrapped plain text view.
* <dt><b>text/html</b>
* <dd>HTML text. The kit used in this case is the class
* <code>javax.swing.text.html.HTMLEditorKit</code>
* which provides HTML 3.2 support.
* <dt><b>text/rtf</b>
* <dd>RTF text. The kit used in this case is the class
* <code>javax.swing.text.rtf.RTFEditorKit</code>
* which provides a limited support of the Rich Text Format.
* </dl>
* <p>
* There are several ways to load content into this component.
* <ol>
* <li>
* The {@link #setText setText} method can be used to initialize
* the component from a string. In this case the current
* <code>EditorKit</code> will be used, and the content type will be
* expected to be of this type.
* <li>
* The {@link #read read} method can be used to initialize the
* component from a <code>Reader</code>. Note that if the content type is HTML,
* relative references (e.g. for things like images) can't be resolved
* unless the <base> tag is used or the <em>Base</em> property
* on <code>HTMLDocument</code> is set.
* In this case the current <code>EditorKit</code> will be used,
* and the content type will be expected to be of this type.
* <li>
* The {@link #setPage setPage} method can be used to initialize
* the component from a URL. In this case, the content type will be
* determined from the URL, and the registered <code>EditorKit</code>
* for that content type will be set.
* </ol>
* <p>
* Some kinds of content may provide hyperlink support by generating
* hyperlink events. The HTML <code>EditorKit</code> will generate
* hyperlink events if the <code>JEditorPane</code> is <em>not editable</em>
* (<code>JEditorPane.setEditable(false);</code> has been called).
* If HTML frames are embedded in the document, the typical response would be
* to change a portion of the current document. The following code
* fragment is a possible hyperlink listener implementation, that treats
* HTML frame events specially, and simply displays any other activated
* hyperlinks.
* <code><pre>
class Hyperactive implements HyperlinkListener {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
JEditorPane pane = (JEditorPane) e.getSource();
if (e instanceof HTMLFrameHyperlinkEvent) {
HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e;
HTMLDocument doc = (HTMLDocument)pane.getDocument();
doc.processHTMLFrameHyperlinkEvent(evt);
} else {
try {
pane.setPage(e.getURL());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
}
* </pre></code>
* <p>
* For information on customizing how <b>text/html</b> is rendered please see
* {@link #W3C_LENGTH_UNITS} and {@link #HONOR_DISPLAY_PROPERTIES}
* <p>
* Culturally dependent information in some documents is handled through
* a mechanism called character encoding. Character encoding is an
* unambiguous mapping of the members of a character set (letters, ideographs,
* digits, symbols, or control functions) to specific numeric code values. It
* represents the way the file is stored. Example character encodings are
* ISO-8859-1, ISO-8859-5, Shift-jis, Euc-jp, and UTF-8. When the file is
* passed to an user agent (<code>JEditorPane</code>) it is converted to
* the document character set (ISO-10646 aka Unicode).
* <p>
* There are multiple ways to get a character set mapping to happen
* with <code>JEditorPane</code>.
* <ol>
* <li>
* One way is to specify the character set as a parameter of the MIME
* type. This will be established by a call to the
* <a href="#setContentType">setContentType</a> method. If the content
* is loaded by the <a href="#setPage">setPage</a> method the content
* type will have been set according to the specification of the URL.
* It the file is loaded directly, the content type would be expected to
* have been set prior to loading.
* <li>
* Another way the character set can be specified is in the document itself.
* This requires reading the document prior to determining the character set
* that is desired. To handle this, it is expected that the
* <code>EditorKit</code>.read operation throw a
* <code>ChangedCharSetException</code> which will
* be caught. The read is then restarted with a new Reader that uses
* the character set specified in the <code>ChangedCharSetException</code>
* (which is an <code>IOException</code>).
* </ol>
* <p>
* <dl>
* <dt><b><font size=+1>Newlines</font></b>
* <dd>
* For a discussion on how newlines are handled, see
* <a href="text/DefaultEditorKit.html">DefaultEditorKit</a>.
* </dl>
*
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: A text component to edit various types of content.
*
* @author Timothy Prinzing
*/
public class JEditorPane extends JTextComponent {
/** {@collect.stats}
* Creates a new <code>JEditorPane</code>.
* The document model is set to <code>null</code>.
*/
public JEditorPane() {
super();
setFocusCycleRoot(true);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() {
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
if (focusCycleRoot != JEditorPane.this ||
(!isEditable() && getComponentCount() > 0)) {
return super.getComponentAfter(focusCycleRoot,
aComponent);
} else {
Container rootAncestor = getFocusCycleRootAncestor();
return (rootAncestor != null)
? rootAncestor.getFocusTraversalPolicy().
getComponentAfter(rootAncestor,
JEditorPane.this)
: null;
}
}
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
if (focusCycleRoot != JEditorPane.this ||
(!isEditable() && getComponentCount() > 0)) {
return super.getComponentBefore(focusCycleRoot,
aComponent);
} else {
Container rootAncestor = getFocusCycleRootAncestor();
return (rootAncestor != null)
? rootAncestor.getFocusTraversalPolicy().
getComponentBefore(rootAncestor,
JEditorPane.this)
: null;
}
}
public Component getDefaultComponent(Container focusCycleRoot)
{
return (focusCycleRoot != JEditorPane.this ||
(!isEditable() && getComponentCount() > 0))
? super.getDefaultComponent(focusCycleRoot)
: null;
}
protected boolean accept(Component aComponent) {
return (aComponent != JEditorPane.this)
? super.accept(aComponent)
: false;
}
});
LookAndFeel.installProperty(this,
"focusTraversalKeysForward",
JComponent.
getManagingFocusForwardTraversalKeys());
LookAndFeel.installProperty(this,
"focusTraversalKeysBackward",
JComponent.
getManagingFocusBackwardTraversalKeys());
}
/** {@collect.stats}
* Creates a <code>JEditorPane</code> based on a specified URL for input.
*
* @param initialPage the URL
* @exception IOException if the URL is <code>null</code>
* or cannot be accessed
*/
public JEditorPane(URL initialPage) throws IOException {
this();
setPage(initialPage);
}
/** {@collect.stats}
* Creates a <code>JEditorPane</code> based on a string containing
* a URL specification.
*
* @param url the URL
* @exception IOException if the URL is <code>null</code> or
* cannot be accessed
*/
public JEditorPane(String url) throws IOException {
this();
setPage(url);
}
/** {@collect.stats}
* Creates a <code>JEditorPane</code> that has been initialized
* to the given text. This is a convenience constructor that calls the
* <code>setContentType</code> and <code>setText</code> methods.
*
* @param type mime type of the given text
* @param text the text to initialize with; may be <code>null</code>
* @exception NullPointerException if the <code>type</code> parameter
* is <code>null</code>
*/
public JEditorPane(String type, String text) {
this();
setContentType(type);
setText(text);
}
/** {@collect.stats}
* Adds a hyperlink listener for notification of any changes, for example
* when a link is selected and entered.
*
* @param listener the listener
*/
public synchronized void addHyperlinkListener(HyperlinkListener listener) {
listenerList.add(HyperlinkListener.class, listener);
}
/** {@collect.stats}
* Removes a hyperlink listener.
*
* @param listener the listener
*/
public synchronized void removeHyperlinkListener(HyperlinkListener listener) {
listenerList.remove(HyperlinkListener.class, listener);
}
/** {@collect.stats}
* Returns an array of all the <code>HyperLinkListener</code>s added
* to this JEditorPane with addHyperlinkListener().
*
* @return all of the <code>HyperLinkListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public synchronized HyperlinkListener[] getHyperlinkListeners() {
return (HyperlinkListener[])listenerList.getListeners(
HyperlinkListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. This is normally called
* by the currently installed <code>EditorKit</code> if a content type
* that supports hyperlinks is currently active and there
* was activity with a link. The listener list is processed
* last to first.
*
* @param e the event
* @see EventListenerList
*/
public void fireHyperlinkUpdate(HyperlinkEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==HyperlinkListener.class) {
((HyperlinkListener)listeners[i+1]).hyperlinkUpdate(e);
}
}
}
/** {@collect.stats}
* Sets the current URL being displayed. The content type of the
* pane is set, and if the editor kit for the pane is
* non-<code>null</code>, then
* a new default document is created and the URL is read into it.
* If the URL contains and reference location, the location will
* be scrolled to by calling the <code>scrollToReference</code>
* method. If the desired URL is the one currently being displayed,
* the document will not be reloaded. To force a document
* reload it is necessary to clear the stream description property
* of the document. The following code shows how this can be done:
*
* <pre>
* Document doc = jEditorPane.getDocument();
* doc.putProperty(Document.StreamDescriptionProperty, null);
* </pre>
*
* If the desired URL is not the one currently being
* displayed, the <code>getStream</code> method is called to
* give subclasses control over the stream provided.
* <p>
* This may load either synchronously or asynchronously
* depending upon the document returned by the <code>EditorKit</code>.
* If the <code>Document</code> is of type
* <code>AbstractDocument</code> and has a value returned by
* <code>AbstractDocument.getAsynchronousLoadPriority</code>
* that is greater than or equal to zero, the page will be
* loaded on a separate thread using that priority.
* <p>
* If the document is loaded synchronously, it will be
* filled in with the stream prior to being installed into
* the editor with a call to <code>setDocument</code>, which
* is bound and will fire a property change event. If an
* <code>IOException</code> is thrown the partially loaded
* document will
* be discarded and neither the document or page property
* change events will be fired. If the document is
* successfully loaded and installed, a view will be
* built for it by the UI which will then be scrolled if
* necessary, and then the page property change event
* will be fired.
* <p>
* If the document is loaded asynchronously, the document
* will be installed into the editor immediately using a
* call to <code>setDocument</code> which will fire a
* document property change event, then a thread will be
* created which will begin doing the actual loading.
* In this case, the page property change event will not be
* fired by the call to this method directly, but rather will be
* fired when the thread doing the loading has finished.
* It will also be fired on the event-dispatch thread.
* Since the calling thread can not throw an <code>IOException</code>
* in the event of failure on the other thread, the page
* property change event will be fired when the other
* thread is done whether the load was successful or not.
*
* @param page the URL of the page
* @exception IOException for a <code>null</code> or invalid
* page specification, or exception from the stream being read
* @see #getPage
* @beaninfo
* description: the URL used to set content
* bound: true
* expert: true
*/
public void setPage(URL page) throws IOException {
if (page == null) {
throw new IOException("invalid url");
}
URL loaded = getPage();
// reset scrollbar
if (!page.equals(loaded) && page.getRef() == null) {
scrollRectToVisible(new Rectangle(0,0,1,1));
}
boolean reloaded = false;
Object postData = getPostData();
if ((loaded == null) || !loaded.sameFile(page) || (postData != null)) {
// different url or POST method, load the new content
int p = getAsynchronousLoadPriority(getDocument());
if ((postData == null) || (p < 0)) {
// Either we do not have POST data, or should submit the data
// synchronously.
InputStream in = getStream(page);
if (kit != null) {
Document doc = initializeModel(kit, page);
// At this point, one could either load up the model with no
// view notifications slowing it down (i.e. best synchronous
// behavior) or set the model and start to feed it on a separate
// thread (best asynchronous behavior).
synchronized(this) {
if (loading != null) {
// we are loading asynchronously, so we need to cancel
// the old stream.
loading.cancel();
loading = null;
}
}
p = getAsynchronousLoadPriority(doc);
if (p >= 0) {
// load asynchronously
setDocument(doc);
synchronized(this) {
loading = new PageStream(in);
Thread pl = new PageLoader(doc, loading, p, loaded, page);
pl.start();
}
return;
}
read(in, doc);
setDocument(doc);
reloaded = true;
}
} else {
// We have POST data and should send it asynchronously.
// Send (and subsequentally read) data in separate thread.
// Model initialization is deferred to that thread, too.
Thread pl = new PageLoader(null, null, p, loaded, page);
pl.start();
return;
}
}
final String reference = page.getRef();
if (reference != null) {
if (!reloaded) {
scrollToReference(reference);
}
else {
// Have to scroll after painted.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollToReference(reference);
}
});
}
getDocument().putProperty(Document.StreamDescriptionProperty, page);
}
firePropertyChange("page", loaded, page);
}
/** {@collect.stats}
* Create model and initialize document properties from page properties.
*/
private Document initializeModel(EditorKit kit, URL page) {
Document doc = kit.createDefaultDocument();
if (pageProperties != null) {
// transfer properties discovered in stream to the
// document property collection.
for (Enumeration e = pageProperties.keys(); e.hasMoreElements() ;) {
Object key = e.nextElement();
doc.putProperty(key, pageProperties.get(key));
}
pageProperties.clear();
}
if (doc.getProperty(Document.StreamDescriptionProperty) == null) {
doc.putProperty(Document.StreamDescriptionProperty, page);
}
return doc;
}
/** {@collect.stats}
* Return load priority for the document or -1 if priority not supported.
*/
private int getAsynchronousLoadPriority(Document doc) {
return (doc instanceof AbstractDocument ?
((AbstractDocument) doc).getAsynchronousLoadPriority() : -1);
}
/** {@collect.stats}
* This method initializes from a stream. If the kit is
* set to be of type <code>HTMLEditorKit</code>, and the
* <code>desc</code> parameter is an <code>HTMLDocument</code>,
* then it invokes the <code>HTMLEditorKit</code> to initiate
* the read. Otherwise it calls the superclass
* method which loads the model as plain text.
*
* @param in the stream from which to read
* @param desc an object describing the stream
* @exception IOException as thrown by the stream being
* used to initialize
* @see JTextComponent#read
* @see #setDocument
*/
public void read(InputStream in, Object desc) throws IOException {
if (desc instanceof HTMLDocument &&
kit instanceof HTMLEditorKit) {
HTMLDocument hdoc = (HTMLDocument) desc;
setDocument(hdoc);
read(in, hdoc);
} else {
String charset = (String) getClientProperty("charset");
Reader r = (charset != null) ? new InputStreamReader(in, charset) :
new InputStreamReader(in);
super.read(r, desc);
}
}
/** {@collect.stats}
* This method invokes the <code>EditorKit</code> to initiate a
* read. In the case where a <code>ChangedCharSetException</code>
* is thrown this exception will contain the new CharSet.
* Therefore the <code>read</code> operation
* is then restarted after building a new Reader with the new charset.
*
* @param in the inputstream to use
* @param doc the document to load
*
*/
void read(InputStream in, Document doc) throws IOException {
if (! Boolean.TRUE.equals(doc.getProperty("IgnoreCharsetDirective"))) {
final int READ_LIMIT = 1024 * 10;
in = new BufferedInputStream(in, READ_LIMIT);
in.mark(READ_LIMIT);
}
try {
String charset = (String) getClientProperty("charset");
Reader r = (charset != null) ? new InputStreamReader(in, charset) :
new InputStreamReader(in);
kit.read(r, doc, 0);
} catch (BadLocationException e) {
throw new IOException(e.getMessage());
} catch (ChangedCharSetException changedCharSetException) {
String charSetSpec = changedCharSetException.getCharSetSpec();
if (changedCharSetException.keyEqualsCharSet()) {
putClientProperty("charset", charSetSpec);
} else {
setCharsetFromContentTypeParameters(charSetSpec);
}
try {
in.reset();
} catch (IOException exception) {
//mark was invalidated
in.close();
URL url = (URL)doc.getProperty(Document.StreamDescriptionProperty);
if (url != null) {
URLConnection conn = url.openConnection();
in = conn.getInputStream();
} else {
//there is nothing we can do to recover stream
throw changedCharSetException;
}
}
try {
doc.remove(0, doc.getLength());
} catch (BadLocationException e) {}
doc.putProperty("IgnoreCharsetDirective", Boolean.valueOf(true));
read(in, doc);
}
}
/** {@collect.stats}
* Thread to load a stream into the text document model.
*/
class PageLoader extends Thread {
/** {@collect.stats}
* Construct an asynchronous page loader.
*/
PageLoader(Document doc, InputStream in, int priority, URL old,
URL page) {
setPriority(priority);
this.in = in;
this.old = old;
this.page = page;
this.doc = doc;
}
boolean pageLoaded = false;
/** {@collect.stats}
* Try to load the document, then scroll the view
* to the reference (if specified). When done, fire
* a page property change event.
*/
public void run() {
try {
if (in == null) {
in = getStream(page);
if (kit == null) {
// We received document of unknown content type.
UIManager.getLookAndFeel().provideErrorFeedback(
JEditorPane.this);
return;
}
// Access to <code>loading</code> should be synchronized.
synchronized(JEditorPane.this) {
in = loading = new PageStream(in);
}
}
if (doc == null) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
doc = initializeModel(kit, page);
setDocument(doc);
}
});
} catch (InvocationTargetException ex) {
UIManager.getLookAndFeel().provideErrorFeedback(
JEditorPane.this);
return;
} catch (InterruptedException ex) {
UIManager.getLookAndFeel().provideErrorFeedback(
JEditorPane.this);
return;
}
}
read(in, doc);
URL page = (URL) doc.getProperty(Document.StreamDescriptionProperty);
String reference = page.getRef();
if (reference != null) {
// scroll the page if necessary, but do it on the
// event thread... that is the only guarantee that
// modelToView can be safely called.
Runnable callScrollToReference = new Runnable() {
public void run() {
URL u = (URL) getDocument().getProperty
(Document.StreamDescriptionProperty);
String ref = u.getRef();
scrollToReference(ref);
}
};
SwingUtilities.invokeLater(callScrollToReference);
}
pageLoaded = true;
} catch (IOException ioe) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
} finally {
synchronized(JEditorPane.this) {
loading = null;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (pageLoaded) {
firePropertyChange("page", old, page);
}
}
});
}
}
/** {@collect.stats}
* The stream to load the document with
*/
InputStream in;
/** {@collect.stats}
* URL of the old page that was replaced (for the property change event)
*/
URL old;
/** {@collect.stats}
* URL of the page being loaded (for the property change event)
*/
URL page;
/** {@collect.stats}
* The Document instance to load into. This is cached in case a
* new Document is created between the time the thread this is created
* and run.
*/
Document doc;
}
static class PageStream extends FilterInputStream {
boolean canceled;
public PageStream(InputStream i) {
super(i);
canceled = false;
}
/** {@collect.stats}
* Cancel the loading of the stream by throwing
* an IOException on the next request.
*/
public synchronized void cancel() {
canceled = true;
}
protected synchronized void checkCanceled() throws IOException {
if (canceled) {
throw new IOException("page canceled");
}
}
public int read() throws IOException {
checkCanceled();
return super.read();
}
public long skip(long n) throws IOException {
checkCanceled();
return super.skip(n);
}
public int available() throws IOException {
checkCanceled();
return super.available();
}
public void reset() throws IOException {
checkCanceled();
super.reset();
}
}
/** {@collect.stats}
* Fetches a stream for the given URL, which is about to
* be loaded by the <code>setPage</code> method. By
* default, this simply opens the URL and returns the
* stream. This can be reimplemented to do useful things
* like fetch the stream from a cache, monitor the progress
* of the stream, etc.
* <p>
* This method is expected to have the the side effect of
* establishing the content type, and therefore setting the
* appropriate <code>EditorKit</code> to use for loading the stream.
* <p>
* If this the stream was an http connection, redirects
* will be followed and the resulting URL will be set as
* the <code>Document.StreamDescriptionProperty</code> so that relative
* URL's can be properly resolved.
*
* @param page the URL of the page
*/
protected InputStream getStream(URL page) throws IOException {
final URLConnection conn = page.openConnection();
if (conn instanceof HttpURLConnection) {
HttpURLConnection hconn = (HttpURLConnection) conn;
hconn.setInstanceFollowRedirects(false);
Object postData = getPostData();
if (postData != null) {
handlePostData(hconn, postData);
}
int response = hconn.getResponseCode();
boolean redirect = (response >= 300 && response <= 399);
/*
* In the case of a redirect, we want to actually change the URL
* that was input to the new, redirected URL
*/
if (redirect) {
String loc = conn.getHeaderField("Location");
if (loc.startsWith("http", 0)) {
page = new URL(loc);
} else {
page = new URL(page, loc);
}
return getStream(page);
}
}
// Connection properties handler should be forced to run on EDT,
// as it instantiates the EditorKit.
if (SwingUtilities.isEventDispatchThread()) {
handleConnectionProperties(conn);
} else {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
handleConnectionProperties(conn);
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
return conn.getInputStream();
}
/** {@collect.stats}
* Handle URL connection properties (most notably, content type).
*/
private void handleConnectionProperties(URLConnection conn) {
if (pageProperties == null) {
pageProperties = new Hashtable();
}
String type = conn.getContentType();
if (type != null) {
setContentType(type);
pageProperties.put("content-type", type);
}
pageProperties.put(Document.StreamDescriptionProperty, conn.getURL());
String enc = conn.getContentEncoding();
if (enc != null) {
pageProperties.put("content-encoding", enc);
}
}
private Object getPostData() {
return getDocument().getProperty(PostDataProperty);
}
private void handlePostData(HttpURLConnection conn, Object postData)
throws IOException {
conn.setDoOutput(true);
DataOutputStream os = null;
try {
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
os = new DataOutputStream(conn.getOutputStream());
os.writeBytes((String) postData);
} finally {
if (os != null) {
os.close();
}
}
}
/** {@collect.stats}
* Scrolls the view to the given reference location
* (that is, the value returned by the <code>UL.getRef</code>
* method for the URL being displayed). By default, this
* method only knows how to locate a reference in an
* HTMLDocument. The implementation calls the
* <code>scrollRectToVisible</code> method to
* accomplish the actual scrolling. If scrolling to a
* reference location is needed for document types other
* than HTML, this method should be reimplemented.
* This method will have no effect if the component
* is not visible.
*
* @param reference the named location to scroll to
*/
public void scrollToReference(String reference) {
Document d = getDocument();
if (d instanceof HTMLDocument) {
HTMLDocument doc = (HTMLDocument) d;
HTMLDocument.Iterator iter = doc.getIterator(HTML.Tag.A);
for (; iter.isValid(); iter.next()) {
AttributeSet a = iter.getAttributes();
String nm = (String) a.getAttribute(HTML.Attribute.NAME);
if ((nm != null) && nm.equals(reference)) {
// found a matching reference in the document.
try {
int pos = iter.getStartOffset();
Rectangle r = modelToView(pos);
if (r != null) {
// the view is visible, scroll it to the
// center of the current visible area.
Rectangle vis = getVisibleRect();
//r.y -= (vis.height / 2);
r.height = vis.height;
scrollRectToVisible(r);
setCaretPosition(pos);
}
} catch (BadLocationException ble) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
}
}
}
}
}
/** {@collect.stats}
* Gets the current URL being displayed. If a URL was
* not specified in the creation of the document, this
* will return <code>null</code>, and relative URL's will not be
* resolved.
*
* @return the URL, or <code>null</code> if none
*/
public URL getPage() {
return (URL) getDocument().getProperty(Document.StreamDescriptionProperty);
}
/** {@collect.stats}
* Sets the current URL being displayed.
*
* @param url the URL for display
* @exception IOException for a <code>null</code> or invalid URL
* specification
*/
public void setPage(String url) throws IOException {
if (url == null) {
throw new IOException("invalid url");
}
URL page = new URL(url);
setPage(page);
}
/** {@collect.stats}
* Gets the class ID for the UI.
*
* @return the string "EditorPaneUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Creates the default editor kit (<code>PlainEditorKit</code>) for when
* the component is first created.
*
* @return the editor kit
*/
protected EditorKit createDefaultEditorKit() {
return new PlainEditorKit();
}
/** {@collect.stats}
* Fetches the currently installed kit for handling content.
* <code>createDefaultEditorKit</code> is called to set up a default
* if necessary.
*
* @return the editor kit
*/
public EditorKit getEditorKit() {
if (kit == null) {
kit = createDefaultEditorKit();
isUserSetEditorKit = false;
}
return kit;
}
/** {@collect.stats}
* Gets the type of content that this editor
* is currently set to deal with. This is
* defined to be the type associated with the
* currently installed <code>EditorKit</code>.
*
* @return the content type, <code>null</code> if no editor kit set
*/
public final String getContentType() {
return (kit != null) ? kit.getContentType() : null;
}
/** {@collect.stats}
* Sets the type of content that this editor
* handles. This calls <code>getEditorKitForContentType</code>,
* and then <code>setEditorKit</code> if an editor kit can
* be successfully located. This is mostly convenience method
* that can be used as an alternative to calling
* <code>setEditorKit</code> directly.
* <p>
* If there is a charset definition specified as a parameter
* of the content type specification, it will be used when
* loading input streams using the associated <code>EditorKit</code>.
* For example if the type is specified as
* <code>text/html; charset=EUC-JP</code> the content
* will be loaded using the <code>EditorKit</code> registered for
* <code>text/html</code> and the Reader provided to
* the <code>EditorKit</code> to load unicode into the document will
* use the <code>EUC-JP</code> charset for translating
* to unicode. If the type is not recognized, the content
* will be loaded using the <code>EditorKit</code> registered
* for plain text, <code>text/plain</code>.
*
* @param type the non-<code>null</code> mime type for the content editing
* support
* @see #getContentType
* @beaninfo
* description: the type of content
* @throws NullPointerException if the <code>type</code> parameter
* is <code>null</code>
*/
public final void setContentType(String type) {
// The type could have optional info is part of it,
// for example some charset info. We need to strip that
// of and save it.
int parm = type.indexOf(";");
if (parm > -1) {
// Save the paramList.
String paramList = type.substring(parm);
// update the content type string.
type = type.substring(0, parm).trim();
if (type.toLowerCase().startsWith("text/")) {
setCharsetFromContentTypeParameters(paramList);
}
}
if ((kit == null) || (! type.equals(kit.getContentType()))
|| !isUserSetEditorKit) {
EditorKit k = getEditorKitForContentType(type);
if (k != null && k != kit) {
setEditorKit(k);
isUserSetEditorKit = false;
}
}
}
/** {@collect.stats}
* This method gets the charset information specified as part
* of the content type in the http header information.
*/
private void setCharsetFromContentTypeParameters(String paramlist) {
String charset = null;
try {
// paramlist is handed to us with a leading ';', strip it.
int semi = paramlist.indexOf(';');
if (semi > -1 && semi < paramlist.length()-1) {
paramlist = paramlist.substring(semi + 1);
}
if (paramlist.length() > 0) {
// parse the paramlist into attr-value pairs & get the
// charset pair's value
HeaderParser hdrParser = new HeaderParser(paramlist);
charset = hdrParser.findValue("charset");
if (charset != null) {
putClientProperty("charset", charset);
}
}
}
catch (IndexOutOfBoundsException e) {
// malformed parameter list, use charset we have
}
catch (NullPointerException e) {
// malformed parameter list, use charset we have
}
catch (Exception e) {
// malformed parameter list, use charset we have; but complain
System.err.println("JEditorPane.getCharsetFromContentTypeParameters failed on: " + paramlist);
e.printStackTrace();
}
}
/** {@collect.stats}
* Sets the currently installed kit for handling
* content. This is the bound property that
* establishes the content type of the editor.
* Any old kit is first deinstalled, then if kit is
* non-<code>null</code>,
* the new kit is installed, and a default document created for it.
* A <code>PropertyChange</code> event ("editorKit") is always fired when
* <code>setEditorKit</code> is called.
* <p>
* <em>NOTE: This has the side effect of changing the model,
* because the <code>EditorKit</code> is the source of how a
* particular type
* of content is modeled. This method will cause <code>setDocument</code>
* to be called on behalf of the caller to ensure integrity
* of the internal state.</em>
*
* @param kit the desired editor behavior
* @see #getEditorKit
* @beaninfo
* description: the currently installed kit for handling content
* bound: true
* expert: true
*/
public void setEditorKit(EditorKit kit) {
EditorKit old = this.kit;
isUserSetEditorKit = true;
if (old != null) {
old.deinstall(this);
}
this.kit = kit;
if (this.kit != null) {
this.kit.install(this);
setDocument(this.kit.createDefaultDocument());
}
firePropertyChange("editorKit", old, kit);
}
/** {@collect.stats}
* Fetches the editor kit to use for the given type
* of content. This is called when a type is requested
* that doesn't match the currently installed type.
* If the component doesn't have an <code>EditorKit</code> registered
* for the given type, it will try to create an
* <code>EditorKit</code> from the default <code>EditorKit</code> registry.
* If that fails, a <code>PlainEditorKit</code> is used on the
* assumption that all text documents can be represented
* as plain text.
* <p>
* This method can be reimplemented to use some
* other kind of type registry. This can
* be reimplemented to use the Java Activation
* Framework, for example.
*
* @param type the non-<code>null</code> content type
* @return the editor kit
*/
public EditorKit getEditorKitForContentType(String type) {
if (typeHandlers == null) {
typeHandlers = new Hashtable(3);
}
EditorKit k = (EditorKit) typeHandlers.get(type);
if (k == null) {
k = createEditorKitForContentType(type);
if (k != null) {
setEditorKitForContentType(type, k);
}
}
if (k == null) {
k = createDefaultEditorKit();
}
return k;
}
/** {@collect.stats}
* Directly sets the editor kit to use for the given type. A
* look-and-feel implementation might use this in conjunction
* with <code>createEditorKitForContentType</code> to install handlers for
* content types with a look-and-feel bias.
*
* @param type the non-<code>null</code> content type
* @param k the editor kit to be set
*/
public void setEditorKitForContentType(String type, EditorKit k) {
if (typeHandlers == null) {
typeHandlers = new Hashtable(3);
}
typeHandlers.put(type, k);
}
/** {@collect.stats}
* Replaces the currently selected content with new content
* represented by the given string. If there is no selection
* this amounts to an insert of the given text. If there
* is no replacement text (i.e. the content string is empty
* or <code>null</code>) this amounts to a removal of the
* current selection. The replacement text will have the
* attributes currently defined for input. If the component is not
* editable, beep and return.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param content the content to replace the selection with. This
* value can be <code>null</code>
*/
public void replaceSelection(String content) {
if (! isEditable()) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
return;
}
EditorKit kit = getEditorKit();
if(kit instanceof StyledEditorKit) {
try {
Document doc = getDocument();
Caret caret = getCaret();
int p0 = Math.min(caret.getDot(), caret.getMark());
int p1 = Math.max(caret.getDot(), caret.getMark());
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).replace(p0, p1 - p0, content,
((StyledEditorKit)kit).getInputAttributes());
}
else {
if (p0 != p1) {
doc.remove(p0, p1 - p0);
}
if (content != null && content.length() > 0) {
doc.insertString(p0, content, ((StyledEditorKit)kit).
getInputAttributes());
}
}
} catch (BadLocationException e) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
}
}
else {
super.replaceSelection(content);
}
}
/** {@collect.stats}
* Creates a handler for the given type from the default registry
* of editor kits. The registry is created if necessary. If the
* registered class has not yet been loaded, an attempt
* is made to dynamically load the prototype of the kit for the
* given type. If the type was registered with a <code>ClassLoader</code>,
* that <code>ClassLoader</code> will be used to load the prototype.
* If there was no registered <code>ClassLoader</code>,
* <code>Class.forName</code> will be used to load the prototype.
* <p>
* Once a prototype <code>EditorKit</code> instance is successfully
* located, it is cloned and the clone is returned.
*
* @param type the content type
* @return the editor kit, or <code>null</code> if there is nothing
* registered for the given type
*/
public static EditorKit createEditorKitForContentType(String type) {
EditorKit k = null;
Hashtable kitRegistry = getKitRegisty();
k = (EditorKit) kitRegistry.get(type);
if (k == null) {
// try to dynamically load the support
String classname = (String) getKitTypeRegistry().get(type);
ClassLoader loader = (ClassLoader) getKitLoaderRegistry().get(type);
try {
Class c;
if (loader != null) {
c = loader.loadClass(classname);
} else {
// Will only happen if developer has invoked
// registerEditorKitForContentType(type, class, null).
c = Class.forName(classname, true, Thread.currentThread().
getContextClassLoader());
}
k = (EditorKit) c.newInstance();
kitRegistry.put(type, k);
} catch (Throwable e) {
k = null;
}
}
// create a copy of the prototype or null if there
// is no prototype.
if (k != null) {
return (EditorKit) k.clone();
}
return null;
}
/** {@collect.stats}
* Establishes the default bindings of <code>type</code> to
* <code>classname</code>.
* The class will be dynamically loaded later when actually
* needed, and can be safely changed before attempted uses
* to avoid loading unwanted classes. The prototype
* <code>EditorKit</code> will be loaded with <code>Class.forName</code>
* when registered with this method.
*
* @param type the non-<code>null</code> content type
* @param classname the class to load later
*/
public static void registerEditorKitForContentType(String type, String classname) {
registerEditorKitForContentType(type, classname,Thread.currentThread().
getContextClassLoader());
}
/** {@collect.stats}
* Establishes the default bindings of <code>type</code> to
* <code>classname</code>.
* The class will be dynamically loaded later when actually
* needed using the given <code>ClassLoader</code>,
* and can be safely changed
* before attempted uses to avoid loading unwanted classes.
*
* @param type the non-<code>null</code> content type
* @param classname the class to load later
* @param loader the <code>ClassLoader</code> to use to load the name
*/
public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) {
getKitTypeRegistry().put(type, classname);
getKitLoaderRegistry().put(type, loader);
getKitRegisty().remove(type);
}
/** {@collect.stats}
* Returns the currently registered <code>EditorKit</code>
* class name for the type <code>type</code>.
*
* @param type the non-<code>null</code> content type
*
* @since 1.3
*/
public static String getEditorKitClassNameForContentType(String type) {
return (String)getKitTypeRegistry().get(type);
}
private static Hashtable getKitTypeRegistry() {
loadDefaultKitsIfNecessary();
return (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey);
}
private static Hashtable getKitLoaderRegistry() {
loadDefaultKitsIfNecessary();
return (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey);
}
private static Hashtable getKitRegisty() {
Hashtable ht = (Hashtable)SwingUtilities.appContextGet(kitRegistryKey);
if (ht == null) {
ht = new Hashtable(3);
SwingUtilities.appContextPut(kitRegistryKey, ht);
}
return ht;
}
/** {@collect.stats}
* This is invoked every time the registries are accessed. Loading
* is done this way instead of via a static as the static is only
* called once when running in plugin resulting in the entries only
* appearing in the first applet.
*/
private static void loadDefaultKitsIfNecessary() {
if (SwingUtilities.appContextGet(kitTypeRegistryKey) == null) {
synchronized(defaultEditorKitMap) {
if (defaultEditorKitMap.size() == 0) {
defaultEditorKitMap.put("text/plain",
"javax.swing.JEditorPane$PlainEditorKit");
defaultEditorKitMap.put("text/html",
"javax.swing.text.html.HTMLEditorKit");
defaultEditorKitMap.put("text/rtf",
"javax.swing.text.rtf.RTFEditorKit");
defaultEditorKitMap.put("application/rtf",
"javax.swing.text.rtf.RTFEditorKit");
}
}
Hashtable ht = new Hashtable();
SwingUtilities.appContextPut(kitTypeRegistryKey, ht);
ht = new Hashtable();
SwingUtilities.appContextPut(kitLoaderRegistryKey, ht);
for (String key : defaultEditorKitMap.keySet()) {
registerEditorKitForContentType(key,defaultEditorKitMap.get(key));
}
}
}
// --- java.awt.Component methods --------------------------
/** {@collect.stats}
* Returns the preferred size for the <code>JEditorPane</code>.
* The preferred size for <code>JEditorPane</code> is slightly altered
* from the preferred size of the superclass. If the size
* of the viewport has become smaller than the minimum size
* of the component, the scrollable definition for tracking
* width or height will turn to false. The default viewport
* layout will give the preferred size, and that is not desired
* in the case where the scrollable is tracking. In that case
* the <em>normal</em> preferred size is adjusted to the
* minimum size. This allows things like HTML tables to
* shrink down to their minimum size and then be laid out at
* their minimum size, refusing to shrink any further.
*
* @return a <code>Dimension</code> containing the preferred size
*/
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
if (getParent() instanceof JViewport) {
JViewport port = (JViewport)getParent();
TextUI ui = getUI();
int prefWidth = d.width;
int prefHeight = d.height;
if (! getScrollableTracksViewportWidth()) {
int w = port.getWidth();
Dimension min = ui.getMinimumSize(this);
if (w != 0 && w < min.width) {
// Only adjust to min if we have a valid size
prefWidth = min.width;
}
}
if (! getScrollableTracksViewportHeight()) {
int h = port.getHeight();
Dimension min = ui.getMinimumSize(this);
if (h != 0 && h < min.height) {
// Only adjust to min if we have a valid size
prefHeight = min.height;
}
}
if (prefWidth != d.width || prefHeight != d.height) {
d = new Dimension(prefWidth, prefHeight);
}
}
return d;
}
// --- JTextComponent methods -----------------------------
/** {@collect.stats}
* Sets the text of this <code>TextComponent</code> to the specified
* content,
* which is expected to be in the format of the content type of
* this editor. For example, if the type is set to <code>text/html</code>
* the string should be specified in terms of HTML.
* <p>
* This is implemented to remove the contents of the current document,
* and replace them by parsing the given string using the current
* <code>EditorKit</code>. This gives the semantics of the
* superclass by not changing
* out the model, while supporting the content type currently set on
* this component. The assumption is that the previous content is
* relatively
* small, and that the previous content doesn't have side effects.
* Both of those assumptions can be violated and cause undesirable results.
* To avoid this, create a new document,
* <code>getEditorKit().createDefaultDocument()</code>, and replace the
* existing <code>Document</code> with the new one. You are then assured the
* previous <code>Document</code> won't have any lingering state.
* <ol>
* <li>
* Leaving the existing model in place means that the old view will be
* torn down, and a new view created, where replacing the document would
* avoid the tear down of the old view.
* <li>
* Some formats (such as HTML) can install things into the document that
* can influence future contents. HTML can have style information embedded
* that would influence the next content installed unexpectedly.
* </ol>
* <p>
* An alternative way to load this component with a string would be to
* create a StringReader and call the read method. In this case the model
* would be replaced after it was initialized with the contents of the
* string.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param t the new text to be set; if <code>null</code> the old
* text will be deleted
* @see #getText
* @beaninfo
* description: the text of this component
*/
public void setText(String t) {
try {
Document doc = getDocument();
doc.remove(0, doc.getLength());
if (t == null || t.equals("")) {
return;
}
Reader r = new StringReader(t);
EditorKit kit = getEditorKit();
kit.read(r, doc, 0);
} catch (IOException ioe) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
} catch (BadLocationException ble) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
}
}
/** {@collect.stats}
* Returns the text contained in this <code>TextComponent</code>
* in terms of the
* content type of this editor. If an exception is thrown while
* attempting to retrieve the text, <code>null</code> will be returned.
* This is implemented to call <code>JTextComponent.write</code> with
* a <code>StringWriter</code>.
*
* @return the text
* @see #setText
*/
public String getText() {
String txt;
try {
StringWriter buf = new StringWriter();
write(buf);
txt = buf.toString();
} catch (IOException ioe) {
txt = null;
}
return txt;
}
// --- Scrollable ----------------------------------------
/** {@collect.stats}
* Returns true if a viewport should always force the width of this
* <code>Scrollable</code> to match the width of the viewport.
*
* @return true if a viewport should force the Scrollables width to
* match its own, false otherwise
*/
public boolean getScrollableTracksViewportWidth() {
if (getParent() instanceof JViewport) {
JViewport port = (JViewport)getParent();
TextUI ui = getUI();
int w = port.getWidth();
Dimension min = ui.getMinimumSize(this);
Dimension max = ui.getMaximumSize(this);
if ((w >= min.width) && (w <= max.width)) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Returns true if a viewport should always force the height of this
* <code>Scrollable</code> to match the height of the viewport.
*
* @return true if a viewport should force the
* <code>Scrollable</code>'s height to match its own,
* false otherwise
*/
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
JViewport port = (JViewport)getParent();
TextUI ui = getUI();
int h = port.getHeight();
Dimension min = ui.getMinimumSize(this);
if (h >= min.height) {
Dimension max = ui.getMaximumSize(this);
if (h <= max.height) {
return true;
}
}
}
return false;
}
// --- Serialization ------------------------------------
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
// --- variables ---------------------------------------
/** {@collect.stats}
* Stream currently loading asynchronously (potentially cancelable).
* Access to this variable should be synchronized.
*/
PageStream loading;
/** {@collect.stats}
* Current content binding of the editor.
*/
private EditorKit kit;
private boolean isUserSetEditorKit;
private Hashtable pageProperties;
/** {@collect.stats} Should be kept in sync with javax.swing.text.html.FormView counterpart. */
final static String PostDataProperty = "javax.swing.JEditorPane.postdata";
/** {@collect.stats}
* Table of registered type handlers for this editor.
*/
private Hashtable typeHandlers;
/*
* Private AppContext keys for this class's static variables.
*/
private static final Object kitRegistryKey = new Object(); // JEditorPane.kitRegistry
private static final Object kitTypeRegistryKey = new Object(); // JEditorPane.kitTypeRegistry
private static final Object kitLoaderRegistryKey = new Object(); // JEditorPane.kitLoaderRegistry
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "EditorPaneUI";
/** {@collect.stats}
* Key for a client property used to indicate whether
* <a href="http://www.w3.org/TR/CSS21/syndata.html#length-units">
* w3c compliant</a> length units are used for html rendering.
* <p>
* By default this is not enabled; to enable
* it set the client {@link #putClientProperty property} with this name
* to <code>Boolean.TRUE</code>.
*
* @since 1.5
*/
public static final String W3C_LENGTH_UNITS = "JEditorPane.w3cLengthUnits";
/** {@collect.stats}
* Key for a client property used to indicate whether
* the default font and foreground color from the component are
* used if a font or foreground color is not specified in the styled
* text.
* <p>
* The default varies based on the look and feel;
* to enable it set the client {@link #putClientProperty property} with
* this name to <code>Boolean.TRUE</code>.
*
* @since 1.5
*/
public static final String HONOR_DISPLAY_PROPERTIES = "JEditorPane.honorDisplayProperties";
static final Map<String, String> defaultEditorKitMap = new HashMap<String, String>(0);
/** {@collect.stats}
* Returns a string representation of this <code>JEditorPane</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JEditorPane</code>
*/
protected String paramString() {
String kitString = (kit != null ?
kit.toString() : "");
String typeHandlersString = (typeHandlers != null ?
typeHandlers.toString() : "");
return super.paramString() +
",kit=" + kitString +
",typeHandlers=" + typeHandlersString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JEditorPane.
* For editor panes, the AccessibleContext takes the form of an
* AccessibleJEditorPane.
* A new AccessibleJEditorPane instance is created if necessary.
*
* @return an AccessibleJEditorPane that serves as the
* AccessibleContext of this JEditorPane
*/
public AccessibleContext getAccessibleContext() {
if (getEditorKit() instanceof HTMLEditorKit) {
if (accessibleContext == null || accessibleContext.getClass() !=
AccessibleJEditorPaneHTML.class) {
accessibleContext = new AccessibleJEditorPaneHTML();
}
} else if (accessibleContext == null || accessibleContext.getClass() !=
AccessibleJEditorPane.class) {
accessibleContext = new AccessibleJEditorPane();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JEditorPane</code> class. It provides an implementation of the
* Java Accessibility API appropriate to editor pane user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJEditorPane extends AccessibleJTextComponent {
/** {@collect.stats}
* Gets the accessibleDescription property of this object. If this
* property isn't set, returns the content type of this
* <code>JEditorPane</code> instead (e.g. "plain/text", "html/text").
*
* @return the localized description of the object; <code>null</code>
* if this object does not have a description
*
* @see #setAccessibleName
*/
public String getAccessibleDescription() {
String description = accessibleDescription;
// fallback to client property
if (description == null) {
description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY);
}
if (description == null) {
description = JEditorPane.this.getContentType();
}
return description;
}
/** {@collect.stats}
* Gets the state set of this object.
*
* @return an instance of AccessibleStateSet describing the states
* of the object
* @see AccessibleStateSet
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
states.add(AccessibleState.MULTI_LINE);
return states;
}
}
/** {@collect.stats}
* This class provides support for <code>AccessibleHypertext</code>,
* and is used in instances where the <code>EditorKit</code>
* installed in this <code>JEditorPane</code> is an instance of
* <code>HTMLEditorKit</code>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane {
private AccessibleContext accessibleContext;
public AccessibleText getAccessibleText() {
return new JEditorPaneAccessibleHypertextSupport();
}
protected AccessibleJEditorPaneHTML () {
HTMLEditorKit kit = (HTMLEditorKit)JEditorPane.this.getEditorKit();
accessibleContext = kit.getAccessibleContext();
}
/** {@collect.stats}
* Returns the number of accessible children of the object.
*
* @return the number of accessible children of the object.
*/
public int getAccessibleChildrenCount() {
if (accessibleContext != null) {
return accessibleContext.getAccessibleChildrenCount();
} else {
return 0;
}
}
/** {@collect.stats}
* Returns the specified Accessible child of the object. The Accessible
* children of an Accessible object are zero-based, so the first child
* of an Accessible child is at index 0, the second child is at index 1,
* and so on.
*
* @param i zero-based index of child
* @return the Accessible child of the object
* @see #getAccessibleChildrenCount
*/
public Accessible getAccessibleChild(int i) {
if (accessibleContext != null) {
return accessibleContext.getAccessibleChild(i);
} else {
return null;
}
}
/** {@collect.stats}
* Returns the Accessible child, if one exists, contained at the local
* coordinate Point.
*
* @param p The point relative to the coordinate system of this object.
* @return the Accessible, if it exists, at the specified location;
* otherwise null
*/
public Accessible getAccessibleAt(Point p) {
if (accessibleContext != null && p != null) {
try {
AccessibleComponent acomp =
accessibleContext.getAccessibleComponent();
if (acomp != null) {
return acomp.getAccessibleAt(p);
} else {
return null;
}
} catch (IllegalComponentStateException e) {
return null;
}
} else {
return null;
}
}
}
/** {@collect.stats}
* What's returned by
* <code>AccessibleJEditorPaneHTML.getAccessibleText</code>.
*
* Provides support for <code>AccessibleHypertext</code> in case
* there is an HTML document being displayed in this
* <code>JEditorPane</code>.
*
*/
protected class JEditorPaneAccessibleHypertextSupport
extends AccessibleJEditorPane implements AccessibleHypertext {
public class HTMLLink extends AccessibleHyperlink {
Element element;
public HTMLLink(Element e) {
element = e;
}
/** {@collect.stats}
* Since the document a link is associated with may have
* changed, this method returns whether this Link is valid
* anymore (with respect to the document it references).
*
* @return a flag indicating whether this link is still valid with
* respect to the AccessibleHypertext it belongs to
*/
public boolean isValid() {
return JEditorPaneAccessibleHypertextSupport.this.linksValid;
}
/** {@collect.stats}
* Returns the number of accessible actions available in this Link
* If there are more than one, the first one is NOT considered the
* "default" action of this LINK object (e.g. in an HTML imagemap).
* In general, links will have only one AccessibleAction in them.
*
* @return the zero-based number of Actions in this object
*/
public int getAccessibleActionCount() {
return 1;
}
/** {@collect.stats}
* Perform the specified Action on the object
*
* @param i zero-based index of actions
* @return true if the the action was performed; else false.
* @see #getAccessibleActionCount
*/
public boolean doAccessibleAction(int i) {
if (i == 0 && isValid() == true) {
URL u = (URL) getAccessibleActionObject(i);
if (u != null) {
HyperlinkEvent linkEvent =
new HyperlinkEvent(JEditorPane.this, HyperlinkEvent.EventType.ACTIVATED, u);
JEditorPane.this.fireHyperlinkUpdate(linkEvent);
return true;
}
}
return false; // link invalid or i != 0
}
/** {@collect.stats}
* Return a String description of this particular
* link action. The string returned is the text
* within the document associated with the element
* which contains this link.
*
* @param i zero-based index of the actions
* @return a String description of the action
* @see #getAccessibleActionCount
*/
public String getAccessibleActionDescription(int i) {
if (i == 0 && isValid() == true) {
Document d = JEditorPane.this.getDocument();
if (d != null) {
try {
return d.getText(getStartIndex(),
getEndIndex() - getStartIndex());
} catch (BadLocationException exception) {
return null;
}
}
}
return null;
}
/** {@collect.stats}
* Returns a URL object that represents the link.
*
* @param i zero-based index of the actions
* @return an URL representing the HTML link itself
* @see #getAccessibleActionCount
*/
public Object getAccessibleActionObject(int i) {
if (i == 0 && isValid() == true) {
AttributeSet as = element.getAttributes();
AttributeSet anchor =
(AttributeSet) as.getAttribute(HTML.Tag.A);
String href = (anchor != null) ?
(String) anchor.getAttribute(HTML.Attribute.HREF) : null;
if (href != null) {
URL u;
try {
u = new URL(JEditorPane.this.getPage(), href);
} catch (MalformedURLException m) {
u = null;
}
return u;
}
}
return null; // link invalid or i != 0
}
/** {@collect.stats}
* Return an object that represents the link anchor,
* as appropriate for that link. E.g. from HTML:
* <a href="http://www.sun.com/access">Accessibility</a>
* this method would return a String containing the text:
* 'Accessibility'.
*
* Similarly, from this HTML:
* <a HREF="#top"><img src="top-hat.gif" alt="top hat"></a>
* this might return the object ImageIcon("top-hat.gif", "top hat");
*
* @param i zero-based index of the actions
* @return an Object representing the hypertext anchor
* @see #getAccessibleActionCount
*/
public Object getAccessibleActionAnchor(int i) {
return getAccessibleActionDescription(i);
}
/** {@collect.stats}
* Get the index with the hypertext document at which this
* link begins
*
* @return index of start of link
*/
public int getStartIndex() {
return element.getStartOffset();
}
/** {@collect.stats}
* Get the index with the hypertext document at which this
* link ends
*
* @return index of end of link
*/
public int getEndIndex() {
return element.getEndOffset();
}
}
private class LinkVector extends Vector {
public int baseElementIndex(Element e) {
HTMLLink l;
for (int i = 0; i < elementCount; i++) {
l = (HTMLLink) elementAt(i);
if (l.element == e) {
return i;
}
}
return -1;
}
}
LinkVector hyperlinks;
boolean linksValid = false;
/** {@collect.stats}
* Build the private table mapping links to locations in the text
*/
private void buildLinkTable() {
hyperlinks.removeAllElements();
Document d = JEditorPane.this.getDocument();
if (d != null) {
ElementIterator ei = new ElementIterator(d);
Element e;
AttributeSet as;
AttributeSet anchor;
String href;
while ((e = ei.next()) != null) {
if (e.isLeaf()) {
as = e.getAttributes();
anchor = (AttributeSet) as.getAttribute(HTML.Tag.A);
href = (anchor != null) ?
(String) anchor.getAttribute(HTML.Attribute.HREF) : null;
if (href != null) {
hyperlinks.addElement(new HTMLLink(e));
}
}
}
}
linksValid = true;
}
/** {@collect.stats}
* Make one of these puppies
*/
public JEditorPaneAccessibleHypertextSupport() {
hyperlinks = new LinkVector();
Document d = JEditorPane.this.getDocument();
if (d != null) {
d.addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent theEvent) {
linksValid = false;
}
public void insertUpdate(DocumentEvent theEvent) {
linksValid = false;
}
public void removeUpdate(DocumentEvent theEvent) {
linksValid = false;
}
});
}
}
/** {@collect.stats}
* Returns the number of links within this hypertext doc.
*
* @return number of links in this hypertext doc.
*/
public int getLinkCount() {
if (linksValid == false) {
buildLinkTable();
}
return hyperlinks.size();
}
/** {@collect.stats}
* Returns the index into an array of hyperlinks that
* is associated with this character index, or -1 if there
* is no hyperlink associated with this index.
*
* @param charIndex index within the text
* @return index into the set of hyperlinks for this hypertext doc.
*/
public int getLinkIndex(int charIndex) {
if (linksValid == false) {
buildLinkTable();
}
Element e = null;
Document doc = JEditorPane.this.getDocument();
if (doc != null) {
for (e = doc.getDefaultRootElement(); ! e.isLeaf(); ) {
int index = e.getElementIndex(charIndex);
e = e.getElement(index);
}
}
// don't need to verify that it's an HREF element; if
// not, then it won't be in the hyperlinks Vector, and
// so indexOf will return -1 in any case
return hyperlinks.baseElementIndex(e);
}
/** {@collect.stats}
* Returns the index into an array of hyperlinks that
* index. If there is no hyperlink at this index, it returns
* null.
*
* @param linkIndex into the set of hyperlinks for this hypertext doc.
* @return string representation of the hyperlink
*/
public AccessibleHyperlink getLink(int linkIndex) {
if (linksValid == false) {
buildLinkTable();
}
if (linkIndex >= 0 && linkIndex < hyperlinks.size()) {
return (AccessibleHyperlink) hyperlinks.elementAt(linkIndex);
} else {
return null;
}
}
/** {@collect.stats}
* Returns the contiguous text within the document that
* is associated with this hyperlink.
*
* @param linkIndex into the set of hyperlinks for this hypertext doc.
* @return the contiguous text sharing the link at this index
*/
public String getLinkText(int linkIndex) {
if (linksValid == false) {
buildLinkTable();
}
Element e = (Element) hyperlinks.elementAt(linkIndex);
if (e != null) {
Document d = JEditorPane.this.getDocument();
if (d != null) {
try {
return d.getText(e.getStartOffset(),
e.getEndOffset() - e.getStartOffset());
} catch (BadLocationException exception) {
return null;
}
}
}
return null;
}
}
static class PlainEditorKit extends DefaultEditorKit implements ViewFactory {
/** {@collect.stats}
* Fetches a factory that is suitable for producing
* views of any models that are produced by this
* kit. The default is to have the UI produce the
* factory, so this method has no implementation.
*
* @return the view factory
*/
public ViewFactory getViewFactory() {
return this;
}
/** {@collect.stats}
* Creates a view from the given structural element of a
* document.
*
* @param elem the piece of the document to build a view of
* @return the view
* @see View
*/
public View create(Element elem) {
Document doc = elem.getDocument();
Object i18nFlag
= doc.getProperty("i18n"/*AbstractDocument.I18NProperty*/);
if ((i18nFlag != null) && i18nFlag.equals(Boolean.TRUE)) {
// build a view that support bidi
return createI18N(elem);
} else {
return new WrappedPlainView(elem);
}
}
View createI18N(Element elem) {
String kind = elem.getName();
if (kind != null) {
if (kind.equals(AbstractDocument.ContentElementName)) {
return new PlainParagraph(elem);
} else if (kind.equals(AbstractDocument.ParagraphElementName)){
return new BoxView(elem, View.Y_AXIS);
}
}
return null;
}
/** {@collect.stats}
* Paragraph for representing plain-text lines that support
* bidirectional text.
*/
static class PlainParagraph extends javax.swing.text.ParagraphView {
PlainParagraph(Element elem) {
super(elem);
layoutPool = new LogicalView(elem);
layoutPool.setParent(this);
}
protected void setPropertiesFromAttributes() {
Component c = getContainer();
if ((c != null)
&& (! c.getComponentOrientation().isLeftToRight()))
{
setJustification(StyleConstants.ALIGN_RIGHT);
} else {
setJustification(StyleConstants.ALIGN_LEFT);
}
}
/** {@collect.stats}
* Fetch the constraining span to flow against for
* the given child index.
*/
public int getFlowSpan(int index) {
Component c = getContainer();
if (c instanceof JTextArea) {
JTextArea area = (JTextArea) c;
if (! area.getLineWrap()) {
// no limit if unwrapped
return Integer.MAX_VALUE;
}
}
return super.getFlowSpan(index);
}
protected SizeRequirements calculateMinorAxisRequirements(int axis,
SizeRequirements r)
{
SizeRequirements req
= super.calculateMinorAxisRequirements(axis, r);
Component c = getContainer();
if (c instanceof JTextArea) {
JTextArea area = (JTextArea) c;
if (! area.getLineWrap()) {
// min is pref if unwrapped
req.minimum = req.preferred;
}
}
return req;
}
/** {@collect.stats}
* This class can be used to represent a logical view for
* a flow. It keeps the children updated to reflect the state
* of the model, gives the logical child views access to the
* view hierarchy, and calculates a preferred span. It doesn't
* do any rendering, layout, or model/view translation.
*/
static class LogicalView extends CompositeView {
LogicalView(Element elem) {
super(elem);
}
protected int getViewIndexAtPosition(int pos) {
Element elem = getElement();
if (elem.getElementCount() > 0) {
return elem.getElementIndex(pos);
}
return 0;
}
protected boolean
updateChildren(DocumentEvent.ElementChange ec,
DocumentEvent e, ViewFactory f)
{
return false;
}
protected void loadChildren(ViewFactory f) {
Element elem = getElement();
if (elem.getElementCount() > 0) {
super.loadChildren(f);
} else {
View v = new GlyphView(elem);
append(v);
}
}
public float getPreferredSpan(int axis) {
if( getViewCount() != 1 )
throw new Error("One child view is assumed.");
View v = getView(0);
//((GlyphView)v).setGlyphPainter(null);
return v.getPreferredSpan(axis);
}
/** {@collect.stats}
* Forward the DocumentEvent to the given child view. This
* is implemented to reparent the child to the logical view
* (the children may have been parented by a row in the flow
* if they fit without breaking) and then execute the
* superclass behavior.
*
* @param v the child view to forward the event to.
* @param e the change information from the associated document
* @param a the current allocation of the view
* @param f the factory to use to rebuild if the view has
* children
* @see #forwardUpdate
* @since 1.3
*/
protected void forwardUpdateToView(View v, DocumentEvent e,
Shape a, ViewFactory f) {
v.setParent(this);
super.forwardUpdateToView(v, e, a, f);
}
// The following methods don't do anything useful, they
// simply keep the class from being abstract.
public void paint(Graphics g, Shape allocation) {
}
protected boolean isBefore(int x, int y, Rectangle alloc) {
return false;
}
protected boolean isAfter(int x, int y, Rectangle alloc) {
return false;
}
protected View getViewAtPoint(int x, int y, Rectangle alloc) {
return null;
}
protected void childAllocation(int index, Rectangle a) {
}
}
}
}
/* This is useful for the nightmare of parsing multi-part HTTP/RFC822 headers
* sensibly:
* From a String like: 'timeout=15, max=5'
* create an array of Strings:
* { {"timeout", "15"},
* {"max", "5"}
* }
* From one like: 'Basic Realm="FuzzFace" Foo="Biz Bar Baz"'
* create one like (no quotes in literal):
* { {"basic", null},
* {"realm", "FuzzFace"}
* {"foo", "Biz Bar Baz"}
* }
* keys are converted to lower case, vals are left as is....
*
* author Dave Brown
*/
static class HeaderParser {
/* table of key/val pairs - maxes out at 10!!!!*/
String raw;
String[][] tab;
public HeaderParser(String raw) {
this.raw = raw;
tab = new String[10][2];
parse();
}
private void parse() {
if (raw != null) {
raw = raw.trim();
char[] ca = raw.toCharArray();
int beg = 0, end = 0, i = 0;
boolean inKey = true;
boolean inQuote = false;
int len = ca.length;
while (end < len) {
char c = ca[end];
if (c == '=') { // end of a key
tab[i][0] = new String(ca, beg, end-beg).toLowerCase();
inKey = false;
end++;
beg = end;
} else if (c == '\"') {
if (inQuote) {
tab[i++][1]= new String(ca, beg, end-beg);
inQuote=false;
do {
end++;
} while (end < len && (ca[end] == ' ' || ca[end] == ','));
inKey=true;
beg=end;
} else {
inQuote=true;
end++;
beg=end;
}
} else if (c == ' ' || c == ',') { // end key/val, of whatever we're in
if (inQuote) {
end++;
continue;
} else if (inKey) {
tab[i++][0] = (new String(ca, beg, end-beg)).toLowerCase();
} else {
tab[i++][1] = (new String(ca, beg, end-beg));
}
while (end < len && (ca[end] == ' ' || ca[end] == ',')) {
end++;
}
inKey = true;
beg = end;
} else {
end++;
}
}
// get last key/val, if any
if (--end > beg) {
if (!inKey) {
if (ca[end] == '\"') {
tab[i++][1] = (new String(ca, beg, end-beg));
} else {
tab[i++][1] = (new String(ca, beg, end-beg+1));
}
} else {
tab[i][0] = (new String(ca, beg, end-beg+1)).toLowerCase();
}
} else if (end == beg) {
if (!inKey) {
if (ca[end] == '\"') {
tab[i++][1] = String.valueOf(ca[end-1]);
} else {
tab[i++][1] = String.valueOf(ca[end]);
}
} else {
tab[i][0] = String.valueOf(ca[end]).toLowerCase();
}
}
}
}
public String findKey(int i) {
if (i < 0 || i > 10)
return null;
return tab[i][0];
}
public String findValue(int i) {
if (i < 0 || i > 10)
return null;
return tab[i][1];
}
public String findValue(String key) {
return findValue(key, null);
}
public String findValue(String k, String Default) {
if (k == null)
return Default;
k = k.toLowerCase();
for (int i = 0; i < 10; ++i) {
if (tab[i][0] == null) {
return Default;
} else if (k.equals(tab[i][0])) {
return tab[i][1];
}
}
return Default;
}
public int findInt(String k, int Default) {
try {
return Integer.parseInt(findValue(k, String.valueOf(Default)));
} catch (Throwable t) {
return Default;
}
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.*;
import java.util.Vector;
import java.util.Enumeration;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.event.*;
import javax.swing.border.Border;
import javax.swing.plaf.*;
import javax.accessibility.*;
/** {@collect.stats}
* An implementation of a menu bar. You add <code>JMenu</code> objects to the
* menu bar to construct a menu. When the user selects a <code>JMenu</code>
* object, its associated <code>JPopupMenu</code> is displayed, allowing the
* user to select one of the <code>JMenuItems</code> on it.
* <p>
* For information and examples of using menu bars see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html">How to Use Menus</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer true
* description: A container for holding and displaying menus.
*
* @author Georges Saab
* @author David Karlton
* @author Arnaud Weber
* @see JMenu
* @see JPopupMenu
* @see JMenuItem
*/
public class JMenuBar extends JComponent implements Accessible,MenuElement
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "MenuBarUI";
/*
* Model for the selected subcontrol.
*/
private transient SingleSelectionModel selectionModel;
private boolean paintBorder = true;
private Insets margin = null;
/* diagnostic aids -- should be false for production builds. */
private static final boolean TRACE = false; // trace creates and disposes
private static final boolean VERBOSE = false; // show reuse hits/misses
private static final boolean DEBUG = false; // show bad params, misc.
/** {@collect.stats}
* Creates a new menu bar.
*/
public JMenuBar() {
super();
setFocusTraversalKeysEnabled(false);
setSelectionModel(new DefaultSingleSelectionModel());
updateUI();
}
/** {@collect.stats}
* Returns the menubar's current UI.
* @see #setUI
*/
public MenuBarUI getUI() {
return (MenuBarUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the new MenuBarUI L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(MenuBarUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the UI property with a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((MenuBarUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "MenuBarUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns the model object that handles single selections.
*
* @return the <code>SingleSelectionModel</code> property
* @see SingleSelectionModel
*/
public SingleSelectionModel getSelectionModel() {
return selectionModel;
}
/** {@collect.stats}
* Sets the model object to handle single selections.
*
* @param model the <code>SingleSelectionModel</code> to use
* @see SingleSelectionModel
* @beaninfo
* bound: true
* description: The selection model, recording which child is selected.
*/
public void setSelectionModel(SingleSelectionModel model) {
SingleSelectionModel oldValue = selectionModel;
this.selectionModel = model;
firePropertyChange("selectionModel", oldValue, selectionModel);
}
/** {@collect.stats}
* Appends the specified menu to the end of the menu bar.
*
* @param c the <code>JMenu</code> component to add
* @return the menu component
*/
public JMenu add(JMenu c) {
super.add(c);
return c;
}
/** {@collect.stats}
* Returns the menu at the specified position in the menu bar.
*
* @param index an integer giving the position in the menu bar, where
* 0 is the first position
* @return the <code>JMenu</code> at that position, or <code>null</code> if
* if there is no <code>JMenu</code> at that position (ie. if
* it is a <code>JMenuItem</code>)
*/
public JMenu getMenu(int index) {
Component c = getComponentAtIndex(index);
if (c instanceof JMenu)
return (JMenu) c;
return null;
}
/** {@collect.stats}
* Returns the number of items in the menu bar.
*
* @return the number of items in the menu bar
*/
public int getMenuCount() {
return getComponentCount();
}
/** {@collect.stats}
* Sets the help menu that appears when the user selects the
* "help" option in the menu bar. This method is not yet implemented
* and will throw an exception.
*
* @param menu the JMenu that delivers help to the user
*/
public void setHelpMenu(JMenu menu) {
throw new Error("setHelpMenu() not yet implemented.");
}
/** {@collect.stats}
* Gets the help menu for the menu bar. This method is not yet
* implemented and will throw an exception.
*
* @return the <code>JMenu</code> that delivers help to the user
*/
public JMenu getHelpMenu() {
throw new Error("getHelpMenu() not yet implemented.");
}
/** {@collect.stats}
* Returns the component at the specified index.
*
* @param i an integer specifying the position, where 0 is first
* @return the <code>Component</code> at the position,
* or <code>null</code> for an invalid index
* @deprecated replaced by <code>getComponent(int i)</code>
*/
@Deprecated
public Component getComponentAtIndex(int i) {
if(i < 0 || i >= getComponentCount()) {
return null;
}
return getComponent(i);
}
/** {@collect.stats}
* Returns the index of the specified component.
*
* @param c the <code>Component</code> to find
* @return an integer giving the component's position, where 0 is first;
* or -1 if it can't be found
*/
public int getComponentIndex(Component c) {
int ncomponents = this.getComponentCount();
Component[] component = this.getComponents();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = component[i];
if (comp == c)
return i;
}
return -1;
}
/** {@collect.stats}
* Sets the currently selected component, producing a
* a change to the selection model.
*
* @param sel the <code>Component</code> to select
*/
public void setSelected(Component sel) {
SingleSelectionModel model = getSelectionModel();
int index = getComponentIndex(sel);
model.setSelectedIndex(index);
}
/** {@collect.stats}
* Returns true if the menu bar currently has a component selected.
*
* @return true if a selection has been made, else false
*/
public boolean isSelected() {
return selectionModel.isSelected();
}
/** {@collect.stats}
* Returns true if the menu bars border should be painted.
*
* @return true if the border should be painted, else false
*/
public boolean isBorderPainted() {
return paintBorder;
}
/** {@collect.stats}
* Sets whether the border should be painted.
*
* @param b if true and border property is not <code>null</code>,
* the border is painted.
* @see #isBorderPainted
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether the border should be painted.
*/
public void setBorderPainted(boolean b) {
boolean oldValue = paintBorder;
paintBorder = b;
firePropertyChange("borderPainted", oldValue, paintBorder);
if (b != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Paints the menubar's border if <code>BorderPainted</code>
* property is true.
*
* @param g the <code>Graphics</code> context to use for painting
* @see JComponent#paint
* @see JComponent#setBorder
*/
protected void paintBorder(Graphics g) {
if (isBorderPainted()) {
super.paintBorder(g);
}
}
/** {@collect.stats}
* Sets the margin between the menubar's border and
* its menus. Setting to <code>null</code> will cause the menubar to
* use the default margins.
*
* @param m an Insets object containing the margin values
* @see Insets
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The space between the menubar's border and its contents
*/
public void setMargin(Insets m) {
Insets old = margin;
this.margin = m;
firePropertyChange("margin", old, m);
if (old == null || !old.equals(m)) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the margin between the menubar's border and
* its menus. If there is no previous margin, it will create
* a default margin with zero size.
*
* @return an <code>Insets</code> object containing the margin values
* @see Insets
*/
public Insets getMargin() {
if(margin == null) {
return new Insets(0,0,0,0);
} else {
return margin;
}
}
/** {@collect.stats}
* Implemented to be a <code>MenuElement</code> -- does nothing.
*
* @see #getSubElements
*/
public void processMouseEvent(MouseEvent event,MenuElement path[],MenuSelectionManager manager) {
}
/** {@collect.stats}
* Implemented to be a <code>MenuElement</code> -- does nothing.
*
* @see #getSubElements
*/
public void processKeyEvent(KeyEvent e,MenuElement path[],MenuSelectionManager manager) {
}
/** {@collect.stats}
* Implemented to be a <code>MenuElement</code> -- does nothing.
*
* @see #getSubElements
*/
public void menuSelectionChanged(boolean isIncluded) {
}
/** {@collect.stats}
* Implemented to be a <code>MenuElement</code> -- returns the
* menus in this menu bar.
* This is the reason for implementing the <code>MenuElement</code>
* interface -- so that the menu bar can be treated the same as
* other menu elements.
* @return an array of menu items in the menu bar.
*/
public MenuElement[] getSubElements() {
MenuElement result[];
Vector tmp = new Vector();
int c = getComponentCount();
int i;
Component m;
for(i=0 ; i < c ; i++) {
m = getComponent(i);
if(m instanceof MenuElement)
tmp.addElement(m);
}
result = new MenuElement[tmp.size()];
for(i=0,c=tmp.size() ; i < c ; i++)
result[i] = (MenuElement) tmp.elementAt(i);
return result;
}
/** {@collect.stats}
* Implemented to be a <code>MenuElement</code>. Returns this object.
*
* @return the current <code>Component</code> (this)
* @see #getSubElements
*/
public Component getComponent() {
return this;
}
/** {@collect.stats}
* Returns a string representation of this <code>JMenuBar</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JMenuBar</code>
*/
protected String paramString() {
String paintBorderString = (paintBorder ?
"true" : "false");
String marginString = (margin != null ?
margin.toString() : "");
return super.paramString() +
",margin=" + marginString +
",paintBorder=" + paintBorderString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JMenuBar.
* For JMenuBars, the AccessibleContext takes the form of an
* AccessibleJMenuBar.
* A new AccessibleJMenuBar instance is created if necessary.
*
* @return an AccessibleJMenuBar that serves as the
* AccessibleContext of this JMenuBar
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJMenuBar();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JMenuBar</code> class. It provides an implementation of the
* Java Accessibility API appropriate to menu bar user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJMenuBar extends AccessibleJComponent
implements AccessibleSelection {
/** {@collect.stats}
* Get the accessible state set of this object.
*
* @return an instance of AccessibleState containing the current state
* of the object
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
return states;
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.MENU_BAR;
}
/** {@collect.stats}
* Get the AccessibleSelection associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleSelection interface on behalf of itself.
*
* @return this object
*/
public AccessibleSelection getAccessibleSelection() {
return this;
}
/** {@collect.stats}
* Returns 1 if a menu is currently selected in this menu bar.
*
* @return 1 if a menu is currently selected, else 0
*/
public int getAccessibleSelectionCount() {
if (isSelected()) {
return 1;
} else {
return 0;
}
}
/** {@collect.stats}
* Returns the currently selected menu if one is selected,
* otherwise null.
*/
public Accessible getAccessibleSelection(int i) {
if (isSelected()) {
if (i != 0) { // single selection model for JMenuBar
return null;
}
int j = getSelectionModel().getSelectedIndex();
if (getComponentAtIndex(j) instanceof Accessible) {
return (Accessible) getComponentAtIndex(j);
}
}
return null;
}
/** {@collect.stats}
* Returns true if the current child of this object is selected.
*
* @param i the zero-based index of the child in this Accessible
* object.
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
return (i == getSelectionModel().getSelectedIndex());
}
/** {@collect.stats}
* Selects the nth menu in the menu bar, forcing it to
* pop up. If another menu is popped up, this will force
* it to close. If the nth menu is already selected, this
* method has no effect.
*
* @param i the zero-based index of selectable items
* @see #getAccessibleStateSet
*/
public void addAccessibleSelection(int i) {
// first close up any open menu
int j = getSelectionModel().getSelectedIndex();
if (i == j) {
return;
}
if (j >= 0 && j < getMenuCount()) {
JMenu menu = getMenu(j);
if (menu != null) {
MenuSelectionManager.defaultManager().setSelectedPath(null);
// menu.setPopupMenuVisible(false);
}
}
// now popup the new menu
getSelectionModel().setSelectedIndex(i);
JMenu menu = getMenu(i);
if (menu != null) {
MenuElement me[] = new MenuElement[3];
me[0] = JMenuBar.this;
me[1] = menu;
me[2] = menu.getPopupMenu();
MenuSelectionManager.defaultManager().setSelectedPath(me);
// menu.setPopupMenuVisible(true);
}
}
/** {@collect.stats}
* Removes the nth selected item in the object from the object's
* selection. If the nth item isn't currently selected, this
* method has no effect. Otherwise, it closes the popup menu.
*
* @param i the zero-based index of selectable items
*/
public void removeAccessibleSelection(int i) {
if (i >= 0 && i < getMenuCount()) {
JMenu menu = getMenu(i);
if (menu != null) {
MenuSelectionManager.defaultManager().setSelectedPath(null);
// menu.setPopupMenuVisible(false);
}
getSelectionModel().setSelectedIndex(-1);
}
}
/** {@collect.stats}
* Clears the selection in the object, so that nothing in the
* object is selected. This will close any open menu.
*/
public void clearAccessibleSelection() {
int i = getSelectionModel().getSelectedIndex();
if (i >= 0 && i < getMenuCount()) {
JMenu menu = getMenu(i);
if (menu != null) {
MenuSelectionManager.defaultManager().setSelectedPath(null);
// menu.setPopupMenuVisible(false);
}
}
getSelectionModel().setSelectedIndex(-1);
}
/** {@collect.stats}
* Normally causes every selected item in the object to be selected
* if the object supports multiple selections. This method
* makes no sense in a menu bar, and so does nothing.
*/
public void selectAllAccessibleSelection() {
}
} // internal class AccessibleJMenuBar
/** {@collect.stats}
* Subclassed to check all the child menus.
* @since 1.3
*/
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
int condition, boolean pressed) {
// See if we have a local binding.
boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
if (!retValue) {
MenuElement[] subElements = getSubElements();
for (int i=0; i<subElements.length; i++) {
if (processBindingForKeyStrokeRecursive(
subElements[i], ks, e, condition, pressed)) {
return true;
}
}
}
return retValue;
}
static boolean processBindingForKeyStrokeRecursive(MenuElement elem,
KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
if (elem == null) {
return false;
}
Component c = elem.getComponent();
if ( !(c.isVisible() || (c instanceof JPopupMenu)) || !c.isEnabled() ) {
return false;
}
if (c != null && c instanceof JComponent &&
((JComponent)c).processKeyBinding(ks, e, condition, pressed)) {
return true;
}
MenuElement[] subElements = elem.getSubElements();
for(int i=0; i<subElements.length; i++) {
if (processBindingForKeyStrokeRecursive(subElements[i], ks, e,
condition, pressed)) {
return true;
// We don't, pass along to children JMenu's
}
}
return false;
}
/** {@collect.stats}
* Overrides <code>JComponent.addNotify</code> to register this
* menu bar with the current keyboard manager.
*/
public void addNotify() {
super.addNotify();
KeyboardManager.getCurrentManager().registerMenuBar(this);
}
/** {@collect.stats}
* Overrides <code>JComponent.removeNotify</code> to unregister this
* menu bar with the current keyboard manager.
*/
public void removeNotify() {
super.removeNotify();
KeyboardManager.getCurrentManager().unregisterMenuBar(this);
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
Object[] kvData = new Object[4];
int n = 0;
if (selectionModel instanceof Serializable) {
kvData[n++] = "selectionModel";
kvData[n++] = selectionModel;
}
s.writeObject(kvData);
}
/** {@collect.stats}
* See JComponent.readObject() for information about serialization
* in Swing.
*/
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
{
s.defaultReadObject();
Object[] kvData = (Object[])(s.readObject());
for(int i = 0; i < kvData.length; i += 2) {
if (kvData[i] == null) {
break;
}
else if (kvData[i].equals("selectionModel")) {
selectionModel = (SingleSelectionModel)kvData[i + 1];
}
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.beans.PropertyVetoException;
import java.beans.PropertyChangeEvent;
import javax.swing.border.Border;
import java.awt.event.ComponentListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
/** {@collect.stats} This is an implementation of the <code>DesktopManager</code>.
* It currently implements the basic behaviors for managing
* <code>JInternalFrame</code>s in an arbitrary parent.
* <code>JInternalFrame</code>s that are not children of a
* <code>JDesktop</code> will use this component
* to handle their desktop-like actions.
* <p>This class provides a policy for the various JInternalFrame methods,
* it is not meant to be called directly rather the various JInternalFrame
* methods will call into the DesktopManager.</p>
* @see JDesktopPane
* @see JInternalFrame
* @author David Kloba
* @author Steve Wilson
*/
public class DefaultDesktopManager implements DesktopManager, java.io.Serializable {
final static String HAS_BEEN_ICONIFIED_PROPERTY = "wasIconOnce";
final static int DEFAULT_DRAG_MODE = 0;
final static int OUTLINE_DRAG_MODE = 1;
final static int FASTER_DRAG_MODE = 2;
int dragMode = DEFAULT_DRAG_MODE;
private transient Rectangle currentBounds = null;
private transient Graphics desktopGraphics = null;
private transient Rectangle desktopBounds = null;
private transient Rectangle[] floatingItems = {};
/** {@collect.stats}
* Set to true when the user actually drags a frame vs clicks on it
* to start the drag operation. This is only used when dragging with
* FASTER_DRAG_MODE.
*/
private transient boolean didDrag;
/** {@collect.stats} Normally this method will not be called. If it is, it
* try to determine the appropriate parent from the desktopIcon of the frame.
* Will remove the desktopIcon from its parent if it successfully adds the frame.
*/
public void openFrame(JInternalFrame f) {
if(f.getDesktopIcon().getParent() != null) {
f.getDesktopIcon().getParent().add(f);
removeIconFor(f);
}
}
/** {@collect.stats}
* Removes the frame, and, if necessary, the
* <code>desktopIcon</code>, from its parent.
* @param f the <code>JInternalFrame</code> to be removed
*/
public void closeFrame(JInternalFrame f) {
JDesktopPane d = f.getDesktopPane();
if (d == null) {
return;
}
boolean findNext = f.isSelected();
Container c = f.getParent();
JInternalFrame nextFrame = null;
if (findNext) {
nextFrame = d.getNextFrame(f);
try { f.setSelected(false); } catch (PropertyVetoException e2) { }
}
if(c != null) {
c.remove(f); // Removes the focus.
c.repaint(f.getX(), f.getY(), f.getWidth(), f.getHeight());
}
removeIconFor(f);
if(f.getNormalBounds() != null)
f.setNormalBounds(null);
if(wasIcon(f))
setWasIcon(f, null);
if (nextFrame != null) {
try { nextFrame.setSelected(true); }
catch (PropertyVetoException e2) { }
} else if (findNext && d.getComponentCount() == 0) {
// It was selected and was the last component on the desktop.
d.requestFocus();
}
}
/** {@collect.stats}
* Resizes the frame to fill its parents bounds.
* @param f the frame to be resized
*/
public void maximizeFrame(JInternalFrame f) {
if (f.isIcon()) {
try {
// In turn calls deiconifyFrame in the desktop manager.
// That method will handle the maximization of the frame.
f.setIcon(false);
} catch (PropertyVetoException e2) {
}
} else {
f.setNormalBounds(f.getBounds());
Rectangle desktopBounds = f.getParent().getBounds();
setBoundsForFrame(f, 0, 0,
desktopBounds.width, desktopBounds.height);
}
// Set the maximized frame as selected.
try {
f.setSelected(true);
} catch (PropertyVetoException e2) {
}
}
/** {@collect.stats}
* Restores the frame back to its size and position prior
* to a <code>maximizeFrame</code> call.
* @param f the <code>JInternalFrame</code> to be restored
*/
public void minimizeFrame(JInternalFrame f) {
// If the frame was an icon restore it back to an icon.
if (f.isIcon()) {
iconifyFrame(f);
return;
}
if ((f.getNormalBounds()) != null) {
Rectangle r = f.getNormalBounds();
f.setNormalBounds(null);
try { f.setSelected(true); } catch (PropertyVetoException e2) { }
setBoundsForFrame(f, r.x, r.y, r.width, r.height);
}
}
/** {@collect.stats}
* Removes the frame from its parent and adds its
* <code>desktopIcon</code> to the parent.
* @param f the <code>JInternalFrame</code> to be iconified
*/
public void iconifyFrame(JInternalFrame f) {
JInternalFrame.JDesktopIcon desktopIcon;
Container c = f.getParent();
JDesktopPane d = f.getDesktopPane();
boolean findNext = f.isSelected();
desktopIcon = f.getDesktopIcon();
if(!wasIcon(f)) {
Rectangle r = getBoundsForIconOf(f);
desktopIcon.setBounds(r.x, r.y, r.width, r.height);
setWasIcon(f, Boolean.TRUE);
}
if (c == null || d == null) {
return;
}
if (c instanceof JLayeredPane) {
JLayeredPane lp = (JLayeredPane)c;
int layer = lp.getLayer(f);
lp.putLayer(desktopIcon, layer);
}
// If we are maximized we already have the normal bounds recorded
// don't try to re-record them, otherwise we incorrectly set the
// normal bounds to maximized state.
if (!f.isMaximum()) {
f.setNormalBounds(f.getBounds());
}
d.setComponentOrderCheckingEnabled(false);
c.remove(f);
c.add(desktopIcon);
d.setComponentOrderCheckingEnabled(true);
c.repaint(f.getX(), f.getY(), f.getWidth(), f.getHeight());
if (findNext) {
if (d.selectFrame(true) == null) {
// The icon is the last frame.
f.restoreSubcomponentFocus();
}
}
}
/** {@collect.stats}
* Removes the desktopIcon from its parent and adds its frame
* to the parent.
* @param f the <code>JInternalFrame</code> to be de-iconified
*/
public void deiconifyFrame(JInternalFrame f) {
JInternalFrame.JDesktopIcon desktopIcon = f.getDesktopIcon();
Container c = desktopIcon.getParent();
JDesktopPane d = f.getDesktopPane();
if (c != null && d != null) {
c.add(f);
// If the frame is to be restored to a maximized state make
// sure it still fills the whole desktop.
if (f.isMaximum()) {
Rectangle desktopBounds = c.getBounds();
if (f.getWidth() != desktopBounds.width ||
f.getHeight() != desktopBounds.height) {
setBoundsForFrame(f, 0, 0,
desktopBounds.width, desktopBounds.height);
}
}
removeIconFor(f);
if (f.isSelected()) {
f.moveToFront();
f.restoreSubcomponentFocus();
}
else {
try {
f.setSelected(true);
} catch (PropertyVetoException e2) {}
}
}
}
/** {@collect.stats} This will activate <b>f</b> moving it to the front. It will
* set the current active frame's (if any)
* <code>IS_SELECTED_PROPERTY</code> to <code>false</code>.
* There can be only one active frame across all Layers.
* @param f the <code>JInternalFrame</code> to be activated
*/
public void activateFrame(JInternalFrame f) {
Container p = f.getParent();
Component[] c;
JDesktopPane d = f.getDesktopPane();
JInternalFrame currentlyActiveFrame =
(d == null) ? null : d.getSelectedFrame();
// fix for bug: 4162443
if(p == null) {
// If the frame is not in parent, its icon maybe, check it
p = f.getDesktopIcon().getParent();
if(p == null)
return;
}
// we only need to keep track of the currentActive InternalFrame, if any
if (currentlyActiveFrame == null){
if (d != null) { d.setSelectedFrame(f);}
} else if (currentlyActiveFrame != f) {
// if not the same frame as the current active
// we deactivate the current
if (currentlyActiveFrame.isSelected()) {
try {
currentlyActiveFrame.setSelected(false);
}
catch(PropertyVetoException e2) {}
}
if (d != null) { d.setSelectedFrame(f);}
}
f.moveToFront();
}
// implements javax.swing.DesktopManager
public void deactivateFrame(JInternalFrame f) {
JDesktopPane d = f.getDesktopPane();
JInternalFrame currentlyActiveFrame =
(d == null) ? null : d.getSelectedFrame();
if (currentlyActiveFrame == f)
d.setSelectedFrame(null);
}
// implements javax.swing.DesktopManager
public void beginDraggingFrame(JComponent f) {
setupDragMode(f);
if (dragMode == FASTER_DRAG_MODE) {
Component desktop = f.getParent();
floatingItems = findFloatingItems(f);
currentBounds = f.getBounds();
if (desktop instanceof JComponent) {
desktopBounds = ((JComponent)desktop).getVisibleRect();
}
else {
desktopBounds = desktop.getBounds();
desktopBounds.x = desktopBounds.y = 0;
}
desktopGraphics = JComponent.safelyGetGraphics(desktop);
((JInternalFrame)f).isDragging = true;
didDrag = false;
}
}
private void setupDragMode(JComponent f) {
JDesktopPane p = getDesktopPane(f);
Container parent = f.getParent();
dragMode = DEFAULT_DRAG_MODE;
if (p != null) {
String mode = (String)p.getClientProperty("JDesktopPane.dragMode");
if (mode != null && mode.equals("outline")) {
dragMode = OUTLINE_DRAG_MODE;
} else if (mode != null && mode.equals("faster")
&& f instanceof JInternalFrame
&& ((JInternalFrame)f).isOpaque() &&
(parent == null || parent.isOpaque())) {
dragMode = FASTER_DRAG_MODE;
} else {
if (p.getDragMode() == JDesktopPane.OUTLINE_DRAG_MODE ) {
dragMode = OUTLINE_DRAG_MODE;
} else if ( p.getDragMode() == JDesktopPane.LIVE_DRAG_MODE
&& f instanceof JInternalFrame
&& ((JInternalFrame)f).isOpaque()) {
dragMode = FASTER_DRAG_MODE;
} else {
dragMode = DEFAULT_DRAG_MODE;
}
}
}
}
private transient Point currentLoc = null;
/** {@collect.stats}
* Moves the visible location of the frame being dragged
* to the location specified. The means by which this occurs can vary depending
* on the dragging algorithm being used. The actual logical location of the frame
* might not change until <code>endDraggingFrame</code> is called.
*/
public void dragFrame(JComponent f, int newX, int newY) {
if (dragMode == OUTLINE_DRAG_MODE) {
JDesktopPane desktopPane = getDesktopPane(f);
if (desktopPane != null){
Graphics g = JComponent.safelyGetGraphics(desktopPane);
g.setXORMode(Color.white);
if (currentLoc != null) {
g.drawRect(currentLoc.x, currentLoc.y,
f.getWidth()-1, f.getHeight()-1);
}
g.drawRect( newX, newY, f.getWidth()-1, f.getHeight()-1);
currentLoc = new Point (newX, newY);
g.dispose();
}
} else if (dragMode == FASTER_DRAG_MODE) {
dragFrameFaster(f, newX, newY);
} else {
setBoundsForFrame(f, newX, newY, f.getWidth(), f.getHeight());
}
}
// implements javax.swing.DesktopManager
public void endDraggingFrame(JComponent f) {
if ( dragMode == OUTLINE_DRAG_MODE && currentLoc != null) {
setBoundsForFrame(f, currentLoc.x, currentLoc.y, f.getWidth(), f.getHeight() );
currentLoc = null;
} else if (dragMode == FASTER_DRAG_MODE) {
currentBounds = null;
if (desktopGraphics != null) {
desktopGraphics.dispose();
desktopGraphics = null;
}
desktopBounds = null;
((JInternalFrame)f).isDragging = false;
}
}
// implements javax.swing.DesktopManager
public void beginResizingFrame(JComponent f, int direction) {
setupDragMode(f);
}
/** {@collect.stats}
* Calls <code>setBoundsForFrame</code> with the new values.
* @param f the component to be resized
* @param newX the new x-coordinate
* @param newY the new y-coordinate
* @param newWidth the new width
* @param newHeight the new height
*/
public void resizeFrame(JComponent f, int newX, int newY, int newWidth, int newHeight) {
if ( dragMode == DEFAULT_DRAG_MODE || dragMode == FASTER_DRAG_MODE ) {
setBoundsForFrame(f, newX, newY, newWidth, newHeight);
} else {
JDesktopPane desktopPane = getDesktopPane(f);
if (desktopPane != null){
Graphics g = JComponent.safelyGetGraphics(desktopPane);
g.setXORMode(Color.white);
if (currentBounds != null) {
g.drawRect( currentBounds.x, currentBounds.y, currentBounds.width-1, currentBounds.height-1);
}
g.drawRect( newX, newY, newWidth-1, newHeight-1);
currentBounds = new Rectangle (newX, newY, newWidth, newHeight);
g.setPaintMode();
g.dispose();
}
}
}
// implements javax.swing.DesktopManager
public void endResizingFrame(JComponent f) {
if ( dragMode == OUTLINE_DRAG_MODE && currentBounds != null) {
setBoundsForFrame(f, currentBounds.x, currentBounds.y, currentBounds.width, currentBounds.height );
currentBounds = null;
}
}
/** {@collect.stats} This moves the <code>JComponent</code> and repaints the damaged areas. */
public void setBoundsForFrame(JComponent f, int newX, int newY, int newWidth, int newHeight) {
boolean didResize = (f.getWidth() != newWidth || f.getHeight() != newHeight);
f.setBounds(newX, newY, newWidth, newHeight);
if(didResize) {
f.validate();
}
}
/** {@collect.stats} Convenience method to remove the desktopIcon of <b>f</b> is necessary. */
protected void removeIconFor(JInternalFrame f) {
JInternalFrame.JDesktopIcon di = f.getDesktopIcon();
Container c = di.getParent();
if(c != null) {
c.remove(di);
c.repaint(di.getX(), di.getY(), di.getWidth(), di.getHeight());
}
}
/** {@collect.stats} The iconifyFrame() code calls this to determine the proper bounds
* for the desktopIcon.
*/
protected Rectangle getBoundsForIconOf(JInternalFrame f) {
//
// Get the icon for this internal frame and its preferred size
//
JInternalFrame.JDesktopIcon icon = f.getDesktopIcon();
Dimension prefSize = icon.getPreferredSize();
//
// Get the parent bounds and child components.
//
Container c = f.getParent();
if (c == null) {
c = f.getDesktopIcon().getParent();
}
if (c == null) {
/* the frame has not yet been added to the parent; how about (0,0) ?*/
return new Rectangle(0, 0, prefSize.width, prefSize.height);
}
Rectangle parentBounds = c.getBounds();
Component [] components = c.getComponents();
//
// Iterate through valid default icon locations and return the
// first one that does not intersect any other icons.
//
Rectangle availableRectangle = null;
JInternalFrame.JDesktopIcon currentIcon = null;
int x = 0;
int y = parentBounds.height - prefSize.height;
int w = prefSize.width;
int h = prefSize.height;
boolean found = false;
while (!found) {
availableRectangle = new Rectangle(x,y,w,h);
found = true;
for ( int i=0; i<components.length; i++ ) {
//
// Get the icon for this component
//
if ( components[i] instanceof JInternalFrame ) {
currentIcon = ((JInternalFrame)components[i]).getDesktopIcon();
}
else if ( components[i] instanceof JInternalFrame.JDesktopIcon ){
currentIcon = (JInternalFrame.JDesktopIcon)components[i];
} else
/* found a child that's neither an internal frame nor
an icon. I don't believe this should happen, but at
present it does and causes a null pointer exception.
Even when that gets fixed, this code protects against
the npe. hania */
continue;
//
// If this icon intersects the current location, get next location.
//
if ( !currentIcon.equals(icon) ) {
if ( availableRectangle.intersects(currentIcon.getBounds()) ) {
found = false;
break;
}
}
}
if (currentIcon == null)
/* didn't find any useful children above. This probably shouldn't
happen, but this check protects against an npe if it ever does
(and it's happening now) */
return availableRectangle;
x += currentIcon.getBounds().width;
if ( x + w > parentBounds.width ) {
x = 0;
y -= h;
}
}
return(availableRectangle);
}
/** {@collect.stats}
* Stores the bounds of the component just before a maximize call.
* @param f the component about to be resized
* @param r the normal bounds to be saved away
*/
protected void setPreviousBounds(JInternalFrame f, Rectangle r) {
f.setNormalBounds(r);
}
/** {@collect.stats}
* Gets the normal bounds of the component prior to the component
* being maximized.
* @param f the <code>JInternalFrame</code> of interest
* @return the normal bounds of the component
*/
protected Rectangle getPreviousBounds(JInternalFrame f) {
return f.getNormalBounds();
}
/** {@collect.stats}
* Sets that the component has been iconized and the bounds of the
* <code>desktopIcon</code> are valid.
*/
protected void setWasIcon(JInternalFrame f, Boolean value) {
if (value != null) {
f.putClientProperty(HAS_BEEN_ICONIFIED_PROPERTY, value);
}
}
/** {@collect.stats}
* Returns <code>true</code> if the component has been iconized
* and the bounds of the <code>desktopIcon</code> are valid,
* otherwise returns <code>false</code>.
*
* @param f the <code>JInternalFrame</code> of interest
* @return <code>true</code> if the component has been iconized;
* otherwise returns <code>false</code>
*/
protected boolean wasIcon(JInternalFrame f) {
return (f.getClientProperty(HAS_BEEN_ICONIFIED_PROPERTY) == Boolean.TRUE);
}
JDesktopPane getDesktopPane( JComponent frame ) {
JDesktopPane pane = null;
Component c = frame.getParent();
// Find the JDesktopPane
while ( pane == null ) {
if ( c instanceof JDesktopPane ) {
pane = (JDesktopPane)c;
}
else if ( c == null ) {
break;
}
else {
c = c.getParent();
}
}
return pane;
}
// =========== stuff for faster frame dragging ===================
private void dragFrameFaster(JComponent f, int newX, int newY) {
Rectangle previousBounds = new Rectangle(currentBounds.x,
currentBounds.y,
currentBounds.width,
currentBounds.height);
// move the frame
currentBounds.x = newX;
currentBounds.y = newY;
if (didDrag) {
// Only initiate cleanup if we have actually done a drag.
emergencyCleanup(f);
}
else {
didDrag = true;
// We reset the danger field as until now we haven't actually
// moved the internal frame so we don't need to initiate repaint.
((JInternalFrame)f).danger = false;
}
boolean floaterCollision = isFloaterCollision(previousBounds, currentBounds);
// System.out.println(previousBounds);
JComponent parent = (JComponent)f.getParent();
Rectangle visBounds = previousBounds.intersection(desktopBounds);
// System.out.println(previousBounds);
// System.out.println(visBounds);
RepaintManager currentManager = RepaintManager.currentManager(f);
currentManager.beginPaint();
try {
if(!floaterCollision) {
currentManager.copyArea(parent, desktopGraphics, visBounds.x,
visBounds.y,
visBounds.width,
visBounds.height,
newX - previousBounds.x,
newY - previousBounds.y,
true);
}
f.setBounds(currentBounds);
if(floaterCollision) {
// since we couldn't blit we just redraw as fast as possible
// the isDragging mucking is to avoid activating emergency
// cleanup
((JInternalFrame)f).isDragging = false;
parent.paintImmediately(currentBounds);
((JInternalFrame)f).isDragging = true;
}
// fake out the repaint manager. We'll take care of everything
currentManager.markCompletelyClean(parent);
currentManager.markCompletelyClean(f);
// compute the minimal newly exposed area
// if the rects intersect then we use computeDifference. Otherwise
// we'll repaint the entire previous bounds
Rectangle[] dirtyRects = null;
if ( previousBounds.intersects(currentBounds) ) {
dirtyRects = SwingUtilities.computeDifference(previousBounds,
currentBounds);
} else {
dirtyRects = new Rectangle[1];
dirtyRects[0] = previousBounds;
// System.out.println("no intersection");
};
// Fix the damage
for (int i = 0; i < dirtyRects.length; i++) {
parent.paintImmediately(dirtyRects[i]);
}
// new areas of blit were exposed
if ( !(visBounds.equals(previousBounds)) ) {
dirtyRects = SwingUtilities.computeDifference(previousBounds,
desktopBounds);
for (int i = 0; i < dirtyRects.length; i++) {
dirtyRects[i].x += newX - previousBounds.x;
dirtyRects[i].y += newY - previousBounds.y;
((JInternalFrame)f).isDragging = false;
parent.paintImmediately(dirtyRects[i]);
((JInternalFrame)f).isDragging = true;
// System.out.println(dirtyRects[i]);
}
}
} finally {
currentManager.endPaint();
}
}
private boolean isFloaterCollision(Rectangle moveFrom, Rectangle moveTo) {
if (floatingItems.length == 0) {
// System.out.println("no floaters");
return false;
}
for (int i = 0; i < floatingItems.length; i++) {
boolean intersectsFrom = moveFrom.intersects(floatingItems[i]);
if (intersectsFrom) {
return true;
}
boolean intersectsTo = moveTo.intersects(floatingItems[i]);
if (intersectsTo) {
return true;
}
}
return false;
}
private Rectangle[] findFloatingItems(JComponent f) {
Container desktop = f.getParent();
Component[] children = desktop.getComponents();
int i = 0;
for (i = 0; i < children.length; i++) {
if (children[i] == f) {
break;
}
}
// System.out.println(i);
Rectangle[] floaters = new Rectangle[i];
for (i = 0; i < floaters.length; i++) {
floaters[i] = children[i].getBounds();
}
return floaters;
}
/** {@collect.stats}
* This method is here to clean up problems associated
* with a race condition which can occur when the full contents
* of a copyArea's source argument is not available onscreen.
* This uses brute force to clean up in case of possible damage
*/
private void emergencyCleanup(final JComponent f) {
if ( ((JInternalFrame)f).danger ) {
SwingUtilities.invokeLater( new Runnable(){
public void run(){
((JInternalFrame)f).isDragging = false;
f.paintImmediately(0,0,
f.getWidth(),
f.getHeight());
//finalFrame.repaint();
((JInternalFrame)f).isDragging = true;
// System.out.println("repair complete");
}});
((JInternalFrame)f).danger = false;
}
}
}
|
Java
|
/*
* Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.FocusTraversalPolicy;
import java.awt.Component;
import java.awt.Container;
import java.awt.Window;
import java.util.HashMap;
import java.util.HashSet;
import java.io.*;
/** {@collect.stats}
* A FocusTraversalPolicy which provides support for legacy applications which
* handle focus traversal via JComponent.setNextFocusableComponent or by
* installing a custom DefaultFocusManager. If a specific traversal has not
* been hard coded, then that traversal is provided either by the custom
* DefaultFocusManager, or by a wrapped FocusTraversalPolicy instance.
*
* @author David Mendenhall
*/
final class LegacyGlueFocusTraversalPolicy extends FocusTraversalPolicy
implements Serializable
{
private transient FocusTraversalPolicy delegatePolicy;
private transient DefaultFocusManager delegateManager;
private HashMap forwardMap = new HashMap(),
backwardMap = new HashMap();
LegacyGlueFocusTraversalPolicy(FocusTraversalPolicy delegatePolicy) {
this.delegatePolicy = delegatePolicy;
}
LegacyGlueFocusTraversalPolicy(DefaultFocusManager delegateManager) {
this.delegateManager = delegateManager;
}
void setNextFocusableComponent(Component left, Component right) {
forwardMap.put(left, right);
backwardMap.put(right, left);
}
void unsetNextFocusableComponent(Component left, Component right) {
forwardMap.remove(left);
backwardMap.remove(right);
}
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
Component hardCoded = aComponent, prevHardCoded;
HashSet sanity = new HashSet();
do {
prevHardCoded = hardCoded;
hardCoded = (Component)forwardMap.get(hardCoded);
if (hardCoded == null) {
if (delegatePolicy != null &&
prevHardCoded.isFocusCycleRoot(focusCycleRoot)) {
return delegatePolicy.getComponentAfter(focusCycleRoot,
prevHardCoded);
} else if (delegateManager != null) {
return delegateManager.
getComponentAfter(focusCycleRoot, aComponent);
} else {
return null;
}
}
if (sanity.contains(hardCoded)) {
// cycle detected; bail
return null;
}
sanity.add(hardCoded);
} while (!accept(hardCoded));
return hardCoded;
}
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
Component hardCoded = aComponent, prevHardCoded;
HashSet sanity = new HashSet();
do {
prevHardCoded = hardCoded;
hardCoded = (Component)backwardMap.get(hardCoded);
if (hardCoded == null) {
if (delegatePolicy != null &&
prevHardCoded.isFocusCycleRoot(focusCycleRoot)) {
return delegatePolicy.getComponentBefore(focusCycleRoot,
prevHardCoded);
} else if (delegateManager != null) {
return delegateManager.
getComponentBefore(focusCycleRoot, aComponent);
} else {
return null;
}
}
if (sanity.contains(hardCoded)) {
// cycle detected; bail
return null;
}
sanity.add(hardCoded);
} while (!accept(hardCoded));
return hardCoded;
}
public Component getFirstComponent(Container focusCycleRoot) {
if (delegatePolicy != null) {
return delegatePolicy.getFirstComponent(focusCycleRoot);
} else if (delegateManager != null) {
return delegateManager.getFirstComponent(focusCycleRoot);
} else {
return null;
}
}
public Component getLastComponent(Container focusCycleRoot) {
if (delegatePolicy != null) {
return delegatePolicy.getLastComponent(focusCycleRoot);
} else if (delegateManager != null) {
return delegateManager.getLastComponent(focusCycleRoot);
} else {
return null;
}
}
public Component getDefaultComponent(Container focusCycleRoot) {
if (delegatePolicy != null) {
return delegatePolicy.getDefaultComponent(focusCycleRoot);
} else {
return getFirstComponent(focusCycleRoot);
}
}
private boolean accept(Component aComponent) {
if (!(aComponent.isVisible() && aComponent.isDisplayable() &&
aComponent.isFocusable() && aComponent.isEnabled())) {
return false;
}
// Verify that the Component is recursively enabled. Disabling a
// heavyweight Container disables its children, whereas disabling
// a lightweight Container does not.
if (!(aComponent instanceof Window)) {
for (Container enableTest = aComponent.getParent();
enableTest != null;
enableTest = enableTest.getParent())
{
if (!(enableTest.isEnabled() || enableTest.isLightweight())) {
return false;
}
if (enableTest instanceof Window) {
break;
}
}
}
return true;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (delegatePolicy instanceof Serializable) {
out.writeObject(delegatePolicy);
} else {
out.writeObject(null);
}
if (delegateManager instanceof Serializable) {
out.writeObject(delegateManager);
} else {
out.writeObject(null);
}
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
delegatePolicy = (FocusTraversalPolicy)in.readObject();
delegateManager = (DefaultFocusManager)in.readObject();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.awt.im.InputContext;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.UIManager;
import javax.swing.event.*;
import javax.swing.plaf.UIResource;
import javax.swing.text.*;
/** {@collect.stats}
* <code>JFormattedTextField</code> extends <code>JTextField</code> adding
* support for formatting arbitrary values, as well as retrieving a particular
* object once the user has edited the text. The following illustrates
* configuring a <code>JFormattedTextField</code> to edit dates:
* <pre>
* JFormattedTextField ftf = new JFormattedTextField();
* ftf.setValue(new Date());
* </pre>
* <p>
* Once a <code>JFormattedTextField</code> has been created, you can
* listen for editing changes by way of adding
* a <code>PropertyChangeListener</code> and listening for
* <code>PropertyChangeEvent</code>s with the property name <code>value</code>.
* <p>
* <code>JFormattedTextField</code> allows
* configuring what action should be taken when focus is lost. The possible
* configurations are:
* <table summary="Possible JFormattedTextField configurations and their descriptions">
* <tr><th><p align="left">Value</p></th><th><p align="left">Description</p></th></tr>
* <tr><td>JFormattedTextField.REVERT
* <td>Revert the display to match that of <code>getValue</code>,
* possibly losing the current edit.
* <tr><td>JFormattedTextField.COMMIT
* <td>Commits the current value. If the value being edited
* isn't considered a legal value by the
* <code>AbstractFormatter</code> that is, a
* <code>ParseException</code> is thrown, then the value
* will not change, and then edited value will persist.
* <tr><td>JFormattedTextField.COMMIT_OR_REVERT
* <td>Similar to <code>COMMIT</code>, but if the value isn't
* legal, behave like <code>REVERT</code>.
* <tr><td>JFormattedTextField.PERSIST
* <td>Do nothing, don't obtain a new
* <code>AbstractFormatter</code>, and don't update the value.
* </table>
* The default is <code>JFormattedTextField.COMMIT_OR_REVERT</code>,
* refer to {@link #setFocusLostBehavior} for more information on this.
* <p>
* <code>JFormattedTextField</code> allows the focus to leave, even if
* the currently edited value is invalid. To lock the focus down while the
* <code>JFormattedTextField</code> is an invalid edit state
* you can attach an <code>InputVerifier</code>. The following code snippet
* shows a potential implementation of such an <code>InputVerifier</code>:
* <pre>
* public class FormattedTextFieldVerifier extends InputVerifier {
* public boolean verify(JComponent input) {
* if (input instanceof JFormattedTextField) {
* JFormattedTextField ftf = (JFormattedTextField)input;
* AbstractFormatter formatter = ftf.getFormatter();
* if (formatter != null) {
* String text = ftf.getText();
* try {
* formatter.stringToValue(text);
* return true;
* } catch (ParseException pe) {
* return false;
* }
* }
* }
* return true;
* }
* public boolean shouldYieldFocus(JComponent input) {
* return verify(input);
* }
* }
* </pre>
* <p>
* Alternatively, you could invoke <code>commitEdit</code>, which would also
* commit the value.
* <p>
* <code>JFormattedTextField</code> does not do the formatting it self,
* rather formatting is done through an instance of
* <code>JFormattedTextField.AbstractFormatter</code> which is obtained from
* an instance of <code>JFormattedTextField.AbstractFormatterFactory</code>.
* Instances of <code>JFormattedTextField.AbstractFormatter</code> are
* notified when they become active by way of the
* <code>install</code> method, at which point the
* <code>JFormattedTextField.AbstractFormatter</code> can install whatever
* it needs to, typically a <code>DocumentFilter</code>. Similarly when
* <code>JFormattedTextField</code> no longer
* needs the <code>AbstractFormatter</code>, it will invoke
* <code>uninstall</code>.
* <p>
* <code>JFormattedTextField</code> typically
* queries the <code>AbstractFormatterFactory</code> for an
* <code>AbstractFormat</code> when it gains or loses focus. Although this
* can change based on the focus lost policy. If the focus lost
* policy is <code>JFormattedTextField.PERSIST</code>
* and the <code>JFormattedTextField</code> has been edited, the
* <code>AbstractFormatterFactory</code> will not be queried until the
* value has been commited. Similarly if the focus lost policy is
* <code>JFormattedTextField.COMMIT</code> and an exception
* is thrown from <code>stringToValue</code>, the
* <code>AbstractFormatterFactory</code> will not be querired when focus is
* lost or gained.
* <p>
* <code>JFormattedTextField.AbstractFormatter</code>
* is also responsible for determining when values are commited to
* the <code>JFormattedTextField</code>. Some
* <code>JFormattedTextField.AbstractFormatter</code>s will make new values
* available on every edit, and others will never commit the value. You can
* force the current value to be obtained
* from the current <code>JFormattedTextField.AbstractFormatter</code>
* by way of invoking <code>commitEdit</code>. <code>commitEdit</code> will
* be invoked whenever return is pressed in the
* <code>JFormattedTextField</code>.
* <p>
* If an <code>AbstractFormatterFactory</code> has not been explicitly
* set, one will be set based on the <code>Class</code> of the value type after
* <code>setValue</code> has been invoked (assuming value is non-null).
* For example, in the following code an appropriate
* <code>AbstractFormatterFactory</code> and <code>AbstractFormatter</code>
* will be created to handle formatting of numbers:
* <pre>
* JFormattedTextField tf = new JFormattedTextField();
* tf.setValue(new Number(100));
* </pre>
* <p>
* <strong>Warning:</strong> As the <code>AbstractFormatter</code> will
* typically install a <code>DocumentFilter</code> on the
* <code>Document</code>, and a <code>NavigationFilter</code> on the
* <code>JFormattedTextField</code> you should not install your own. If you do,
* you are likely to see odd behavior in that the editing policy of the
* <code>AbstractFormatter</code> will not be enforced.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @since 1.4
*/
public class JFormattedTextField extends JTextField {
private static final String uiClassID = "FormattedTextFieldUI";
private static final Action[] defaultActions =
{ new CommitAction(), new CancelAction() };
/** {@collect.stats}
* Constant identifying that when focus is lost,
* <code>commitEdit</code> should be invoked. If in commiting the
* new value a <code>ParseException</code> is thrown, the invalid
* value will remain.
*
* @see #setFocusLostBehavior
*/
public static final int COMMIT = 0;
/** {@collect.stats}
* Constant identifying that when focus is lost,
* <code>commitEdit</code> should be invoked. If in commiting the new
* value a <code>ParseException</code> is thrown, the value will be
* reverted.
*
* @see #setFocusLostBehavior
*/
public static final int COMMIT_OR_REVERT = 1;
/** {@collect.stats}
* Constant identifying that when focus is lost, editing value should
* be reverted to current value set on the
* <code>JFormattedTextField</code>.
*
* @see #setFocusLostBehavior
*/
public static final int REVERT = 2;
/** {@collect.stats}
* Constant identifying that when focus is lost, the edited value
* should be left.
*
* @see #setFocusLostBehavior
*/
public static final int PERSIST = 3;
/** {@collect.stats}
* Factory used to obtain an instance of AbstractFormatter.
*/
private AbstractFormatterFactory factory;
/** {@collect.stats}
* Object responsible for formatting the current value.
*/
private AbstractFormatter format;
/** {@collect.stats}
* Last valid value.
*/
private Object value;
/** {@collect.stats}
* True while the value being edited is valid.
*/
private boolean editValid;
/** {@collect.stats}
* Behavior when focus is lost.
*/
private int focusLostBehavior;
/** {@collect.stats}
* Indicates the current value has been edited.
*/
private boolean edited;
/** {@collect.stats}
* Used to set the dirty state.
*/
private DocumentListener documentListener;
/** {@collect.stats}
* Masked used to set the AbstractFormatterFactory.
*/
private Object mask;
/** {@collect.stats}
* ActionMap that the TextFormatter Actions are added to.
*/
private ActionMap textFormatterActionMap;
/** {@collect.stats}
* Indicates the input method composed text is in the document
*/
private boolean composedTextExists = false;
/** {@collect.stats}
* A handler for FOCUS_LOST event
*/
private FocusLostHandler focusLostHandler;
/** {@collect.stats}
* Creates a <code>JFormattedTextField</code> with no
* <code>AbstractFormatterFactory</code>. Use <code>setMask</code> or
* <code>setFormatterFactory</code> to configure the
* <code>JFormattedTextField</code> to edit a particular type of
* value.
*/
public JFormattedTextField() {
super();
enableEvents(AWTEvent.FOCUS_EVENT_MASK);
setFocusLostBehavior(COMMIT_OR_REVERT);
}
/** {@collect.stats}
* Creates a JFormattedTextField with the specified value. This will
* create an <code>AbstractFormatterFactory</code> based on the
* type of <code>value</code>.
*
* @param value Initial value for the JFormattedTextField
*/
public JFormattedTextField(Object value) {
this();
setValue(value);
}
/** {@collect.stats}
* Creates a <code>JFormattedTextField</code>. <code>format</code> is
* wrapped in an appropriate <code>AbstractFormatter</code> which is
* then wrapped in an <code>AbstractFormatterFactory</code>.
*
* @param format Format used to look up an AbstractFormatter
*/
public JFormattedTextField(java.text.Format format) {
this();
setFormatterFactory(getDefaultFormatterFactory(format));
}
/** {@collect.stats}
* Creates a <code>JFormattedTextField</code> with the specified
* <code>AbstractFormatter</code>. The <code>AbstractFormatter</code>
* is placed in an <code>AbstractFormatterFactory</code>.
*
* @param formatter AbstractFormatter to use for formatting.
*/
public JFormattedTextField(AbstractFormatter formatter) {
this(new DefaultFormatterFactory(formatter));
}
/** {@collect.stats}
* Creates a <code>JFormattedTextField</code> with the specified
* <code>AbstractFormatterFactory</code>.
*
* @param factory AbstractFormatterFactory used for formatting.
*/
public JFormattedTextField(AbstractFormatterFactory factory) {
this();
setFormatterFactory(factory);
}
/** {@collect.stats}
* Creates a <code>JFormattedTextField</code> with the specified
* <code>AbstractFormatterFactory</code> and initial value.
*
* @param factory <code>AbstractFormatterFactory</code> used for
* formatting.
* @param currentValue Initial value to use
*/
public JFormattedTextField(AbstractFormatterFactory factory,
Object currentValue) {
this(currentValue);
setFormatterFactory(factory);
}
/** {@collect.stats}
* Sets the behavior when focus is lost. This will be one of
* <code>JFormattedTextField.COMMIT_OR_REVERT</code>,
* <code>JFormattedTextField.REVERT</code>,
* <code>JFormattedTextField.COMMIT</code> or
* <code>JFormattedTextField.PERSIST</code>
* Note that some <code>AbstractFormatter</code>s may push changes as
* they occur, so that the value of this will have no effect.
* <p>
* This will throw an <code>IllegalArgumentException</code> if the object
* passed in is not one of the afore mentioned values.
* <p>
* The default value of this property is
* <code>JFormattedTextField.COMMIT_OR_REVERT</code>.
*
* @param behavior Identifies behavior when focus is lost
* @throws IllegalArgumentException if behavior is not one of the known
* values
* @beaninfo
* enum: COMMIT JFormattedTextField.COMMIT
* COMMIT_OR_REVERT JFormattedTextField.COMMIT_OR_REVERT
* REVERT JFormattedTextField.REVERT
* PERSIST JFormattedTextField.PERSIST
* description: Behavior when component loses focus
*/
public void setFocusLostBehavior(int behavior) {
if (behavior != COMMIT && behavior != COMMIT_OR_REVERT &&
behavior != PERSIST && behavior != REVERT) {
throw new IllegalArgumentException("setFocusLostBehavior must be one of: JFormattedTextField.COMMIT, JFormattedTextField.COMMIT_OR_REVERT, JFormattedTextField.PERSIST or JFormattedTextField.REVERT");
}
focusLostBehavior = behavior;
}
/** {@collect.stats}
* Returns the behavior when focus is lost. This will be one of
* <code>COMMIT_OR_REVERT</code>,
* <code>COMMIT</code>,
* <code>REVERT</code> or
* <code>PERSIST</code>
* Note that some <code>AbstractFormatter</code>s may push changes as
* they occur, so that the value of this will have no effect.
*
* @return returns behavior when focus is lost
*/
public int getFocusLostBehavior() {
return focusLostBehavior;
}
/** {@collect.stats}
* Sets the <code>AbstractFormatterFactory</code>.
* <code>AbstractFormatterFactory</code> is
* able to return an instance of <code>AbstractFormatter</code> that is
* used to format a value for display, as well an enforcing an editing
* policy.
* <p>
* If you have not explicitly set an <code>AbstractFormatterFactory</code>
* by way of this method (or a constructor) an
* <code>AbstractFormatterFactory</code> and consequently an
* <code>AbstractFormatter</code> will be used based on the
* <code>Class</code> of the value. <code>NumberFormatter</code> will
* be used for <code>Number</code>s, <code>DateFormatter</code> will
* be used for <code>Dates</code>, otherwise <code>DefaultFormatter</code>
* will be used.
* <p>
* This is a JavaBeans bound property.
*
* @param tf <code>AbstractFormatterFactory</code> used to lookup
* instances of <code>AbstractFormatter</code>
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: AbstractFormatterFactory, responsible for returning an
* AbstractFormatter that can format the current value.
*/
public void setFormatterFactory(AbstractFormatterFactory tf) {
AbstractFormatterFactory oldFactory = factory;
factory = tf;
firePropertyChange("formatterFactory", oldFactory, tf);
setValue(getValue(), true, false);
}
/** {@collect.stats}
* Returns the current <code>AbstractFormatterFactory</code>.
*
* @see #setFormatterFactory
* @return <code>AbstractFormatterFactory</code> used to determine
* <code>AbstractFormatter</code>s
*/
public AbstractFormatterFactory getFormatterFactory() {
return factory;
}
/** {@collect.stats}
* Sets the current <code>AbstractFormatter</code>.
* <p>
* You should not normally invoke this, instead set the
* <code>AbstractFormatterFactory</code> or set the value.
* <code>JFormattedTextField</code> will
* invoke this as the state of the <code>JFormattedTextField</code>
* changes and requires the value to be reset.
* <code>JFormattedTextField</code> passes in the
* <code>AbstractFormatter</code> obtained from the
* <code>AbstractFormatterFactory</code>.
* <p>
* This is a JavaBeans bound property.
*
* @see #setFormatterFactory
* @param format AbstractFormatter to use for formatting
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: TextFormatter, responsible for formatting the current value
*/
protected void setFormatter(AbstractFormatter format) {
AbstractFormatter oldFormat = this.format;
if (oldFormat != null) {
oldFormat.uninstall();
}
setEditValid(true);
this.format = format;
if (format != null) {
format.install(this);
}
setEdited(false);
firePropertyChange("textFormatter", oldFormat, format);
}
/** {@collect.stats}
* Returns the <code>AbstractFormatter</code> that is used to format and
* parse the current value.
*
* @return AbstractFormatter used for formatting
*/
public AbstractFormatter getFormatter() {
return format;
}
/** {@collect.stats}
* Sets the value that will be formatted by an
* <code>AbstractFormatter</code> obtained from the current
* <code>AbstractFormatterFactory</code>. If no
* <code>AbstractFormatterFactory</code> has been specified, this will
* attempt to create one based on the type of <code>value</code>.
* <p>
* The default value of this property is null.
* <p>
* This is a JavaBeans bound property.
*
* @param value Current value to display
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The value to be formatted.
*/
public void setValue(Object value) {
if (value != null && getFormatterFactory() == null) {
setFormatterFactory(getDefaultFormatterFactory(value));
}
setValue(value, true, true);
}
/** {@collect.stats}
* Returns the last valid value. Based on the editing policy of
* the <code>AbstractFormatter</code> this may not return the current
* value. The currently edited value can be obtained by invoking
* <code>commitEdit</code> followed by <code>getValue</code>.
*
* @return Last valid value
*/
public Object getValue() {
return value;
}
/** {@collect.stats}
* Forces the current value to be taken from the
* <code>AbstractFormatter</code> and set as the current value.
* This has no effect if there is no current
* <code>AbstractFormatter</code> installed.
*
* @throws ParseException if the <code>AbstractFormatter</code> is not able
* to format the current value
*/
public void commitEdit() throws ParseException {
AbstractFormatter format = getFormatter();
if (format != null) {
setValue(format.stringToValue(getText()), false, true);
}
}
/** {@collect.stats}
* Sets the validity of the edit on the receiver. You should not normally
* invoke this. This will be invoked by the
* <code>AbstractFormatter</code> as the user edits the value.
* <p>
* Not all formatters will allow the component to get into an invalid
* state, and thus this may never be invoked.
* <p>
* Based on the look and feel this may visually change the state of
* the receiver.
*
* @param isValid boolean indicating if the currently edited value is
* valid.
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: True indicates the edited value is valid
*/
private void setEditValid(boolean isValid) {
if (isValid != editValid) {
editValid = isValid;
firePropertyChange("editValid", Boolean.valueOf(!isValid),
Boolean.valueOf(isValid));
}
}
/** {@collect.stats}
* Returns true if the current value being edited is valid. The value of
* this is managed by the current <code>AbstractFormatter</code>, as such
* there is no public setter for it.
*
* @return true if the current value being edited is valid.
*/
public boolean isEditValid() {
return editValid;
}
/** {@collect.stats}
* Invoked when the user inputs an invalid value. This gives the
* component a chance to provide feedback. The default
* implementation beeps.
*/
protected void invalidEdit() {
UIManager.getLookAndFeel().provideErrorFeedback(JFormattedTextField.this);
}
/** {@collect.stats}
* Processes any input method events, such as
* <code>InputMethodEvent.INPUT_METHOD_TEXT_CHANGED</code> or
* <code>InputMethodEvent.CARET_POSITION_CHANGED</code>.
*
* @param e the <code>InputMethodEvent</code>
* @see InputMethodEvent
*/
protected void processInputMethodEvent(InputMethodEvent e) {
AttributedCharacterIterator text = e.getText();
int commitCount = e.getCommittedCharacterCount();
// Keep track of the composed text
if (text != null) {
int begin = text.getBeginIndex();
int end = text.getEndIndex();
composedTextExists = ((end - begin) > commitCount);
} else {
composedTextExists = false;
}
super.processInputMethodEvent(e);
}
/** {@collect.stats}
* Processes any focus events, such as
* <code>FocusEvent.FOCUS_GAINED</code> or
* <code>FocusEvent.FOCUS_LOST</code>.
*
* @param e the <code>FocusEvent</code>
* @see FocusEvent
*/
protected void processFocusEvent(FocusEvent e) {
super.processFocusEvent(e);
// ignore temporary focus event
if (e.isTemporary()) {
return;
}
if (isEdited() && e.getID() == FocusEvent.FOCUS_LOST) {
InputContext ic = getInputContext();
if (focusLostHandler == null) {
focusLostHandler = new FocusLostHandler();
}
// if there is a composed text, process it first
if ((ic != null) && composedTextExists) {
ic.endComposition();
EventQueue.invokeLater(focusLostHandler);
} else {
focusLostHandler.run();
}
}
else if (!isEdited()) {
// reformat
setValue(getValue(), true, true);
}
}
/** {@collect.stats}
* FOCUS_LOST behavior implementation
*/
private class FocusLostHandler implements Runnable, Serializable {
public void run() {
int fb = JFormattedTextField.this.getFocusLostBehavior();
if (fb == JFormattedTextField.COMMIT ||
fb == JFormattedTextField.COMMIT_OR_REVERT) {
try {
JFormattedTextField.this.commitEdit();
// Give it a chance to reformat.
JFormattedTextField.this.setValue(
JFormattedTextField.this.getValue(), true, true);
} catch (ParseException pe) {
if (fb == JFormattedTextField.this.COMMIT_OR_REVERT) {
JFormattedTextField.this.setValue(
JFormattedTextField.this.getValue(), true, true);
}
}
}
else if (fb == JFormattedTextField.REVERT) {
JFormattedTextField.this.setValue(
JFormattedTextField.this.getValue(), true, true);
}
}
}
/** {@collect.stats}
* Fetches the command list for the editor. This is
* the list of commands supported by the plugged-in UI
* augmented by the collection of commands that the
* editor itself supports. These are useful for binding
* to events, such as in a keymap.
*
* @return the command list
*/
public Action[] getActions() {
return TextAction.augmentList(super.getActions(), defaultActions);
}
/** {@collect.stats}
* Gets the class ID for a UI.
*
* @return the string "FormattedTextFieldUI"
* @see JComponent#getUIClassID
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Associates the editor with a text document.
* The currently registered factory is used to build a view for
* the document, which gets displayed by the editor after revalidation.
* A PropertyChange event ("document") is propagated to each listener.
*
* @param doc the document to display/edit
* @see #getDocument
* @beaninfo
* description: the text document model
* bound: true
* expert: true
*/
public void setDocument(Document doc) {
if (documentListener != null && getDocument() != null) {
getDocument().removeDocumentListener(documentListener);
}
super.setDocument(doc);
if (documentListener == null) {
documentListener = new DocumentHandler();
}
doc.addDocumentListener(documentListener);
}
/*
* See readObject and writeObject in JComponent for more
* information about serialization in Swing.
*
* @param s Stream to write to
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Resets the Actions that come from the TextFormatter to
* <code>actions</code>.
*/
private void setFormatterActions(Action[] actions) {
if (actions == null) {
if (textFormatterActionMap != null) {
textFormatterActionMap.clear();
}
}
else {
if (textFormatterActionMap == null) {
ActionMap map = getActionMap();
textFormatterActionMap = new ActionMap();
while (map != null) {
ActionMap parent = map.getParent();
if (parent instanceof UIResource || parent == null) {
map.setParent(textFormatterActionMap);
textFormatterActionMap.setParent(parent);
break;
}
map = parent;
}
}
for (int counter = actions.length - 1; counter >= 0;
counter--) {
Object key = actions[counter].getValue(Action.NAME);
if (key != null) {
textFormatterActionMap.put(key, actions[counter]);
}
}
}
}
/** {@collect.stats}
* Does the setting of the value. If <code>createFormat</code> is true,
* this will also obtain a new <code>AbstractFormatter</code> from the
* current factory. The property change event will be fired if
* <code>firePC</code> is true.
*/
private void setValue(Object value, boolean createFormat, boolean firePC) {
Object oldValue = this.value;
this.value = value;
if (createFormat) {
AbstractFormatterFactory factory = getFormatterFactory();
AbstractFormatter atf;
if (factory != null) {
atf = factory.getFormatter(this);
}
else {
atf = null;
}
setFormatter(atf);
}
else {
// Assumed to be valid
setEditValid(true);
}
setEdited(false);
if (firePC) {
firePropertyChange("value", oldValue, value);
}
}
/** {@collect.stats}
* Sets the edited state of the receiver.
*/
private void setEdited(boolean edited) {
this.edited = edited;
}
/** {@collect.stats}
* Returns true if the receiver has been edited.
*/
private boolean isEdited() {
return edited;
}
/** {@collect.stats}
* Returns an AbstractFormatterFactory suitable for the passed in
* Object type.
*/
private AbstractFormatterFactory getDefaultFormatterFactory(Object type) {
if (type instanceof DateFormat) {
return new DefaultFormatterFactory(new DateFormatter
((DateFormat)type));
}
if (type instanceof NumberFormat) {
return new DefaultFormatterFactory(new NumberFormatter(
(NumberFormat)type));
}
if (type instanceof Format) {
return new DefaultFormatterFactory(new InternationalFormatter(
(Format)type));
}
if (type instanceof Date) {
return new DefaultFormatterFactory(new DateFormatter());
}
if (type instanceof Number) {
AbstractFormatter displayFormatter = new NumberFormatter();
((NumberFormatter)displayFormatter).setValueClass(type.getClass());
AbstractFormatter editFormatter = new NumberFormatter(
new DecimalFormat("#.#"));
((NumberFormatter)editFormatter).setValueClass(type.getClass());
return new DefaultFormatterFactory(displayFormatter,
displayFormatter,editFormatter);
}
return new DefaultFormatterFactory(new DefaultFormatter());
}
/** {@collect.stats}
* Instances of <code>AbstractFormatterFactory</code> are used by
* <code>JFormattedTextField</code> to obtain instances of
* <code>AbstractFormatter</code> which in turn are used to format values.
* <code>AbstractFormatterFactory</code> can return different
* <code>AbstractFormatter</code>s based on the state of the
* <code>JFormattedTextField</code>, perhaps returning different
* <code>AbstractFormatter</code>s when the
* <code>JFormattedTextField</code> has focus vs when it
* doesn't have focus.
* @since 1.4
*/
public static abstract class AbstractFormatterFactory {
/** {@collect.stats}
* Returns an <code>AbstractFormatter</code> that can handle formatting
* of the passed in <code>JFormattedTextField</code>.
*
* @param tf JFormattedTextField requesting AbstractFormatter
* @return AbstractFormatter to handle formatting duties, a null
* return value implies the JFormattedTextField should behave
* like a normal JTextField
*/
public abstract AbstractFormatter getFormatter(JFormattedTextField tf);
}
/** {@collect.stats}
* Instances of <code>AbstractFormatter</code> are used by
* <code>JFormattedTextField</code> to handle the conversion both
* from an Object to a String, and back from a String to an Object.
* <code>AbstractFormatter</code>s can also enfore editing policies,
* or navigation policies, or manipulate the
* <code>JFormattedTextField</code> in any way it sees fit to
* enforce the desired policy.
* <p>
* An <code>AbstractFormatter</code> can only be active in
* one <code>JFormattedTextField</code> at a time.
* <code>JFormattedTextField</code> invokes
* <code>install</code> when it is ready to use it followed
* by <code>uninstall</code> when done. Subclasses
* that wish to install additional state should override
* <code>install</code> and message super appropriately.
* <p>
* Subclasses must override the conversion methods
* <code>stringToValue</code> and <code>valueToString</code>. Optionally
* they can override <code>getActions</code>,
* <code>getNavigationFilter</code> and <code>getDocumentFilter</code>
* to restrict the <code>JFormattedTextField</code> in a particular
* way.
* <p>
* Subclasses that allow the <code>JFormattedTextField</code> to be in
* a temporarily invalid state should invoke <code>setEditValid</code>
* at the appropriate times.
* @since 1.4
*/
public static abstract class AbstractFormatter implements Serializable {
private JFormattedTextField ftf;
/** {@collect.stats}
* Installs the <code>AbstractFormatter</code> onto a particular
* <code>JFormattedTextField</code>.
* This will invoke <code>valueToString</code> to convert the
* current value from the <code>JFormattedTextField</code> to
* a String. This will then install the <code>Action</code>s from
* <code>getActions</code>, the <code>DocumentFilter</code>
* returned from <code>getDocumentFilter</code> and the
* <code>NavigationFilter</code> returned from
* <code>getNavigationFilter</code> onto the
* <code>JFormattedTextField</code>.
* <p>
* Subclasses will typically only need to override this if they
* wish to install additional listeners on the
* <code>JFormattedTextField</code>.
* <p>
* If there is a <code>ParseException</code> in converting the
* current value to a String, this will set the text to an empty
* String, and mark the <code>JFormattedTextField</code> as being
* in an invalid state.
* <p>
* While this is a public method, this is typically only useful
* for subclassers of <code>JFormattedTextField</code>.
* <code>JFormattedTextField</code> will invoke this method at
* the appropriate times when the value changes, or its internal
* state changes. You will only need to invoke this yourself if
* you are subclassing <code>JFormattedTextField</code> and
* installing/uninstalling <code>AbstractFormatter</code> at a
* different time than <code>JFormattedTextField</code> does.
*
* @param ftf JFormattedTextField to format for, may be null indicating
* uninstall from current JFormattedTextField.
*/
public void install(JFormattedTextField ftf) {
if (this.ftf != null) {
uninstall();
}
this.ftf = ftf;
if (ftf != null) {
try {
ftf.setText(valueToString(ftf.getValue()));
} catch (ParseException pe) {
ftf.setText("");
setEditValid(false);
}
installDocumentFilter(getDocumentFilter());
ftf.setNavigationFilter(getNavigationFilter());
ftf.setFormatterActions(getActions());
}
}
/** {@collect.stats}
* Uninstalls any state the <code>AbstractFormatter</code> may have
* installed on the <code>JFormattedTextField</code>. This resets the
* <code>DocumentFilter</code>, <code>NavigationFilter</code>
* and additional <code>Action</code>s installed on the
* <code>JFormattedTextField</code>.
*/
public void uninstall() {
if (this.ftf != null) {
installDocumentFilter(null);
this.ftf.setNavigationFilter(null);
this.ftf.setFormatterActions(null);
}
}
/** {@collect.stats}
* Parses <code>text</code> returning an arbitrary Object. Some
* formatters may return null.
*
* @throws ParseException if there is an error in the conversion
* @param text String to convert
* @return Object representation of text
*/
public abstract Object stringToValue(String text) throws
ParseException;
/** {@collect.stats}
* Returns the string value to display for <code>value</code>.
*
* @throws ParseException if there is an error in the conversion
* @param value Value to convert
* @return String representation of value
*/
public abstract String valueToString(Object value) throws
ParseException;
/** {@collect.stats}
* Returns the current <code>JFormattedTextField</code> the
* <code>AbstractFormatter</code> is installed on.
*
* @return JFormattedTextField formatting for.
*/
protected JFormattedTextField getFormattedTextField() {
return ftf;
}
/** {@collect.stats}
* This should be invoked when the user types an invalid character.
* This forwards the call to the current JFormattedTextField.
*/
protected void invalidEdit() {
JFormattedTextField ftf = getFormattedTextField();
if (ftf != null) {
ftf.invalidEdit();
}
}
/** {@collect.stats}
* Invoke this to update the <code>editValid</code> property of the
* <code>JFormattedTextField</code>. If you an enforce a policy
* such that the <code>JFormattedTextField</code> is always in a
* valid state, you will never need to invoke this.
*
* @param valid Valid state of the JFormattedTextField
*/
protected void setEditValid(boolean valid) {
JFormattedTextField ftf = getFormattedTextField();
if (ftf != null) {
ftf.setEditValid(valid);
}
}
/** {@collect.stats}
* Subclass and override if you wish to provide a custom set of
* <code>Action</code>s. <code>install</code> will install these
* on the <code>JFormattedTextField</code>'s <code>ActionMap</code>.
*
* @return Array of Actions to install on JFormattedTextField
*/
protected Action[] getActions() {
return null;
}
/** {@collect.stats}
* Subclass and override if you wish to provide a
* <code>DocumentFilter</code> to restrict what can be input.
* <code>install</code> will install the returned value onto
* the <code>JFormattedTextField</code>.
*
* @return DocumentFilter to restrict edits
*/
protected DocumentFilter getDocumentFilter() {
return null;
}
/** {@collect.stats}
* Subclass and override if you wish to provide a filter to restrict
* where the user can navigate to.
* <code>install</code> will install the returned value onto
* the <code>JFormattedTextField</code>.
*
* @return NavigationFilter to restrict navigation
*/
protected NavigationFilter getNavigationFilter() {
return null;
}
/** {@collect.stats}
* Clones the <code>AbstractFormatter</code>. The returned instance
* is not associated with a <code>JFormattedTextField</code>.
*
* @return Copy of the AbstractFormatter
*/
protected Object clone() throws CloneNotSupportedException {
AbstractFormatter formatter = (AbstractFormatter)super.clone();
formatter.ftf = null;
return formatter;
}
/** {@collect.stats}
* Installs the <code>DocumentFilter</code> <code>filter</code>
* onto the current <code>JFormattedTextField</code>.
*
* @param filter DocumentFilter to install on the Document.
*/
private void installDocumentFilter(DocumentFilter filter) {
JFormattedTextField ftf = getFormattedTextField();
if (ftf != null) {
Document doc = ftf.getDocument();
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).setDocumentFilter(filter);
}
doc.putProperty(DocumentFilter.class, null);
}
}
}
/** {@collect.stats}
* Used to commit the edit. This extends JTextField.NotifyAction
* so that <code>isEnabled</code> is true while a JFormattedTextField
* has focus, and extends <code>actionPerformed</code> to invoke
* commitEdit.
*/
static class CommitAction extends JTextField.NotifyAction {
public void actionPerformed(ActionEvent e) {
JTextComponent target = getFocusedComponent();
if (target instanceof JFormattedTextField) {
// Attempt to commit the value
try {
((JFormattedTextField)target).commitEdit();
} catch (ParseException pe) {
((JFormattedTextField)target).invalidEdit();
// value not commited, don't notify ActionListeners
return;
}
}
// Super behavior.
super.actionPerformed(e);
}
public boolean isEnabled() {
JTextComponent target = getFocusedComponent();
if (target instanceof JFormattedTextField) {
JFormattedTextField ftf = (JFormattedTextField)target;
if (!ftf.isEdited()) {
return false;
}
return true;
}
return super.isEnabled();
}
}
/** {@collect.stats}
* CancelAction will reset the value in the JFormattedTextField when
* <code>actionPerformed</code> is invoked. It will only be
* enabled if the focused component is an instance of
* JFormattedTextField.
*/
private static class CancelAction extends TextAction {
public CancelAction() {
super("reset-field-edit");
}
public void actionPerformed(ActionEvent e) {
JTextComponent target = getFocusedComponent();
if (target instanceof JFormattedTextField) {
JFormattedTextField ftf = (JFormattedTextField)target;
ftf.setValue(ftf.getValue());
}
}
public boolean isEnabled() {
JTextComponent target = getFocusedComponent();
if (target instanceof JFormattedTextField) {
JFormattedTextField ftf = (JFormattedTextField)target;
if (!ftf.isEdited()) {
return false;
}
return true;
}
return super.isEnabled();
}
}
/** {@collect.stats}
* Sets the dirty state as the document changes.
*/
private class DocumentHandler implements DocumentListener, Serializable {
public void insertUpdate(DocumentEvent e) {
setEdited(true);
}
public void removeUpdate(DocumentEvent e) {
setEdited(true);
}
public void changedUpdate(DocumentEvent e) {}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.event.*;
import java.io.Serializable;
import java.util.EventListener;
/** {@collect.stats}
* A generic implementation of BoundedRangeModel.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author David Kloba
* @author Hans Muller
* @see BoundedRangeModel
*/
public class DefaultBoundedRangeModel implements BoundedRangeModel, Serializable
{
/** {@collect.stats}
* Only one <code>ChangeEvent</code> is needed per model instance since the
* event's only (read-only) state is the source property. The source
* of events generated here is always "this".
*/
protected transient ChangeEvent changeEvent = null;
/** {@collect.stats} The listeners waiting for model changes. */
protected EventListenerList listenerList = new EventListenerList();
private int value = 0;
private int extent = 0;
private int min = 0;
private int max = 100;
private boolean isAdjusting = false;
/** {@collect.stats}
* Initializes all of the properties with default values.
* Those values are:
* <ul>
* <li><code>value</code> = 0
* <li><code>extent</code> = 0
* <li><code>minimum</code> = 0
* <li><code>maximum</code> = 100
* <li><code>adjusting</code> = false
* </ul>
*/
public DefaultBoundedRangeModel() {
}
/** {@collect.stats}
* Initializes value, extent, minimum and maximum. Adjusting is false.
* Throws an <code>IllegalArgumentException</code> if the following
* constraints aren't satisfied:
* <pre>
* min <= value <= value+extent <= max
* </pre>
*/
public DefaultBoundedRangeModel(int value, int extent, int min, int max)
{
if ((max >= min) &&
(value >= min) &&
((value + extent) >= value) &&
((value + extent) <= max)) {
this.value = value;
this.extent = extent;
this.min = min;
this.max = max;
}
else {
throw new IllegalArgumentException("invalid range properties");
}
}
/** {@collect.stats}
* Returns the model's current value.
* @return the model's current value
* @see #setValue
* @see BoundedRangeModel#getValue
*/
public int getValue() {
return value;
}
/** {@collect.stats}
* Returns the model's extent.
* @return the model's extent
* @see #setExtent
* @see BoundedRangeModel#getExtent
*/
public int getExtent() {
return extent;
}
/** {@collect.stats}
* Returns the model's minimum.
* @return the model's minimum
* @see #setMinimum
* @see BoundedRangeModel#getMinimum
*/
public int getMinimum() {
return min;
}
/** {@collect.stats}
* Returns the model's maximum.
* @return the model's maximum
* @see #setMaximum
* @see BoundedRangeModel#getMaximum
*/
public int getMaximum() {
return max;
}
/** {@collect.stats}
* Sets the current value of the model. For a slider, that
* determines where the knob appears. Ensures that the new
* value, <I>n</I> falls within the model's constraints:
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
*
* @see BoundedRangeModel#setValue
*/
public void setValue(int n) {
n = Math.min(n, Integer.MAX_VALUE - extent);
int newValue = Math.max(n, min);
if (newValue + extent > max) {
newValue = max - extent;
}
setRangeProperties(newValue, extent, min, max, isAdjusting);
}
/** {@collect.stats}
* Sets the extent to <I>n</I> after ensuring that <I>n</I>
* is greater than or equal to zero and falls within the model's
* constraints:
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
* @see BoundedRangeModel#setExtent
*/
public void setExtent(int n) {
int newExtent = Math.max(0, n);
if(value + newExtent > max) {
newExtent = max - value;
}
setRangeProperties(value, newExtent, min, max, isAdjusting);
}
/** {@collect.stats}
* Sets the minimum to <I>n</I> after ensuring that <I>n</I>
* that the other three properties obey the model's constraints:
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
* @see #getMinimum
* @see BoundedRangeModel#setMinimum
*/
public void setMinimum(int n) {
int newMax = Math.max(n, max);
int newValue = Math.max(n, value);
int newExtent = Math.min(newMax - newValue, extent);
setRangeProperties(newValue, newExtent, n, newMax, isAdjusting);
}
/** {@collect.stats}
* Sets the maximum to <I>n</I> after ensuring that <I>n</I>
* that the other three properties obey the model's constraints:
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
* @see BoundedRangeModel#setMaximum
*/
public void setMaximum(int n) {
int newMin = Math.min(n, min);
int newExtent = Math.min(n - newMin, extent);
int newValue = Math.min(n - newExtent, value);
setRangeProperties(newValue, newExtent, newMin, n, isAdjusting);
}
/** {@collect.stats}
* Sets the <code>valueIsAdjusting</code> property.
*
* @see #getValueIsAdjusting
* @see #setValue
* @see BoundedRangeModel#setValueIsAdjusting
*/
public void setValueIsAdjusting(boolean b) {
setRangeProperties(value, extent, min, max, b);
}
/** {@collect.stats}
* Returns true if the value is in the process of changing
* as a result of actions being taken by the user.
*
* @return the value of the <code>valueIsAdjusting</code> property
* @see #setValue
* @see BoundedRangeModel#getValueIsAdjusting
*/
public boolean getValueIsAdjusting() {
return isAdjusting;
}
/** {@collect.stats}
* Sets all of the <code>BoundedRangeModel</code> properties after forcing
* the arguments to obey the usual constraints:
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
* <p>
* At most, one <code>ChangeEvent</code> is generated.
*
* @see BoundedRangeModel#setRangeProperties
* @see #setValue
* @see #setExtent
* @see #setMinimum
* @see #setMaximum
* @see #setValueIsAdjusting
*/
public void setRangeProperties(int newValue, int newExtent, int newMin, int newMax, boolean adjusting)
{
if (newMin > newMax) {
newMin = newMax;
}
if (newValue > newMax) {
newMax = newValue;
}
if (newValue < newMin) {
newMin = newValue;
}
/* Convert the addends to long so that extent can be
* Integer.MAX_VALUE without rolling over the sum.
* A JCK test covers this, see bug 4097718.
*/
if (((long)newExtent + (long)newValue) > newMax) {
newExtent = newMax - newValue;
}
if (newExtent < 0) {
newExtent = 0;
}
boolean isChange =
(newValue != value) ||
(newExtent != extent) ||
(newMin != min) ||
(newMax != max) ||
(adjusting != isAdjusting);
if (isChange) {
value = newValue;
extent = newExtent;
min = newMin;
max = newMax;
isAdjusting = adjusting;
fireStateChanged();
}
}
/** {@collect.stats}
* Adds a <code>ChangeListener</code>. The change listeners are run each
* time any one of the Bounded Range model properties changes.
*
* @param l the ChangeListener to add
* @see #removeChangeListener
* @see BoundedRangeModel#addChangeListener
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a <code>ChangeListener</code>.
*
* @param l the <code>ChangeListener</code> to remove
* @see #addChangeListener
* @see BoundedRangeModel#removeChangeListener
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the change listeners
* registered on this <code>DefaultBoundedRangeModel</code>.
*
* @return all of this model's <code>ChangeListener</code>s
* or an empty
* array if no change listeners are currently registered
*
* @see #addChangeListener
* @see #removeChangeListener
*
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Runs each <code>ChangeListener</code>'s <code>stateChanged</code> method.
*
* @see #setRangeProperties
* @see EventListenerList
*/
protected void fireStateChanged()
{
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -=2 ) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/** {@collect.stats}
* Returns a string that displays all of the
* <code>BoundedRangeModel</code> properties.
*/
public String toString() {
String modelString =
"value=" + getValue() + ", " +
"extent=" + getExtent() + ", " +
"min=" + getMinimum() + ", " +
"max=" + getMaximum() + ", " +
"adj=" + getValueIsAdjusting();
return getClass().getName() + "[" + modelString + "]";
}
/** {@collect.stats}
* Returns an array of all the objects currently registered as
* <code><em>Foo</em>Listener</code>s
* upon this model.
* <code><em>Foo</em>Listener</code>s
* are registered using the <code>add<em>Foo</em>Listener</code> method.
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as <code><em>Foo</em>Listener.class</code>.
* For example, you can query a <code>DefaultBoundedRangeModel</code>
* instance <code>m</code>
* for its change listeners
* with the following code:
*
* <pre>ChangeListener[] cls = (ChangeListener[])(m.getListeners(ChangeListener.class));</pre>
*
* If no such listeners exist,
* this method returns an empty array.
*
* @param listenerType the type of listeners requested;
* this parameter should specify an interface
* that descends from <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s
* on this model,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code> doesn't
* specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getChangeListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.filechooser;
import java.io.File;
/** {@collect.stats}
* <code>FileFilter</code> is an abstract class used by {@code JFileChooser}
* for filtering the set of files shown to the user. See
* {@code FileNameExtensionFilter} for an implementation that filters using
* the file name extension.
* <p>
* A <code>FileFilter</code>
* can be set on a <code>JFileChooser</code> to
* keep unwanted files from appearing in the directory listing.
* For an example implementation of a simple file filter, see
* <code><i>yourJDK</i>/demo/jfc/FileChooserDemo/ExampleFileFilter.java</code>.
* For more information and examples see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html">How to Use File Choosers</a>,
* a section in <em>The Java Tutorial</em>.
*
* @see FileNameExtensionFilter
* @see javax.swing.JFileChooser#setFileFilter
* @see javax.swing.JFileChooser#addChoosableFileFilter
*
* @author Jeff Dinkins
*/
public abstract class FileFilter {
/** {@collect.stats}
* Whether the given file is accepted by this filter.
*/
public abstract boolean accept(File f);
/** {@collect.stats}
* The description of this filter. For example: "JPG and GIF Images"
* @see FileView#getName
*/
public abstract String getDescription();
}
|
Java
|
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.filechooser;
import java.io.File;
import java.util.Locale;
/** {@collect.stats}
* An implementation of {@code FileFilter} that filters using a
* specified set of extensions. The extension for a file is the
* portion of the file name after the last ".". Files whose name does
* not contain a "." have no file name extension. File name extension
* comparisons are case insensitive.
* <p>
* The following example creates a
* {@code FileNameExtensionFilter} that will show {@code jpg} files:
* <pre>
* FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
* JFileChooser fileChooser = ...;
* fileChooser.addChoosableFileFilter(filter);
* </pre>
*
* @see FileFilter
* @see javax.swing.JFileChooser#setFileFilter
* @see javax.swing.JFileChooser#addChoosableFileFilter
* @see javax.swing.JFileChooser#getFileFilter
*
* @since 1.6
*/
public final class FileNameExtensionFilter extends FileFilter {
// Description of this filter.
private final String description;
// Known extensions.
private final String[] extensions;
// Cached ext
private final String[] lowerCaseExtensions;
/** {@collect.stats}
* Creates a {@code FileNameExtensionFilter} with the specified
* description and file name extensions. The returned {@code
* FileNameExtensionFilter} will accept all directories and any
* file with a file name extension contained in {@code extensions}.
*
* @param description textual description for the filter, may be
* {@code null}
* @param extensions the accepted file name extensions
* @throws IllegalArgumentException if extensions is {@code null}, empty,
* contains {@code null}, or contains an empty string
* @see #accept
*/
public FileNameExtensionFilter(String description, String... extensions) {
if (extensions == null || extensions.length == 0) {
throw new IllegalArgumentException(
"Extensions must be non-null and not empty");
}
this.description = description;
this.extensions = new String[extensions.length];
this.lowerCaseExtensions = new String[extensions.length];
for (int i = 0; i < extensions.length; i++) {
if (extensions[i] == null || extensions[i].length() == 0) {
throw new IllegalArgumentException(
"Each extension must be non-null and not empty");
}
this.extensions[i] = extensions[i];
lowerCaseExtensions[i] = extensions[i].toLowerCase(Locale.ENGLISH);
}
}
/** {@collect.stats}
* Tests the specified file, returning true if the file is
* accepted, false otherwise. True is returned if the extension
* matches one of the file name extensions of this {@code
* FileFilter}, or the file is a directory.
*
* @param f the {@code File} to test
* @return true if the file is to be accepted, false otherwise
*/
public boolean accept(File f) {
if (f != null) {
if (f.isDirectory()) {
return true;
}
// NOTE: we tested implementations using Maps, binary search
// on a sorted list and this implementation. All implementations
// provided roughly the same speed, most likely because of
// overhead associated with java.io.File. Therefor we've stuck
// with the simple lightweight approach.
String fileName = f.getName();
int i = fileName.lastIndexOf('.');
if (i > 0 && i < fileName.length() - 1) {
String desiredExtension = fileName.substring(i+1).
toLowerCase(Locale.ENGLISH);
for (String extension : lowerCaseExtensions) {
if (desiredExtension.equals(extension)) {
return true;
}
}
}
}
return false;
}
/** {@collect.stats}
* The description of this filter. For example: "JPG and GIF Images."
*
* @return the description of this filter
*/
public String getDescription() {
return description;
}
/** {@collect.stats}
* Returns the set of file name extensions files are tested against.
*
* @return the set of file name extensions files are tested against
*/
public String[] getExtensions() {
String[] result = new String[extensions.length];
System.arraycopy(extensions, 0, result, 0, extensions.length);
return result;
}
/** {@collect.stats}
* Returns a string representation of the {@code FileNameExtensionFilter}.
* This method is intended to be used for debugging purposes,
* and the content and format of the returned string may vary
* between implementations.
*
* @return a string representation of this {@code FileNameExtensionFilter}
*/
public String toString() {
return super.toString() + "[description=" + getDescription() +
" extensions=" + java.util.Arrays.asList(getExtensions()) + "]";
}
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.filechooser;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.Image;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.lang.reflect.*;
import sun.awt.shell.*;
/** {@collect.stats}
* FileSystemView is JFileChooser's gateway to the
* file system. Since the JDK1.1 File API doesn't allow
* access to such information as root partitions, file type
* information, or hidden file bits, this class is designed
* to intuit as much OS-specific file system information as
* possible.
*
* <p>
*
* Java Licensees may want to provide a different implementation of
* FileSystemView to better handle a given operating system.
*
* @author Jeff Dinkins
*/
// PENDING(jeff) - need to provide a specification for
// how Mac/OS2/BeOS/etc file systems can modify FileSystemView
// to handle their particular type of file system.
public abstract class FileSystemView {
static FileSystemView windowsFileSystemView = null;
static FileSystemView unixFileSystemView = null;
//static FileSystemView macFileSystemView = null;
static FileSystemView genericFileSystemView = null;
static boolean useSystemExtensionsHiding = false;
public static FileSystemView getFileSystemView() {
useSystemExtensionsHiding = UIManager.getDefaults().getBoolean("FileChooser.useSystemExtensionHiding");
UIManager.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals("lookAndFeel")) {
useSystemExtensionsHiding = UIManager.getDefaults().getBoolean("FileChooser.useSystemExtensionHiding");
}
}
});
if(File.separatorChar == '\\') {
if(windowsFileSystemView == null) {
windowsFileSystemView = new WindowsFileSystemView();
}
return windowsFileSystemView;
}
if(File.separatorChar == '/') {
if(unixFileSystemView == null) {
unixFileSystemView = new UnixFileSystemView();
}
return unixFileSystemView;
}
// if(File.separatorChar == ':') {
// if(macFileSystemView == null) {
// macFileSystemView = new MacFileSystemView();
// }
// return macFileSystemView;
//}
if(genericFileSystemView == null) {
genericFileSystemView = new GenericFileSystemView();
}
return genericFileSystemView;
}
/** {@collect.stats}
* Determines if the given file is a root in the navigatable tree(s).
* Examples: Windows 98 has one root, the Desktop folder. DOS has one root
* per drive letter, <code>C:\</code>, <code>D:\</code>, etc. Unix has one root,
* the <code>"/"</code> directory.
*
* The default implementation gets information from the <code>ShellFolder</code> class.
*
* @param f a <code>File</code> object representing a directory
* @return <code>true</code> if <code>f</code> is a root in the navigatable tree.
* @see #isFileSystemRoot
*/
public boolean isRoot(File f) {
if (f == null || !f.isAbsolute()) {
return false;
}
File[] roots = getRoots();
for (int i = 0; i < roots.length; i++) {
if (roots[i].equals(f)) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Returns true if the file (directory) can be visited.
* Returns false if the directory cannot be traversed.
*
* @param f the <code>File</code>
* @return <code>true</code> if the file/directory can be traversed, otherwise <code>false</code>
* @see JFileChooser#isTraversable
* @see FileView#isTraversable
* @since 1.4
*/
public Boolean isTraversable(File f) {
return Boolean.valueOf(f.isDirectory());
}
/** {@collect.stats}
* Name of a file, directory, or folder as it would be displayed in
* a system file browser. Example from Windows: the "M:\" directory
* displays as "CD-ROM (M:)"
*
* The default implementation gets information from the ShellFolder class.
*
* @param f a <code>File</code> object
* @return the file name as it would be displayed by a native file chooser
* @see JFileChooser#getName
* @since 1.4
*/
public String getSystemDisplayName(File f) {
String name = null;
if (f != null) {
name = f.getName();
if (!name.equals("..") && !name.equals(".") &&
(useSystemExtensionsHiding ||
!isFileSystem(f) ||
isFileSystemRoot(f)) &&
((f instanceof ShellFolder) ||
f.exists())) {
name = getShellFolder(f).getDisplayName();
if (name == null || name.length() == 0) {
name = f.getPath(); // e.g. "/"
}
}
}
return name;
}
/** {@collect.stats}
* Type description for a file, directory, or folder as it would be displayed in
* a system file browser. Example from Windows: the "Desktop" folder
* is desribed as "Desktop".
*
* Override for platforms with native ShellFolder implementations.
*
* @param f a <code>File</code> object
* @return the file type description as it would be displayed by a native file chooser
* or null if no native information is available.
* @see JFileChooser#getTypeDescription
* @since 1.4
*/
public String getSystemTypeDescription(File f) {
return null;
}
/** {@collect.stats}
* Icon for a file, directory, or folder as it would be displayed in
* a system file browser. Example from Windows: the "M:\" directory
* displays a CD-ROM icon.
*
* The default implementation gets information from the ShellFolder class.
*
* @param f a <code>File</code> object
* @return an icon as it would be displayed by a native file chooser
* @see JFileChooser#getIcon
* @since 1.4
*/
public Icon getSystemIcon(File f) {
if (f != null) {
ShellFolder sf = getShellFolder(f);
Image img = sf.getIcon(false);
if (img != null) {
return new ImageIcon(img, sf.getFolderType());
} else {
return UIManager.getIcon(f.isDirectory() ? "FileView.directoryIcon" : "FileView.fileIcon");
}
} else {
return null;
}
}
/** {@collect.stats}
* On Windows, a file can appear in multiple folders, other than its
* parent directory in the filesystem. Folder could for example be the
* "Desktop" folder which is not the same as file.getParentFile().
*
* @param folder a <code>File</code> object repesenting a directory or special folder
* @param file a <code>File</code> object
* @return <code>true</code> if <code>folder</code> is a directory or special folder and contains <code>file</code>.
* @since 1.4
*/
public boolean isParent(File folder, File file) {
if (folder == null || file == null) {
return false;
} else if (folder instanceof ShellFolder) {
File parent = file.getParentFile();
if (parent != null && parent.equals(folder)) {
return true;
}
File[] children = getFiles(folder, false);
for (int i = 0; i < children.length; i++) {
if (file.equals(children[i])) {
return true;
}
}
return false;
} else {
return folder.equals(file.getParentFile());
}
}
/** {@collect.stats}
*
* @param parent a <code>File</code> object repesenting a directory or special folder
* @param fileName a name of a file or folder which exists in <code>parent</code>
* @return a File object. This is normally constructed with <code>new
* File(parent, fileName)</code> except when parent and child are both
* special folders, in which case the <code>File</code> is a wrapper containing
* a <code>ShellFolder</code> object.
* @since 1.4
*/
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];
}
}
}
return createFileObject(parent, fileName);
}
/** {@collect.stats}
* Checks if <code>f</code> represents a real directory or file as opposed to a
* special folder such as <code>"Desktop"</code>. Used by UI classes to decide if
* a folder is selectable when doing directory choosing.
*
* @param f a <code>File</code> object
* @return <code>true</code> if <code>f</code> is a real file or directory.
* @since 1.4
*/
public boolean isFileSystem(File f) {
if (f instanceof ShellFolder) {
ShellFolder sf = (ShellFolder)f;
// Shortcuts to directories are treated as not being file system objects,
// so that they are never returned by JFileChooser.
return sf.isFileSystem() && !(sf.isLink() && sf.isDirectory());
} else {
return true;
}
}
/** {@collect.stats}
* Creates a new folder with a default folder name.
*/
public abstract File createNewFolder(File containingDir) throws IOException;
/** {@collect.stats}
* Returns whether a file is hidden or not.
*/
public boolean isHiddenFile(File f) {
return f.isHidden();
}
/** {@collect.stats}
* Is dir the root of a tree in the file system, such as a drive
* or partition. Example: Returns true for "C:\" on Windows 98.
*
* @param dir a <code>File</code> object representing a directory
* @return <code>true</code> if <code>f</code> is a root of a filesystem
* @see #isRoot
* @since 1.4
*/
public boolean isFileSystemRoot(File dir) {
return ShellFolder.isFileSystemRoot(dir);
}
/** {@collect.stats}
* Used by UI classes to decide whether to display a special icon
* for drives or partitions, e.g. a "hard disk" icon.
*
* The default implementation has no way of knowing, so always returns false.
*
* @param dir a directory
* @return <code>false</code> always
* @since 1.4
*/
public boolean isDrive(File dir) {
return false;
}
/** {@collect.stats}
* Used by UI classes to decide whether to display a special icon
* for a floppy disk. Implies isDrive(dir).
*
* The default implementation has no way of knowing, so always returns false.
*
* @param dir a directory
* @return <code>false</code> always
* @since 1.4
*/
public boolean isFloppyDrive(File dir) {
return false;
}
/** {@collect.stats}
* Used by UI classes to decide whether to display a special icon
* for a computer node, e.g. "My Computer" or a network server.
*
* The default implementation has no way of knowing, so always returns false.
*
* @param dir a directory
* @return <code>false</code> always
* @since 1.4
*/
public boolean isComputerNode(File dir) {
return ShellFolder.isComputerNode(dir);
}
/** {@collect.stats}
* Returns all root partitions on this system. For example, on
* Windows, this would be the "Desktop" folder, while on DOS this
* would be the A: through Z: drives.
*/
public File[] getRoots() {
// Don't cache this array, because filesystem might change
File[] roots = (File[])ShellFolder.get("roots");
for (int i = 0; i < roots.length; i++) {
if (isFileSystemRoot(roots[i])) {
roots[i] = createFileSystemRoot(roots[i]);
}
}
return roots;
}
// Providing default implementations for the remaining methods
// because most OS file systems will likely be able to use this
// code. If a given OS can't, override these methods in its
// implementation.
public File getHomeDirectory() {
return createFileObject(System.getProperty("user.home"));
}
/** {@collect.stats}
* Return the user's default starting directory for the file chooser.
*
* @return a <code>File</code> object representing the default
* starting folder
* @since 1.4
*/
public File getDefaultDirectory() {
File f = (File)ShellFolder.get("fileChooserDefaultFolder");
if (isFileSystemRoot(f)) {
f = createFileSystemRoot(f);
}
return f;
}
/** {@collect.stats}
* Returns a File object constructed in dir from the given filename.
*/
public File createFileObject(File dir, String filename) {
if(dir == null) {
return new File(filename);
} else {
return new File(dir, filename);
}
}
/** {@collect.stats}
* Returns a File object constructed from the given path string.
*/
public File createFileObject(String path) {
File f = new File(path);
if (isFileSystemRoot(f)) {
f = createFileSystemRoot(f);
}
return f;
}
/** {@collect.stats}
* Gets the list of shown (i.e. not hidden) files.
*/
public File[] getFiles(File dir, boolean useFileHiding) {
Vector files = new Vector();
// add all files in dir
File[] names;
if (!(dir instanceof ShellFolder)) {
dir = getShellFolder(dir);
}
names = ((ShellFolder)dir).listFiles(!useFileHiding);
File f;
int nameCount = (names == null) ? 0 : names.length;
for (int i = 0; i < nameCount; i++) {
if (Thread.currentThread().isInterrupted()) {
break;
}
f = names[i];
if (!(f instanceof ShellFolder)) {
if (isFileSystemRoot(f)) {
f = createFileSystemRoot(f);
}
try {
f = ShellFolder.getShellFolder(f);
} catch (FileNotFoundException e) {
// Not a valid file (wouldn't show in native file chooser)
// Example: C:\pagefile.sys
continue;
} catch (InternalError e) {
// Not a valid file (wouldn't show in native file chooser)
// Example C:\Winnt\Profiles\joe\history\History.IE5
continue;
}
}
if (!useFileHiding || !isHiddenFile(f)) {
files.addElement(f);
}
}
return (File[])files.toArray(new File[files.size()]);
}
/** {@collect.stats}
* Returns the parent directory of <code>dir</code>.
* @param dir the <code>File</code> being queried
* @return the parent directory of <code>dir</code>, or
* <code>null</code> if <code>dir</code> is <code>null</code>
*/
public File getParentDirectory(File dir) {
if (dir != null && dir.exists()) {
ShellFolder sf = getShellFolder(dir);
File psf = sf.getParentFile();
if (psf != null) {
if (isFileSystem(psf)) {
File f = psf;
if (f != null && !f.exists()) {
// This could be a node under "Network Neighborhood".
File ppsf = psf.getParentFile();
if (ppsf == null || !isFileSystem(ppsf)) {
// We're mostly after the exists() override for windows below.
f = createFileSystemRoot(f);
}
}
return f;
} else {
return psf;
}
}
}
return null;
}
ShellFolder getShellFolder(File f) {
if (!(f instanceof ShellFolder)
&& !(f instanceof FileSystemRoot)
&& isFileSystemRoot(f)) {
f = createFileSystemRoot(f);
}
try {
return ShellFolder.getShellFolder(f);
} catch (FileNotFoundException e) {
System.err.println("FileSystemView.getShellFolder: f="+f);
e.printStackTrace();
return null;
} catch (InternalError e) {
System.err.println("FileSystemView.getShellFolder: f="+f);
e.printStackTrace();
return null;
}
}
/** {@collect.stats}
* Creates a new <code>File</code> object for <code>f</code> with correct
* behavior for a file system root directory.
*
* @param f a <code>File</code> object representing a file system root
* directory, for example "/" on Unix or "C:\" on Windows.
* @return a new <code>File</code> object
* @since 1.4
*/
protected File createFileSystemRoot(File f) {
return new FileSystemRoot(f);
}
static class FileSystemRoot extends File {
public FileSystemRoot(File f) {
super(f,"");
}
public FileSystemRoot(String s) {
super(s);
}
public boolean isDirectory() {
return true;
}
public String getName() {
return getPath();
}
}
}
/** {@collect.stats}
* FileSystemView that handles some specific unix-isms.
*/
class UnixFileSystemView extends FileSystemView {
private static final String newFolderString =
UIManager.getString("FileChooser.other.newFolder");
private static final String newFolderNextString =
UIManager.getString("FileChooser.other.newFolder.subsequent");
/** {@collect.stats}
* Creates a new folder with a default folder name.
*/
public File createNewFolder(File containingDir) throws IOException {
if(containingDir == null) {
throw new IOException("Containing directory is null:");
}
File newFolder = null;
// Unix - using OpenWindows' default folder name. Can't find one for Motif/CDE.
newFolder = createFileObject(containingDir, newFolderString);
int i = 1;
while (newFolder.exists() && (i < 100)) {
newFolder = createFileObject(containingDir, MessageFormat.format(
newFolderNextString, new Object[] { new Integer(i) }));
i++;
}
if(newFolder.exists()) {
throw new IOException("Directory already exists:" + newFolder.getAbsolutePath());
} else {
newFolder.mkdirs();
}
return newFolder;
}
public boolean isFileSystemRoot(File dir) {
return (dir != null && dir.getAbsolutePath().equals("/"));
}
public boolean isDrive(File dir) {
if (isFloppyDrive(dir)) {
return true;
} else {
return false;
}
}
public boolean isFloppyDrive(File dir) {
// Could be looking at the path for Solaris, but wouldn't be reliable.
// For example:
// return (dir != null && dir.getAbsolutePath().toLowerCase().startsWith("/floppy"));
return false;
}
public boolean isComputerNode(File dir) {
if (dir != null) {
String parent = dir.getParent();
if (parent != null && parent.equals("/net")) {
return true;
}
}
return false;
}
}
/** {@collect.stats}
* FileSystemView that handles some specific windows concepts.
*/
class WindowsFileSystemView extends FileSystemView {
private static final String newFolderString =
UIManager.getString("FileChooser.win32.newFolder");
private static final String newFolderNextString =
UIManager.getString("FileChooser.win32.newFolder.subsequent");
public Boolean isTraversable(File f) {
return Boolean.valueOf(isFileSystemRoot(f) || isComputerNode(f) || f.isDirectory());
}
public File getChild(File parent, String fileName) {
if (fileName.startsWith("\\")
&& !(fileName.startsWith("\\\\"))
&& isFileSystem(parent)) {
//Path is relative to the root of parent's drive
String path = parent.getAbsolutePath();
if (path.length() >= 2
&& path.charAt(1) == ':'
&& Character.isLetter(path.charAt(0))) {
return createFileObject(path.substring(0, 2) + fileName);
}
}
return super.getChild(parent, fileName);
}
/** {@collect.stats}
* Type description for a file, directory, or folder as it would be displayed in
* a system file browser. Example from Windows: the "Desktop" folder
* is desribed as "Desktop".
*
* The Windows implementation gets information from the ShellFolder class.
*/
public String getSystemTypeDescription(File f) {
if (f != null) {
return getShellFolder(f).getFolderType();
} else {
return null;
}
}
/** {@collect.stats}
* @return the Desktop folder.
*/
public File getHomeDirectory() {
return getRoots()[0];
}
/** {@collect.stats}
* Creates a new folder with a default folder name.
*/
public File createNewFolder(File containingDir) throws IOException {
if(containingDir == null) {
throw new IOException("Containing directory is null:");
}
File newFolder = null;
// Using NT's default folder name
newFolder = createFileObject(containingDir, newFolderString);
int i = 2;
while (newFolder.exists() && (i < 100)) {
newFolder = createFileObject(containingDir, MessageFormat.format(
newFolderNextString, new Object[] { new Integer(i) }));
i++;
}
if(newFolder.exists()) {
throw new IOException("Directory already exists:" + newFolder.getAbsolutePath());
} else {
newFolder.mkdirs();
}
return newFolder;
}
public boolean isDrive(File dir) {
return isFileSystemRoot(dir);
}
public boolean isFloppyDrive(File dir) {
String path = dir.getAbsolutePath();
return (path != null && (path.equals("A:\\") || path.equals("B:\\")));
}
/** {@collect.stats}
* Returns a File object constructed from the given path string.
*/
public File createFileObject(String path) {
// Check for missing backslash after drive letter such as "C:" or "C:filename"
if (path.length() >= 2 && path.charAt(1) == ':' && Character.isLetter(path.charAt(0))) {
if (path.length() == 2) {
path += "\\";
} else if (path.charAt(2) != '\\') {
path = path.substring(0, 2) + "\\" + path.substring(2);
}
}
return super.createFileObject(path);
}
protected File createFileSystemRoot(File f) {
// Problem: Removable drives on Windows return false on f.exists()
// Workaround: Override exists() to always return true.
return new FileSystemRoot(f) {
public boolean exists() {
return true;
}
};
}
}
/** {@collect.stats}
* Fallthrough FileSystemView in case we can't determine the OS.
*/
class GenericFileSystemView extends FileSystemView {
private static final String newFolderString =
UIManager.getString("FileChooser.other.newFolder");
/** {@collect.stats}
* Creates a new folder with a default folder name.
*/
public File createNewFolder(File containingDir) throws IOException {
if(containingDir == null) {
throw new IOException("Containing directory is null:");
}
File newFolder = null;
// Using NT's default folder name
newFolder = createFileObject(containingDir, newFolderString);
if(newFolder.exists()) {
throw new IOException("Directory already exists:" + newFolder.getAbsolutePath());
} else {
newFolder.mkdirs();
}
return newFolder;
}
}
|
Java
|
/*
* Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.filechooser;
import java.io.File;
import javax.swing.*;
/** {@collect.stats}
* <code>FileView</code> defines an abstract class that can be implemented
* to provide the filechooser with UI information for a <code>File</code>.
* Each L&F <code>JFileChooserUI</code> object implements this
* class to pass back the correct icons and type descriptions specific to
* that L&F. For example, the Microsoft Windows L&F returns the
* generic Windows icons for directories and generic files.
* Additionally, you may want to provide your own <code>FileView</code> to
* <code>JFileChooser</code> to return different icons or additional
* information using {@link javax.swing.JFileChooser#setFileView}.
*
* <p>
*
* <code>JFileChooser</code> first looks to see if there is a user defined
* <code>FileView</code>, if there is, it gets type information from
* there first. If <code>FileView</code> returns <code>null</code> for
* any method, <code>JFileChooser</code> then uses the L&F specific
* view to get the information.
* So, for example, if you provide a <code>FileView</code> class that
* returns an <code>Icon</code> for JPG files, and returns <code>null</code>
* icons for all other files, the UI's <code>FileView</code> will provide
* default icons for all other files.
*
* <p>
*
* For an example implementation of a simple file view, see
* <code><i>yourJDK</i>/demo/jfc/FileChooserDemo/ExampleFileView.java</code>.
* For more information and examples see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html">How to Use File Choosers</a>,
* a section in <em>The Java Tutorial</em>.
*
* @see javax.swing.JFileChooser
*
* @author Jeff Dinkins
*
*/
public abstract class FileView {
/** {@collect.stats}
* The name of the file. Normally this would be simply
* <code>f.getName()</code>.
*/
public String getName(File f) {
return null;
};
/** {@collect.stats}
* A human readable description of the file. For example,
* a file named <i>jag.jpg</i> might have a description that read:
* "A JPEG image file of James Gosling's face".
*/
public String getDescription(File f) {
return null;
}
/** {@collect.stats}
* A human readable description of the type of the file. For
* example, a <code>jpg</code> file might have a type description of:
* "A JPEG Compressed Image File"
*/
public String getTypeDescription(File f) {
return null;
}
/** {@collect.stats}
* The icon that represents this file in the <code>JFileChooser</code>.
*/
public Icon getIcon(File f) {
return null;
}
/** {@collect.stats}
* Whether the directory is traversable or not. This might be
* useful, for example, if you want a directory to represent
* a compound document and don't want the user to descend into it.
*/
public Boolean isTraversable(File f) {
return null;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.AtomicLong;
import sun.awt.AppContext;
/** {@collect.stats}
* Internal class to manage all Timers using one thread.
* TimerQueue manages a queue of Timers. The Timers are chained
* together in a linked list sorted by the order in which they will expire.
*
* @author Dave Moore
* @author Igor Kushnirskiy
*/
class TimerQueue implements Runnable
{
private static final Object sharedInstanceKey = new Object(); // TimerQueue.sharedInstanceKey
private final DelayQueue<DelayedTimer> queue;
private volatile boolean running;
private final Lock runningLock;
/* Lock object used in place of class object for synchronization.
* (4187686)
*/
private static final Object classLock = new Object();
/** {@collect.stats} Base of nanosecond timings, to avoid wrapping */
private static final long NANO_ORIGIN = System.nanoTime();
/** {@collect.stats}
* Constructor for TimerQueue.
*/
public TimerQueue() {
super();
queue = new DelayQueue<DelayedTimer>();
// Now start the TimerQueue thread.
runningLock = new ReentrantLock();
startIfNeeded();
}
public static TimerQueue sharedInstance() {
synchronized (classLock) {
TimerQueue sharedInst = (TimerQueue)
SwingUtilities.appContextGet(
sharedInstanceKey);
if (sharedInst == null) {
sharedInst = new TimerQueue();
SwingUtilities.appContextPut(sharedInstanceKey, sharedInst);
}
return sharedInst;
}
}
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();
}
}
}
void addTimer(Timer timer, long delayMillis) {
timer.getLock().lock();
try {
// If the Timer is already in the queue, then ignore the add.
if (! containsTimer(timer)) {
addTimer(new DelayedTimer(timer,
TimeUnit.MILLISECONDS.toNanos(delayMillis)
+ now()));
}
} finally {
timer.getLock().unlock();
}
}
private void addTimer(DelayedTimer delayedTimer) {
assert delayedTimer != null && ! containsTimer(delayedTimer.getTimer());
Timer timer = delayedTimer.getTimer();
timer.getLock().lock();
try {
timer.delayedTimer = delayedTimer;
queue.add(delayedTimer);
} finally {
timer.getLock().unlock();
}
}
void removeTimer(Timer timer) {
timer.getLock().lock();
try {
if (timer.delayedTimer != null) {
queue.remove(timer.delayedTimer);
timer.delayedTimer = null;
}
} finally {
timer.getLock().unlock();
}
}
boolean containsTimer(Timer timer) {
timer.getLock().lock();
try {
return timer.delayedTimer != null;
} finally {
timer.getLock().unlock();
}
}
public void run() {
runningLock.lock();
try {
while (running) {
try {
Timer timer = queue.take().getTimer();
timer.getLock().lock();
try {
DelayedTimer delayedTimer = timer.delayedTimer;
if (delayedTimer != null) {
/*
* Timer is not removed after we get it from
* the queue and before the lock on the timer is
* acquired
*/
timer.post(); // have timer post an event
timer.delayedTimer = null;
if (timer.isRepeats()) {
delayedTimer.setTime(now()
+ TimeUnit.MILLISECONDS.toNanos(
timer.getDelay()));
addTimer(delayedTimer);
}
}
} catch (SecurityException ignore) {
} finally {
timer.getLock().unlock();
}
} catch (InterruptedException ignore) {
}
}
}
catch (ThreadDeath 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();
}
}
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("TimerQueue (");
boolean isFirst = true;
for (DelayedTimer delayedTimer : queue) {
if (! isFirst) {
buf.append(", ");
}
buf.append(delayedTimer.getTimer().toString());
isFirst = false;
}
buf.append(")");
return buf.toString();
}
/** {@collect.stats}
* Returns nanosecond time offset by origin
*/
private final static long now() {
return System.nanoTime() - NANO_ORIGIN;
}
static class DelayedTimer implements Delayed {
// most of it copied from
// java.util.concurrent.ScheduledThreadPoolExecutor
/** {@collect.stats}
* Sequence number to break scheduling ties, and in turn to
* guarantee FIFO order among tied entries.
*/
private static final AtomicLong sequencer = new AtomicLong(0);
/** {@collect.stats} Sequence number to break ties FIFO */
private final long sequenceNumber;
/** {@collect.stats} The time the task is enabled to execute in nanoTime units */
private volatile long time;
private final Timer timer;
DelayedTimer(Timer timer, long nanos) {
this.timer = timer;
time = nanos;
sequenceNumber = sequencer.getAndIncrement();
}
final public long getDelay(TimeUnit unit) {
return unit.convert(time - now(), TimeUnit.NANOSECONDS);
}
final void setTime(long nanos) {
time = nanos;
}
final Timer getTimer() {
return timer;
}
public int compareTo(Delayed other) {
if (other == this) { // compare zero ONLY if same object
return 0;
}
if (other instanceof DelayedTimer) {
DelayedTimer x = (DelayedTimer)other;
long diff = time - x.time;
if (diff < 0) {
return -1;
} else if (diff > 0) {
return 1;
} else if (sequenceNumber < x.sequenceNumber) {
return -1;
} else {
return 1;
}
}
long d = (getDelay(TimeUnit.NANOSECONDS) -
other.getDelay(TimeUnit.NANOSECONDS));
return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import javax.swing.plaf.FileChooserUI;
import javax.accessibility.*;
import java.io.File;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.Vector;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.lang.ref.WeakReference;
/** {@collect.stats}
* <code>JFileChooser</code> provides a simple mechanism for the user to
* choose a file.
* For information about using <code>JFileChooser</code>, see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html">How to Use File Choosers</a>,
* a section in <em>The Java Tutorial</em>.
*
* <p>
*
* The following code pops up a file chooser for the user's home directory that
* sees only .jpg and .gif images:
* <pre>
* JFileChooser chooser = new JFileChooser();
* FileNameExtensionFilter filter = new FileNameExtensionFilter(
* "JPG & GIF Images", "jpg", "gif");
* chooser.setFileFilter(filter);
* int returnVal = chooser.showOpenDialog(parent);
* if(returnVal == JFileChooser.APPROVE_OPTION) {
* System.out.println("You chose to open this file: " +
* chooser.getSelectedFile().getName());
* }
* </pre>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
*
* @beaninfo
* attribute: isContainer false
* description: A component which allows for the interactive selection of a file.
*
* @author Jeff Dinkins
*
*/
public class JFileChooser extends JComponent implements Accessible {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "FileChooserUI";
// ************************
// ***** Dialog Types *****
// ************************
/** {@collect.stats}
* Type value indicating that the <code>JFileChooser</code> supports an
* "Open" file operation.
*/
public static final int OPEN_DIALOG = 0;
/** {@collect.stats}
* Type value indicating that the <code>JFileChooser</code> supports a
* "Save" file operation.
*/
public static final int SAVE_DIALOG = 1;
/** {@collect.stats}
* Type value indicating that the <code>JFileChooser</code> supports a
* developer-specified file operation.
*/
public static final int CUSTOM_DIALOG = 2;
// ********************************
// ***** Dialog Return Values *****
// ********************************
/** {@collect.stats}
* Return value if cancel is chosen.
*/
public static final int CANCEL_OPTION = 1;
/** {@collect.stats}
* Return value if approve (yes, ok) is chosen.
*/
public static final int APPROVE_OPTION = 0;
/** {@collect.stats}
* Return value if an error occured.
*/
public static final int ERROR_OPTION = -1;
// **********************************
// ***** JFileChooser properties *****
// **********************************
/** {@collect.stats} Instruction to display only files. */
public static final int FILES_ONLY = 0;
/** {@collect.stats} Instruction to display only directories. */
public static final int DIRECTORIES_ONLY = 1;
/** {@collect.stats} Instruction to display both files and directories. */
public static final int FILES_AND_DIRECTORIES = 2;
/** {@collect.stats} Instruction to cancel the current selection. */
public static final String CANCEL_SELECTION = "CancelSelection";
/** {@collect.stats}
* Instruction to approve the current selection
* (same as pressing yes or ok).
*/
public static final String APPROVE_SELECTION = "ApproveSelection";
/** {@collect.stats} Identifies change in the text on the approve (yes, ok) button. */
public static final String APPROVE_BUTTON_TEXT_CHANGED_PROPERTY = "ApproveButtonTextChangedProperty";
/** {@collect.stats}
* Identifies change in the tooltip text for the approve (yes, ok)
* button.
*/
public static final String APPROVE_BUTTON_TOOL_TIP_TEXT_CHANGED_PROPERTY = "ApproveButtonToolTipTextChangedProperty";
/** {@collect.stats} Identifies change in the mnemonic for the approve (yes, ok) button. */
public static final String APPROVE_BUTTON_MNEMONIC_CHANGED_PROPERTY = "ApproveButtonMnemonicChangedProperty";
/** {@collect.stats} Instruction to display the control buttons. */
public static final String CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY = "ControlButtonsAreShownChangedProperty";
/** {@collect.stats} Identifies user's directory change. */
public static final String DIRECTORY_CHANGED_PROPERTY = "directoryChanged";
/** {@collect.stats} Identifies change in user's single-file selection. */
public static final String SELECTED_FILE_CHANGED_PROPERTY = "SelectedFileChangedProperty";
/** {@collect.stats} Identifies change in user's multiple-file selection. */
public static final String SELECTED_FILES_CHANGED_PROPERTY = "SelectedFilesChangedProperty";
/** {@collect.stats} Enables multiple-file selections. */
public static final String MULTI_SELECTION_ENABLED_CHANGED_PROPERTY = "MultiSelectionEnabledChangedProperty";
/** {@collect.stats}
* Says that a different object is being used to find available drives
* on the system.
*/
public static final String FILE_SYSTEM_VIEW_CHANGED_PROPERTY = "FileSystemViewChanged";
/** {@collect.stats}
* Says that a different object is being used to retrieve file
* information.
*/
public static final String FILE_VIEW_CHANGED_PROPERTY = "fileViewChanged";
/** {@collect.stats} Identifies a change in the display-hidden-files property. */
public static final String FILE_HIDING_CHANGED_PROPERTY = "FileHidingChanged";
/** {@collect.stats} User changed the kind of files to display. */
public static final String FILE_FILTER_CHANGED_PROPERTY = "fileFilterChanged";
/** {@collect.stats}
* Identifies a change in the kind of selection (single,
* multiple, etc.).
*/
public static final String FILE_SELECTION_MODE_CHANGED_PROPERTY = "fileSelectionChanged";
/** {@collect.stats}
* Says that a different accessory component is in use
* (for example, to preview files).
*/
public static final String ACCESSORY_CHANGED_PROPERTY = "AccessoryChangedProperty";
/** {@collect.stats}
* Identifies whether a the AcceptAllFileFilter is used or not.
*/
public static final String ACCEPT_ALL_FILE_FILTER_USED_CHANGED_PROPERTY = "acceptAllFileFilterUsedChanged";
/** {@collect.stats} Identifies a change in the dialog title. */
public static final String DIALOG_TITLE_CHANGED_PROPERTY = "DialogTitleChangedProperty";
/** {@collect.stats}
* Identifies a change in the type of files displayed (files only,
* directories only, or both files and directories).
*/
public static final String DIALOG_TYPE_CHANGED_PROPERTY = "DialogTypeChangedProperty";
/** {@collect.stats}
* Identifies a change in the list of predefined file filters
* the user can choose from.
*/
public static final String CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY = "ChoosableFileFilterChangedProperty";
// ******************************
// ***** instance variables *****
// ******************************
private String dialogTitle = null;
private String approveButtonText = null;
private String approveButtonToolTipText = null;
private int approveButtonMnemonic = 0;
private Vector filters = new Vector(5);
private JDialog dialog = null;
private int dialogType = OPEN_DIALOG;
private int returnValue = ERROR_OPTION;
private JComponent accessory = null;
private FileView fileView = null;
// uiFileView is not serialized, as it is initialized
// by updateUI() after deserialization
private transient FileView uiFileView = null;
private boolean controlsShown = true;
private boolean useFileHiding = true;
private static final String SHOW_HIDDEN_PROP = "awt.file.showHiddenFiles";
// Listens to changes in the native setting for showing hidden files.
// The Listener is removed and the native setting is ignored if
// setFileHidingEnabled() is ever called.
private transient PropertyChangeListener showFilesListener = null;
private int fileSelectionMode = FILES_ONLY;
private boolean multiSelectionEnabled = false;
private boolean useAcceptAllFileFilter = true;
private boolean dragEnabled = false;
private FileFilter fileFilter = null;
private FileSystemView fileSystemView = null;
private File currentDirectory = null;
private File selectedFile = null;
private File[] selectedFiles;
// *************************************
// ***** JFileChooser Constructors *****
// *************************************
/** {@collect.stats}
* Constructs a <code>JFileChooser</code> pointing to the user's
* default directory. This default depends on the operating system.
* It is typically the "My Documents" folder on Windows, and the
* user's home directory on Unix.
*/
public JFileChooser() {
this((File) null, (FileSystemView) null);
}
/** {@collect.stats}
* Constructs a <code>JFileChooser</code> using the given path.
* Passing in a <code>null</code>
* string causes the file chooser to point to the user's default directory.
* This default depends on the operating system. It is
* typically the "My Documents" folder on Windows, and the user's
* home directory on Unix.
*
* @param currentDirectoryPath a <code>String</code> giving the path
* to a file or directory
*/
public JFileChooser(String currentDirectoryPath) {
this(currentDirectoryPath, (FileSystemView) null);
}
/** {@collect.stats}
* Constructs a <code>JFileChooser</code> using the given <code>File</code>
* as the path. Passing in a <code>null</code> file
* causes the file chooser to point to the user's default directory.
* This default depends on the operating system. It is
* typically the "My Documents" folder on Windows, and the user's
* home directory on Unix.
*
* @param currentDirectory a <code>File</code> object specifying
* the path to a file or directory
*/
public JFileChooser(File currentDirectory) {
this(currentDirectory, (FileSystemView) null);
}
/** {@collect.stats}
* Constructs a <code>JFileChooser</code> using the given
* <code>FileSystemView</code>.
*/
public JFileChooser(FileSystemView fsv) {
this((File) null, fsv);
}
/** {@collect.stats}
* Constructs a <code>JFileChooser</code> using the given current directory
* and <code>FileSystemView</code>.
*/
public JFileChooser(File currentDirectory, FileSystemView fsv) {
setup(fsv);
setCurrentDirectory(currentDirectory);
}
/** {@collect.stats}
* Constructs a <code>JFileChooser</code> using the given current directory
* path and <code>FileSystemView</code>.
*/
public JFileChooser(String currentDirectoryPath, FileSystemView fsv) {
setup(fsv);
if(currentDirectoryPath == null) {
setCurrentDirectory(null);
} else {
setCurrentDirectory(fileSystemView.createFileObject(currentDirectoryPath));
}
}
/** {@collect.stats}
* Performs common constructor initialization and setup.
*/
protected void setup(FileSystemView view) {
installShowFilesListener();
if(view == null) {
view = FileSystemView.getFileSystemView();
}
setFileSystemView(view);
updateUI();
if(isAcceptAllFileFilterUsed()) {
setFileFilter(getAcceptAllFileFilter());
}
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
private void installShowFilesListener() {
// Track native setting for showing hidden files
Toolkit tk = Toolkit.getDefaultToolkit();
Object showHiddenProperty = tk.getDesktopProperty(SHOW_HIDDEN_PROP);
if (showHiddenProperty instanceof Boolean) {
useFileHiding = !((Boolean)showHiddenProperty).booleanValue();
showFilesListener = new WeakPCL(this);
tk.addPropertyChangeListener(SHOW_HIDDEN_PROP, showFilesListener);
}
}
/** {@collect.stats}
* Sets the <code>dragEnabled</code> property,
* which must be <code>true</code> to enable
* automatic drag handling (the first part of drag and drop)
* on this component.
* The <code>transferHandler</code> property needs to be set
* to a non-<code>null</code> value for the drag to do
* anything. The default value of the <code>dragEnabled</code>
* property
* is <code>false</code>.
*
* <p>
*
* When automatic drag handling is enabled,
* most look and feels begin a drag-and-drop operation
* whenever the user presses the mouse button over an item
* and then moves the mouse a few pixels.
* Setting this property to <code>true</code>
* can therefore have a subtle effect on
* how selections behave.
*
* <p>
*
* Some look and feels might not support automatic drag and drop;
* they will ignore this property. You can work around such
* look and feels by modifying the component
* to directly call the <code>exportAsDrag</code> method of a
* <code>TransferHandler</code>.
*
* @param b the value to set the <code>dragEnabled</code> property to
* @exception HeadlessException if
* <code>b</code> is <code>true</code> and
* <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #getDragEnabled
* @see #setTransferHandler
* @see TransferHandler
* @since 1.4
*
* @beaninfo
* description: determines whether automatic drag handling is enabled
* bound: false
*/
public void setDragEnabled(boolean b) {
if (b && GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
dragEnabled = b;
}
/** {@collect.stats}
* Gets the value of the <code>dragEnabled</code> property.
*
* @return the value of the <code>dragEnabled</code> property
* @see #setDragEnabled
* @since 1.4
*/
public boolean getDragEnabled() {
return dragEnabled;
}
// *****************************
// ****** File Operations ******
// *****************************
/** {@collect.stats}
* Returns the selected file. This can be set either by the
* programmer via <code>setSelectedFile</code> or by a user action, such as
* either typing the filename into the UI or selecting the
* file from a list in the UI.
*
* @see #setSelectedFile
* @return the selected file
*/
public File getSelectedFile() {
return selectedFile;
}
/** {@collect.stats}
* Sets the selected file. If the file's parent directory is
* not the current directory, changes the current directory
* to be the file's parent directory.
*
* @beaninfo
* preferred: true
* bound: true
*
* @see #getSelectedFile
*
* @param file the selected file
*/
public void setSelectedFile(File file) {
File oldValue = selectedFile;
selectedFile = file;
if(selectedFile != null) {
if (file.isAbsolute() && !getFileSystemView().isParent(getCurrentDirectory(), selectedFile)) {
setCurrentDirectory(selectedFile.getParentFile());
}
if (!isMultiSelectionEnabled() || selectedFiles == null || selectedFiles.length == 1) {
ensureFileIsVisible(selectedFile);
}
}
firePropertyChange(SELECTED_FILE_CHANGED_PROPERTY, oldValue, selectedFile);
}
/** {@collect.stats}
* Returns a list of selected files if the file chooser is
* set to allow multiple selection.
*/
public File[] getSelectedFiles() {
if(selectedFiles == null) {
return new File[0];
} else {
return (File[]) selectedFiles.clone();
}
}
/** {@collect.stats}
* Sets the list of selected files if the file chooser is
* set to allow multiple selection.
*
* @beaninfo
* bound: true
* description: The list of selected files if the chooser is in multiple selection mode.
*/
public void setSelectedFiles(File[] selectedFiles) {
File[] oldValue = this.selectedFiles;
if (selectedFiles == null || selectedFiles.length == 0) {
selectedFiles = null;
this.selectedFiles = null;
setSelectedFile(null);
} else {
this.selectedFiles = selectedFiles.clone();
setSelectedFile(this.selectedFiles[0]);
}
firePropertyChange(SELECTED_FILES_CHANGED_PROPERTY, oldValue, selectedFiles);
}
/** {@collect.stats}
* Returns the current directory.
*
* @return the current directory
* @see #setCurrentDirectory
*/
public File getCurrentDirectory() {
return currentDirectory;
}
/** {@collect.stats}
* Sets the current directory. Passing in <code>null</code> sets the
* file chooser to point to the user's default directory.
* This default depends on the operating system. It is
* typically the "My Documents" folder on Windows, and the user's
* home directory on Unix.
*
* If the file passed in as <code>currentDirectory</code> is not a
* directory, the parent of the file will be used as the currentDirectory.
* If the parent is not traversable, then it will walk up the parent tree
* until it finds a traversable directory, or hits the root of the
* file system.
*
* @beaninfo
* preferred: true
* bound: true
* description: The directory that the JFileChooser is showing files of.
*
* @param dir the current directory to point to
* @see #getCurrentDirectory
*/
public void setCurrentDirectory(File dir) {
File oldValue = currentDirectory;
if (dir != null && !dir.exists()) {
dir = currentDirectory;
}
if (dir == null) {
dir = getFileSystemView().getDefaultDirectory();
}
if (currentDirectory != null) {
/* Verify the toString of object */
if (this.currentDirectory.equals(dir)) {
return;
}
}
File prev = null;
while (!isTraversable(dir) && prev != dir) {
prev = dir;
dir = getFileSystemView().getParentDirectory(dir);
}
currentDirectory = dir;
firePropertyChange(DIRECTORY_CHANGED_PROPERTY, oldValue, currentDirectory);
}
/** {@collect.stats}
* Changes the directory to be set to the parent of the
* current directory.
*
* @see #getCurrentDirectory
*/
public void changeToParentDirectory() {
selectedFile = null;
File oldValue = getCurrentDirectory();
setCurrentDirectory(getFileSystemView().getParentDirectory(oldValue));
}
/** {@collect.stats}
* Tells the UI to rescan its files list from the current directory.
*/
public void rescanCurrentDirectory() {
getUI().rescanCurrentDirectory(this);
}
/** {@collect.stats}
* Makes sure that the specified file is viewable, and
* not hidden.
*
* @param f a File object
*/
public void ensureFileIsVisible(File f) {
getUI().ensureFileIsVisible(this, f);
}
// **************************************
// ***** JFileChooser Dialog methods *****
// **************************************
/** {@collect.stats}
* Pops up an "Open File" file chooser dialog. Note that the
* text that appears in the approve button is determined by
* the L&F.
*
* @param parent the parent component of the dialog,
* can be <code>null</code>;
* see <code>showDialog</code> for details
* @return the return state of the file chooser on popdown:
* <ul>
* <li>JFileChooser.CANCEL_OPTION
* <li>JFileChooser.APPROVE_OPTION
* <li>JFileChooser.ERROR_OPTION if an error occurs or the
* dialog is dismissed
* </ul>
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #showDialog
*/
public int showOpenDialog(Component parent) throws HeadlessException {
setDialogType(OPEN_DIALOG);
return showDialog(parent, null);
}
/** {@collect.stats}
* Pops up a "Save File" file chooser dialog. Note that the
* text that appears in the approve button is determined by
* the L&F.
*
* @param parent the parent component of the dialog,
* can be <code>null</code>;
* see <code>showDialog</code> for details
* @return the return state of the file chooser on popdown:
* <ul>
* <li>JFileChooser.CANCEL_OPTION
* <li>JFileChooser.APPROVE_OPTION
* <li>JFileChooser.ERROR_OPTION if an error occurs or the
* dialog is dismissed
* </ul>
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #showDialog
*/
public int showSaveDialog(Component parent) throws HeadlessException {
setDialogType(SAVE_DIALOG);
return showDialog(parent, null);
}
/** {@collect.stats}
* Pops a custom file chooser dialog with a custom approve button.
* For example, the following code
* pops up a file chooser with a "Run Application" button
* (instead of the normal "Save" or "Open" button):
* <pre>
* filechooser.showDialog(parentFrame, "Run Application");
* </pre>
*
* Alternatively, the following code does the same thing:
* <pre>
* JFileChooser chooser = new JFileChooser(null);
* chooser.setApproveButtonText("Run Application");
* chooser.showDialog(parentFrame, null);
* </pre>
*
* <!--PENDING(jeff) - the following method should be added to the api:
* showDialog(Component parent);-->
* <!--PENDING(kwalrath) - should specify modality and what
* "depends" means.-->
*
* <p>
*
* The <code>parent</code> argument determines two things:
* the frame on which the open dialog depends and
* the component whose position the look and feel
* should consider when placing the dialog. If the parent
* is a <code>Frame</code> object (such as a <code>JFrame</code>)
* then the dialog depends on the frame and
* the look and feel positions the dialog
* relative to the frame (for example, centered over the frame).
* If the parent is a component, then the dialog
* depends on the frame containing the component,
* and is positioned relative to the component
* (for example, centered over the component).
* If the parent is <code>null</code>, then the dialog depends on
* no visible window, and it's placed in a
* look-and-feel-dependent position
* such as the center of the screen.
*
* @param parent the parent component of the dialog;
* can be <code>null</code>
* @param approveButtonText the text of the <code>ApproveButton</code>
* @return the return state of the file chooser on popdown:
* <ul>
* <li>JFileChooser.CANCEL_OPTION
* <li>JFileChooser.APPROVE_OPTION
* <li>JFileCHooser.ERROR_OPTION if an error occurs or the
* dialog is dismissed
* </ul>
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public int showDialog(Component parent, String approveButtonText)
throws HeadlessException {
if(approveButtonText != null) {
setApproveButtonText(approveButtonText);
setDialogType(CUSTOM_DIALOG);
}
dialog = createDialog(parent);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
returnValue = CANCEL_OPTION;
}
});
returnValue = ERROR_OPTION;
rescanCurrentDirectory();
dialog.show();
firePropertyChange("JFileChooserDialogIsClosingProperty", dialog, null);
dialog.dispose();
dialog = null;
return returnValue;
}
/** {@collect.stats}
* Creates and returns a new <code>JDialog</code> wrapping
* <code>this</code> centered on the <code>parent</code>
* in the <code>parent</code>'s frame.
* This method can be overriden to further manipulate the dialog,
* to disable resizing, set the location, etc. Example:
* <pre>
* class MyFileChooser extends JFileChooser {
* protected JDialog createDialog(Component parent) throws HeadlessException {
* JDialog dialog = super.createDialog(parent);
* dialog.setLocation(300, 200);
* dialog.setResizable(false);
* return dialog;
* }
* }
* </pre>
*
* @param parent the parent component of the dialog;
* can be <code>null</code>
* @return a new <code>JDialog</code> containing this instance
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @since 1.4
*/
protected JDialog createDialog(Component parent) throws HeadlessException {
String title = getUI().getDialogTitle(this);
putClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY,
title);
JDialog dialog;
Window window = JOptionPane.getWindowForComponent(parent);
if (window instanceof Frame) {
dialog = new JDialog((Frame)window, title, true);
} else {
dialog = new JDialog((Dialog)window, title, true);
}
dialog.setComponentOrientation(this.getComponentOrientation());
Container contentPane = dialog.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(this, BorderLayout.CENTER);
if (JDialog.isDefaultLookAndFeelDecorated()) {
boolean supportsWindowDecorations =
UIManager.getLookAndFeel().getSupportsWindowDecorations();
if (supportsWindowDecorations) {
dialog.getRootPane().setWindowDecorationStyle(JRootPane.FILE_CHOOSER_DIALOG);
}
}
dialog.pack();
dialog.setLocationRelativeTo(parent);
return dialog;
}
// **************************
// ***** Dialog Options *****
// **************************
/** {@collect.stats}
* Returns the value of the <code>controlButtonsAreShown</code>
* property.
*
* @return the value of the <code>controlButtonsAreShown</code>
* property
*
* @see #setControlButtonsAreShown
* @since 1.3
*/
public boolean getControlButtonsAreShown() {
return controlsShown;
}
/** {@collect.stats}
* Sets the property
* that indicates whether the <i>approve</i> and <i>cancel</i>
* buttons are shown in the file chooser. This property
* is <code>true</code> by default. Look and feels
* that always show these buttons will ignore the value
* of this property.
* This method fires a property-changed event,
* using the string value of
* <code>CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY</code>
* as the name of the property.
*
* @param b <code>false</code> if control buttons should not be
* shown; otherwise, <code>true</code>
*
* @beaninfo
* preferred: true
* bound: true
* description: Sets whether the approve & cancel buttons are shown.
*
* @see #getControlButtonsAreShown
* @see #CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY
* @since 1.3
*/
public void setControlButtonsAreShown(boolean b) {
if(controlsShown == b) {
return;
}
boolean oldValue = controlsShown;
controlsShown = b;
firePropertyChange(CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY, oldValue, controlsShown);
}
/** {@collect.stats}
* Returns the type of this dialog. The default is
* <code>JFileChooser.OPEN_DIALOG</code>.
*
* @return the type of dialog to be displayed:
* <ul>
* <li>JFileChooser.OPEN_DIALOG
* <li>JFileChooser.SAVE_DIALOG
* <li>JFileChooser.CUSTOM_DIALOG
* </ul>
*
* @see #setDialogType
*/
public int getDialogType() {
return dialogType;
}
/** {@collect.stats}
* Sets the type of this dialog. Use <code>OPEN_DIALOG</code> when you
* want to bring up a file chooser that the user can use to open a file.
* Likewise, use <code>SAVE_DIALOG</code> for letting the user choose
* a file for saving.
* Use <code>CUSTOM_DIALOG</code> when you want to use the file
* chooser in a context other than "Open" or "Save".
* For instance, you might want to bring up a file chooser that allows
* the user to choose a file to execute. Note that you normally would not
* need to set the <code>JFileChooser</code> to use
* <code>CUSTOM_DIALOG</code>
* since a call to <code>setApproveButtonText</code> does this for you.
* The default dialog type is <code>JFileChooser.OPEN_DIALOG</code>.
*
* @param dialogType the type of dialog to be displayed:
* <ul>
* <li>JFileChooser.OPEN_DIALOG
* <li>JFileChooser.SAVE_DIALOG
* <li>JFileChooser.CUSTOM_DIALOG
* </ul>
*
* @exception IllegalArgumentException if <code>dialogType</code> is
* not legal
* @beaninfo
* preferred: true
* bound: true
* description: The type (open, save, custom) of the JFileChooser.
* enum:
* OPEN_DIALOG JFileChooser.OPEN_DIALOG
* SAVE_DIALOG JFileChooser.SAVE_DIALOG
* CUSTOM_DIALOG JFileChooser.CUSTOM_DIALOG
*
* @see #getDialogType
* @see #setApproveButtonText
*/
// PENDING(jeff) - fire button text change property
public void setDialogType(int dialogType) {
if(this.dialogType == dialogType) {
return;
}
if(!(dialogType == OPEN_DIALOG || dialogType == SAVE_DIALOG || dialogType == CUSTOM_DIALOG)) {
throw new IllegalArgumentException("Incorrect Dialog Type: " + dialogType);
}
int oldValue = this.dialogType;
this.dialogType = dialogType;
if(dialogType == OPEN_DIALOG || dialogType == SAVE_DIALOG) {
setApproveButtonText(null);
}
firePropertyChange(DIALOG_TYPE_CHANGED_PROPERTY, oldValue, dialogType);
}
/** {@collect.stats}
* Sets the string that goes in the <code>JFileChooser</code> window's
* title bar.
*
* @param dialogTitle the new <code>String</code> for the title bar
*
* @beaninfo
* preferred: true
* bound: true
* description: The title of the JFileChooser dialog window.
*
* @see #getDialogTitle
*
*/
public void setDialogTitle(String dialogTitle) {
String oldValue = this.dialogTitle;
this.dialogTitle = dialogTitle;
if(dialog != null) {
dialog.setTitle(dialogTitle);
}
firePropertyChange(DIALOG_TITLE_CHANGED_PROPERTY, oldValue, dialogTitle);
}
/** {@collect.stats}
* Gets the string that goes in the <code>JFileChooser</code>'s titlebar.
*
* @see #setDialogTitle
*/
public String getDialogTitle() {
return dialogTitle;
}
// ************************************
// ***** JFileChooser View Options *****
// ************************************
/** {@collect.stats}
* Sets the tooltip text used in the <code>ApproveButton</code>.
* If <code>null</code>, the UI object will determine the button's text.
*
* @beaninfo
* preferred: true
* bound: true
* description: The tooltip text for the ApproveButton.
*
* @param toolTipText the tooltip text for the approve button
* @see #setApproveButtonText
* @see #setDialogType
* @see #showDialog
*/
public void setApproveButtonToolTipText(String toolTipText) {
if(approveButtonToolTipText == toolTipText) {
return;
}
String oldValue = approveButtonToolTipText;
approveButtonToolTipText = toolTipText;
firePropertyChange(APPROVE_BUTTON_TOOL_TIP_TEXT_CHANGED_PROPERTY, oldValue, approveButtonToolTipText);
}
/** {@collect.stats}
* Returns the tooltip text used in the <code>ApproveButton</code>.
* If <code>null</code>, the UI object will determine the button's text.
*
* @return the tooltip text used for the approve button
*
* @see #setApproveButtonText
* @see #setDialogType
* @see #showDialog
*/
public String getApproveButtonToolTipText() {
return approveButtonToolTipText;
}
/** {@collect.stats}
* Returns the approve button's mnemonic.
* @return an integer value for the mnemonic key
*
* @see #setApproveButtonMnemonic
*/
public int getApproveButtonMnemonic() {
return approveButtonMnemonic;
}
/** {@collect.stats}
* Sets the approve button's mnemonic using a numeric keycode.
*
* @param mnemonic an integer value for the mnemonic key
*
* @beaninfo
* preferred: true
* bound: true
* description: The mnemonic key accelerator for the ApproveButton.
*
* @see #getApproveButtonMnemonic
*/
public void setApproveButtonMnemonic(int mnemonic) {
if(approveButtonMnemonic == mnemonic) {
return;
}
int oldValue = approveButtonMnemonic;
approveButtonMnemonic = mnemonic;
firePropertyChange(APPROVE_BUTTON_MNEMONIC_CHANGED_PROPERTY, oldValue, approveButtonMnemonic);
}
/** {@collect.stats}
* Sets the approve button's mnemonic using a character.
* @param mnemonic a character value for the mnemonic key
*
* @see #getApproveButtonMnemonic
*/
public void setApproveButtonMnemonic(char mnemonic) {
int vk = (int) mnemonic;
if(vk >= 'a' && vk <='z') {
vk -= ('a' - 'A');
}
setApproveButtonMnemonic(vk);
}
/** {@collect.stats}
* Sets the text used in the <code>ApproveButton</code> in the
* <code>FileChooserUI</code>.
*
* @beaninfo
* preferred: true
* bound: true
* description: The text that goes in the ApproveButton.
*
* @param approveButtonText the text used in the <code>ApproveButton</code>
*
* @see #getApproveButtonText
* @see #setDialogType
* @see #showDialog
*/
// PENDING(jeff) - have ui set this on dialog type change
public void setApproveButtonText(String approveButtonText) {
if(this.approveButtonText == approveButtonText) {
return;
}
String oldValue = this.approveButtonText;
this.approveButtonText = approveButtonText;
firePropertyChange(APPROVE_BUTTON_TEXT_CHANGED_PROPERTY, oldValue, approveButtonText);
}
/** {@collect.stats}
* Returns the text used in the <code>ApproveButton</code> in the
* <code>FileChooserUI</code>.
* If <code>null</code>, the UI object will determine the button's text.
*
* Typically, this would be "Open" or "Save".
*
* @return the text used in the <code>ApproveButton</code>
*
* @see #setApproveButtonText
* @see #setDialogType
* @see #showDialog
*/
public String getApproveButtonText() {
return approveButtonText;
}
/** {@collect.stats}
* Gets the list of user choosable file filters.
*
* @return a <code>FileFilter</code> array containing all the choosable
* file filters
*
* @see #addChoosableFileFilter
* @see #removeChoosableFileFilter
* @see #resetChoosableFileFilters
*/
public FileFilter[] getChoosableFileFilters() {
FileFilter[] filterArray = new FileFilter[filters.size()];
filters.copyInto(filterArray);
return filterArray;
}
/** {@collect.stats}
* Adds a filter to the list of user choosable file filters.
* For information on setting the file selection mode, see
* {@link #setFileSelectionMode setFileSelectionMode}.
*
* @param filter the <code>FileFilter</code> to add to the choosable file
* filter list
*
* @beaninfo
* preferred: true
* bound: true
* description: Adds a filter to the list of user choosable file filters.
*
* @see #getChoosableFileFilters
* @see #removeChoosableFileFilter
* @see #resetChoosableFileFilters
* @see #setFileSelectionMode
*/
public void addChoosableFileFilter(FileFilter filter) {
if(filter != null && !filters.contains(filter)) {
FileFilter[] oldValue = getChoosableFileFilters();
filters.addElement(filter);
firePropertyChange(CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY, oldValue, getChoosableFileFilters());
if (fileFilter == null && filters.size() == 1) {
setFileFilter(filter);
}
}
}
/** {@collect.stats}
* Removes a filter from the list of user choosable file filters. Returns
* true if the file filter was removed.
*
* @see #addChoosableFileFilter
* @see #getChoosableFileFilters
* @see #resetChoosableFileFilters
*/
public boolean removeChoosableFileFilter(FileFilter f) {
if(filters.contains(f)) {
if(getFileFilter() == f) {
setFileFilter(null);
}
FileFilter[] oldValue = getChoosableFileFilters();
filters.removeElement(f);
firePropertyChange(CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY, oldValue, getChoosableFileFilters());
return true;
} else {
return false;
}
}
/** {@collect.stats}
* Resets the choosable file filter list to its starting state. Normally,
* this removes all added file filters while leaving the
* <code>AcceptAll</code> file filter.
*
* @see #addChoosableFileFilter
* @see #getChoosableFileFilters
* @see #removeChoosableFileFilter
*/
public void resetChoosableFileFilters() {
FileFilter[] oldValue = getChoosableFileFilters();
setFileFilter(null);
filters.removeAllElements();
if(isAcceptAllFileFilterUsed()) {
addChoosableFileFilter(getAcceptAllFileFilter());
}
firePropertyChange(CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY, oldValue, getChoosableFileFilters());
}
/** {@collect.stats}
* Returns the <code>AcceptAll</code> file filter.
* For example, on Microsoft Windows this would be All Files (*.*).
*/
public FileFilter getAcceptAllFileFilter() {
FileFilter filter = null;
if(getUI() != null) {
filter = getUI().getAcceptAllFileFilter(this);
}
return filter;
}
/** {@collect.stats}
* Returns whether the <code>AcceptAll FileFilter</code> is used.
* @return true if the <code>AcceptAll FileFilter</code> is used
* @see #setAcceptAllFileFilterUsed
* @since 1.3
*/
public boolean isAcceptAllFileFilterUsed() {
return useAcceptAllFileFilter;
}
/** {@collect.stats}
* Determines whether the <code>AcceptAll FileFilter</code> is used
* as an available choice in the choosable filter list.
* If false, the <code>AcceptAll</code> file filter is removed from
* the list of available file filters.
* If true, the <code>AcceptAll</code> file filter will become the
* the actively used file filter.
*
* @beaninfo
* preferred: true
* bound: true
* description: Sets whether the AcceptAll FileFilter is used as an available choice in the choosable filter list.
*
* @see #isAcceptAllFileFilterUsed
* @see #getAcceptAllFileFilter
* @see #setFileFilter
* @since 1.3
*/
public void setAcceptAllFileFilterUsed(boolean b) {
boolean oldValue = useAcceptAllFileFilter;
useAcceptAllFileFilter = b;
if(!b) {
removeChoosableFileFilter(getAcceptAllFileFilter());
} else {
removeChoosableFileFilter(getAcceptAllFileFilter());
addChoosableFileFilter(getAcceptAllFileFilter());
}
firePropertyChange(ACCEPT_ALL_FILE_FILTER_USED_CHANGED_PROPERTY, oldValue, useAcceptAllFileFilter);
}
/** {@collect.stats}
* Returns the accessory component.
*
* @return this JFileChooser's accessory component, or null
* @see #setAccessory
*/
public JComponent getAccessory() {
return accessory;
}
/** {@collect.stats}
* Sets the accessory component. An accessory is often used to show a
* preview image of the selected file; however, it can be used for anything
* that the programmer wishes, such as extra custom file chooser controls.
*
* <p>
* Note: if there was a previous accessory, you should unregister
* any listeners that the accessory might have registered with the
* file chooser.
*
* @beaninfo
* preferred: true
* bound: true
* description: Sets the accessory component on the JFileChooser.
*/
public void setAccessory(JComponent newAccessory) {
JComponent oldValue = accessory;
accessory = newAccessory;
firePropertyChange(ACCESSORY_CHANGED_PROPERTY, oldValue, accessory);
}
/** {@collect.stats}
* Sets the <code>JFileChooser</code> to allow the user to just
* select files, just select
* directories, or select both files and directories. The default is
* <code>JFilesChooser.FILES_ONLY</code>.
*
* @param mode the type of files to be displayed:
* <ul>
* <li>JFileChooser.FILES_ONLY
* <li>JFileChooser.DIRECTORIES_ONLY
* <li>JFileChooser.FILES_AND_DIRECTORIES
* </ul>
*
* @exception IllegalArgumentException if <code>mode</code> is an
* illegal file selection mode
* @beaninfo
* preferred: true
* bound: true
* description: Sets the types of files that the JFileChooser can choose.
* enum: FILES_ONLY JFileChooser.FILES_ONLY
* DIRECTORIES_ONLY JFileChooser.DIRECTORIES_ONLY
* FILES_AND_DIRECTORIES JFileChooser.FILES_AND_DIRECTORIES
*
*
* @see #getFileSelectionMode
*/
public void setFileSelectionMode(int mode) {
if(fileSelectionMode == mode) {
return;
}
if ((mode == FILES_ONLY) || (mode == DIRECTORIES_ONLY) || (mode == FILES_AND_DIRECTORIES)) {
int oldValue = fileSelectionMode;
fileSelectionMode = mode;
firePropertyChange(FILE_SELECTION_MODE_CHANGED_PROPERTY, oldValue, fileSelectionMode);
} else {
throw new IllegalArgumentException("Incorrect Mode for file selection: " + mode);
}
}
/** {@collect.stats}
* Returns the current file-selection mode. The default is
* <code>JFilesChooser.FILES_ONLY</code>.
*
* @return the type of files to be displayed, one of the following:
* <ul>
* <li>JFileChooser.FILES_ONLY
* <li>JFileChooser.DIRECTORIES_ONLY
* <li>JFileChooser.FILES_AND_DIRECTORIES
* </ul>
* @see #setFileSelectionMode
*/
public int getFileSelectionMode() {
return fileSelectionMode;
}
/** {@collect.stats}
* Convenience call that determines if files are selectable based on the
* current file selection mode.
*
* @see #setFileSelectionMode
* @see #getFileSelectionMode
*/
public boolean isFileSelectionEnabled() {
return ((fileSelectionMode == FILES_ONLY) || (fileSelectionMode == FILES_AND_DIRECTORIES));
}
/** {@collect.stats}
* Convenience call that determines if directories are selectable based
* on the current file selection mode.
*
* @see #setFileSelectionMode
* @see #getFileSelectionMode
*/
public boolean isDirectorySelectionEnabled() {
return ((fileSelectionMode == DIRECTORIES_ONLY) || (fileSelectionMode == FILES_AND_DIRECTORIES));
}
/** {@collect.stats}
* Sets the file chooser to allow multiple file selections.
*
* @param b true if multiple files may be selected
* @beaninfo
* bound: true
* description: Sets multiple file selection mode.
*
* @see #isMultiSelectionEnabled
*/
public void setMultiSelectionEnabled(boolean b) {
if(multiSelectionEnabled == b) {
return;
}
boolean oldValue = multiSelectionEnabled;
multiSelectionEnabled = b;
firePropertyChange(MULTI_SELECTION_ENABLED_CHANGED_PROPERTY, oldValue, multiSelectionEnabled);
}
/** {@collect.stats}
* Returns true if multiple files can be selected.
* @return true if multiple files can be selected
* @see #setMultiSelectionEnabled
*/
public boolean isMultiSelectionEnabled() {
return multiSelectionEnabled;
}
/** {@collect.stats}
* Returns true if hidden files are not shown in the file chooser;
* otherwise, returns false.
*
* @return the status of the file hiding property
* @see #setFileHidingEnabled
*/
public boolean isFileHidingEnabled() {
return useFileHiding;
}
/** {@collect.stats}
* Sets file hiding on or off. If true, hidden files are not shown
* in the file chooser. The job of determining which files are
* shown is done by the <code>FileView</code>.
*
* @beaninfo
* preferred: true
* bound: true
* description: Sets file hiding on or off.
*
* @param b the boolean value that determines whether file hiding is
* turned on
* @see #isFileHidingEnabled
*/
public void setFileHidingEnabled(boolean b) {
// Dump showFilesListener since we'll ignore it from now on
if (showFilesListener != null) {
Toolkit.getDefaultToolkit().removePropertyChangeListener(SHOW_HIDDEN_PROP, showFilesListener);
showFilesListener = null;
}
boolean oldValue = useFileHiding;
useFileHiding = b;
firePropertyChange(FILE_HIDING_CHANGED_PROPERTY, oldValue, useFileHiding);
}
/** {@collect.stats}
* Sets the current file filter. The file filter is used by the
* file chooser to filter out files from the user's view.
*
* @beaninfo
* preferred: true
* bound: true
* description: Sets the File Filter used to filter out files of type.
*
* @param filter the new current file filter to use
* @see #getFileFilter
*/
public void setFileFilter(FileFilter filter) {
FileFilter oldValue = fileFilter;
fileFilter = filter;
if (filter != null) {
if (isMultiSelectionEnabled() && selectedFiles != null && selectedFiles.length > 0) {
Vector fList = new Vector();
boolean failed = false;
for (int i = 0; i < selectedFiles.length; i++) {
if (filter.accept(selectedFiles[i])) {
fList.add(selectedFiles[i]);
} else {
failed = true;
}
}
if (failed) {
setSelectedFiles((fList.size() == 0) ? null : (File[])fList.toArray(new File[fList.size()]));
}
} else if (selectedFile != null && !filter.accept(selectedFile)) {
setSelectedFile(null);
}
}
firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, oldValue, fileFilter);
}
/** {@collect.stats}
* Returns the currently selected file filter.
*
* @return the current file filter
* @see #setFileFilter
* @see #addChoosableFileFilter
*/
public FileFilter getFileFilter() {
return fileFilter;
}
/** {@collect.stats}
* Sets the file view to used to retrieve UI information, such as
* the icon that represents a file or the type description of a file.
*
* @beaninfo
* preferred: true
* bound: true
* description: Sets the File View used to get file type information.
*
* @see #getFileView
*/
public void setFileView(FileView fileView) {
FileView oldValue = this.fileView;
this.fileView = fileView;
firePropertyChange(FILE_VIEW_CHANGED_PROPERTY, oldValue, fileView);
}
/** {@collect.stats}
* Returns the current file view.
*
* @see #setFileView
*/
public FileView getFileView() {
return fileView;
}
// ******************************
// *****FileView delegation *****
// ******************************
// NOTE: all of the following methods attempt to delegate
// first to the client set fileView, and if <code>null</code> is returned
// (or there is now client defined fileView) then calls the
// UI's default fileView.
/** {@collect.stats}
* Returns the filename.
* @param f the <code>File</code>
* @return the <code>String</code> containing the filename for
* <code>f</code>
* @see FileView#getName
*/
public String getName(File f) {
String filename = null;
if(f != null) {
if(getFileView() != null) {
filename = getFileView().getName(f);
}
if(filename == null && uiFileView != null) {
filename = uiFileView.getName(f);
}
}
return filename;
}
/** {@collect.stats}
* Returns the file description.
* @param f the <code>File</code>
* @return the <code>String</code> containing the file description for
* <code>f</code>
* @see FileView#getDescription
*/
public String getDescription(File f) {
String description = null;
if(f != null) {
if(getFileView() != null) {
description = getFileView().getDescription(f);
}
if(description == null && uiFileView != null) {
description = uiFileView.getDescription(f);
}
}
return description;
}
/** {@collect.stats}
* Returns the file type.
* @param f the <code>File</code>
* @return the <code>String</code> containing the file type description for
* <code>f</code>
* @see FileView#getTypeDescription
*/
public String getTypeDescription(File f) {
String typeDescription = null;
if(f != null) {
if(getFileView() != null) {
typeDescription = getFileView().getTypeDescription(f);
}
if(typeDescription == null && uiFileView != null) {
typeDescription = uiFileView.getTypeDescription(f);
}
}
return typeDescription;
}
/** {@collect.stats}
* Returns the icon for this file or type of file, depending
* on the system.
* @param f the <code>File</code>
* @return the <code>Icon</code> for this file, or type of file
* @see FileView#getIcon
*/
public Icon getIcon(File f) {
Icon icon = null;
if (f != null) {
if(getFileView() != null) {
icon = getFileView().getIcon(f);
}
if(icon == null && uiFileView != null) {
icon = uiFileView.getIcon(f);
}
}
return icon;
}
/** {@collect.stats}
* Returns true if the file (directory) can be visited.
* Returns false if the directory cannot be traversed.
* @param f the <code>File</code>
* @return true if the file/directory can be traversed, otherwise false
* @see FileView#isTraversable
*/
public boolean isTraversable(File f) {
Boolean traversable = null;
if (f != null) {
if (getFileView() != null) {
traversable = getFileView().isTraversable(f);
}
if (traversable == null && uiFileView != null) {
traversable = uiFileView.isTraversable(f);
}
if (traversable == null) {
traversable = getFileSystemView().isTraversable(f);
}
}
return (traversable != null && traversable.booleanValue());
}
/** {@collect.stats}
* Returns true if the file should be displayed.
* @param f the <code>File</code>
* @return true if the file should be displayed, otherwise false
* @see FileFilter#accept
*/
public boolean accept(File f) {
boolean shown = true;
if(f != null && fileFilter != null) {
shown = fileFilter.accept(f);
}
return shown;
}
/** {@collect.stats}
* Sets the file system view that the <code>JFileChooser</code> uses for
* accessing and creating file system resources, such as finding
* the floppy drive and getting a list of root drives.
* @param fsv the new <code>FileSystemView</code>
*
* @beaninfo
* expert: true
* bound: true
* description: Sets the FileSytemView used to get filesystem information.
*
* @see FileSystemView
*/
public void setFileSystemView(FileSystemView fsv) {
FileSystemView oldValue = fileSystemView;
fileSystemView = fsv;
firePropertyChange(FILE_SYSTEM_VIEW_CHANGED_PROPERTY, oldValue, fileSystemView);
}
/** {@collect.stats}
* Returns the file system view.
* @return the <code>FileSystemView</code> object
* @see #setFileSystemView
*/
public FileSystemView getFileSystemView() {
return fileSystemView;
}
// **************************
// ***** Event Handling *****
// **************************
/** {@collect.stats}
* Called by the UI when the user hits the Approve button
* (labeled "Open" or "Save", by default). This can also be
* called by the programmer.
* This method causes an action event to fire
* with the command string equal to
* <code>APPROVE_SELECTION</code>.
*
* @see #APPROVE_SELECTION
*/
public void approveSelection() {
returnValue = APPROVE_OPTION;
if(dialog != null) {
dialog.setVisible(false);
}
fireActionPerformed(APPROVE_SELECTION);
}
/** {@collect.stats}
* Called by the UI when the user chooses the Cancel button.
* This can also be called by the programmer.
* This method causes an action event to fire
* with the command string equal to
* <code>CANCEL_SELECTION</code>.
*
* @see #CANCEL_SELECTION
*/
public void cancelSelection() {
returnValue = CANCEL_OPTION;
if(dialog != null) {
dialog.setVisible(false);
}
fireActionPerformed(CANCEL_SELECTION);
}
/** {@collect.stats}
* Adds an <code>ActionListener</code> to the file chooser.
*
* @param l the listener to be added
*
* @see #approveSelection
* @see #cancelSelection
*/
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
/** {@collect.stats}
* Removes an <code>ActionListener</code> from the file chooser.
*
* @param l the listener to be removed
*
* @see #addActionListener
*/
public void removeActionListener(ActionListener l) {
listenerList.remove(ActionListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the action listeners
* registered on this file chooser.
*
* @return all of this file chooser's <code>ActionListener</code>s
* or an empty
* array if no action listeners are currently registered
*
* @see #addActionListener
* @see #removeActionListener
*
* @since 1.4
*/
public ActionListener[] getActionListeners() {
return (ActionListener[])listenerList.getListeners(
ActionListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>command</code> parameter.
*
* @see EventListenerList
*/
protected void fireActionPerformed(String command) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
long mostRecentEventTime = EventQueue.getMostRecentEventTime();
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent) {
modifiers = ((InputEvent)currentEvent).getModifiers();
} else if (currentEvent instanceof ActionEvent) {
modifiers = ((ActionEvent)currentEvent).getModifiers();
}
ActionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ActionListener.class) {
// Lazily create the event:
if (e == null) {
e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
command, mostRecentEventTime,
modifiers);
}
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
}
private static class WeakPCL implements PropertyChangeListener {
WeakReference<JFileChooser> jfcRef;
public WeakPCL(JFileChooser jfc) {
jfcRef = new WeakReference(jfc);
}
public void propertyChange(PropertyChangeEvent ev) {
assert ev.getPropertyName().equals(SHOW_HIDDEN_PROP);
JFileChooser jfc = jfcRef.get();
if (jfc == null) {
// Our JFileChooser is no longer around, so we no longer need to
// listen for PropertyChangeEvents.
Toolkit.getDefaultToolkit().removePropertyChangeListener(SHOW_HIDDEN_PROP, this);
}
else {
boolean oldValue = jfc.useFileHiding;
jfc.useFileHiding = !((Boolean)ev.getNewValue()).booleanValue();
jfc.firePropertyChange(FILE_HIDING_CHANGED_PROPERTY, oldValue, jfc.useFileHiding);
}
}
}
// *********************************
// ***** Pluggable L&F methods *****
// *********************************
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
if (isAcceptAllFileFilterUsed()) {
removeChoosableFileFilter(getAcceptAllFileFilter());
}
FileChooserUI ui = ((FileChooserUI)UIManager.getUI(this));
if (fileSystemView == null) {
// We were probably deserialized
setFileSystemView(FileSystemView.getFileSystemView());
}
setUI(ui);
uiFileView = getUI().getFileView(this);
if(isAcceptAllFileFilterUsed()) {
addChoosableFileFilter(getAcceptAllFileFilter());
}
}
/** {@collect.stats}
* Returns a string that specifies the name of the L&F class
* that renders this component.
*
* @return the string "FileChooserUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
* @beaninfo
* expert: true
* description: A string that specifies the name of the L&F class.
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Gets the UI object which implements the L&F for this component.
*
* @return the FileChooserUI object that implements the FileChooserUI L&F
*/
public FileChooserUI getUI() {
return (FileChooserUI) ui;
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
installShowFilesListener();
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
FileSystemView fsv = null;
if (isAcceptAllFileFilterUsed()) {
//The AcceptAllFileFilter is UI specific, it will be reset by
//updateUI() after deserialization
removeChoosableFileFilter(getAcceptAllFileFilter());
}
if (fileSystemView.equals(FileSystemView.getFileSystemView())) {
//The default FileSystemView is platform specific, it will be
//reset by updateUI() after deserialization
fsv = fileSystemView;
fileSystemView = null;
}
s.defaultWriteObject();
if (fsv != null) {
fileSystemView = fsv;
}
if (isAcceptAllFileFilterUsed()) {
addChoosableFileFilter(getAcceptAllFileFilter());
}
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JFileChooser</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JFileChooser</code>
*/
protected String paramString() {
String approveButtonTextString = (approveButtonText != null ?
approveButtonText: "");
String dialogTitleString = (dialogTitle != null ?
dialogTitle: "");
String dialogTypeString;
if (dialogType == OPEN_DIALOG) {
dialogTypeString = "OPEN_DIALOG";
} else if (dialogType == SAVE_DIALOG) {
dialogTypeString = "SAVE_DIALOG";
} else if (dialogType == CUSTOM_DIALOG) {
dialogTypeString = "CUSTOM_DIALOG";
} else dialogTypeString = "";
String returnValueString;
if (returnValue == CANCEL_OPTION) {
returnValueString = "CANCEL_OPTION";
} else if (returnValue == APPROVE_OPTION) {
returnValueString = "APPROVE_OPTION";
} else if (returnValue == ERROR_OPTION) {
returnValueString = "ERROR_OPTION";
} else returnValueString = "";
String useFileHidingString = (useFileHiding ?
"true" : "false");
String fileSelectionModeString;
if (fileSelectionMode == FILES_ONLY) {
fileSelectionModeString = "FILES_ONLY";
} else if (fileSelectionMode == DIRECTORIES_ONLY) {
fileSelectionModeString = "DIRECTORIES_ONLY";
} else if (fileSelectionMode == FILES_AND_DIRECTORIES) {
fileSelectionModeString = "FILES_AND_DIRECTORIES";
} else fileSelectionModeString = "";
String currentDirectoryString = (currentDirectory != null ?
currentDirectory.toString() : "");
String selectedFileString = (selectedFile != null ?
selectedFile.toString() : "");
return super.paramString() +
",approveButtonText=" + approveButtonTextString +
",currentDirectory=" + currentDirectoryString +
",dialogTitle=" + dialogTitleString +
",dialogType=" + dialogTypeString +
",fileSelectionMode=" + fileSelectionModeString +
",returnValue=" + returnValueString +
",selectedFile=" + selectedFileString +
",useFileHiding=" + useFileHidingString;
}
/////////////////
// Accessibility support
////////////////
protected AccessibleContext accessibleContext = null;
/** {@collect.stats}
* Gets the AccessibleContext associated with this JFileChooser.
* For file choosers, the AccessibleContext takes the form of an
* AccessibleJFileChooser.
* A new AccessibleJFileChooser instance is created if necessary.
*
* @return an AccessibleJFileChooser that serves as the
* AccessibleContext of this JFileChooser
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJFileChooser();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JFileChooser</code> class. It provides an implementation of the
* Java Accessibility API appropriate to file chooser user-interface
* elements.
*/
protected class AccessibleJFileChooser extends AccessibleJComponent {
/** {@collect.stats}
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.FILE_CHOOSER;
}
} // inner class AccessibleJFileChooser
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
/** {@collect.stats}
* Autoscroller is responsible for generating synthetic mouse dragged
* events. It is the responsibility of the Component (or its MouseListeners)
* that receive the events to do the actual scrolling in response to the
* mouse dragged events.
*
* @author Dave Moore
* @author Scott Violet
*/
class Autoscroller implements ActionListener {
/** {@collect.stats}
* Global Autoscroller.
*/
private static Autoscroller sharedInstance = new Autoscroller();
// As there can only ever be one autoscroller active these fields are
// static. The Timer is recreated as necessary to target the appropriate
// Autoscroller instance.
private static MouseEvent event;
private static Timer timer;
private static JComponent component;
//
// The public API, all methods are cover methods for an instance method
//
/** {@collect.stats}
* Stops autoscroll events from happening on the specified component.
*/
public static void stop(JComponent c) {
sharedInstance._stop(c);
}
/** {@collect.stats}
* Stops autoscroll events from happening on the specified component.
*/
public static boolean isRunning(JComponent c) {
return sharedInstance._isRunning(c);
}
/** {@collect.stats}
* Invoked when a mouse dragged event occurs, will start the autoscroller
* if necessary.
*/
public static void processMouseDragged(MouseEvent e) {
sharedInstance._processMouseDragged(e);
}
Autoscroller() {
}
/** {@collect.stats}
* Starts the timer targeting the passed in component.
*/
private void start(JComponent c, MouseEvent e) {
Point screenLocation = c.getLocationOnScreen();
if (component != c) {
_stop(component);
}
component = c;
event = new MouseEvent(component, e.getID(), e.getWhen(),
e.getModifiers(), e.getX() + screenLocation.x,
e.getY() + screenLocation.y,
e.getXOnScreen(),
e.getYOnScreen(),
e.getClickCount(), e.isPopupTrigger(),
MouseEvent.NOBUTTON);
if (timer == null) {
timer = new Timer(100, this);
}
if (!timer.isRunning()) {
timer.start();
}
}
//
// Methods mirror the public static API
//
/** {@collect.stats}
* Stops scrolling for the passed in widget.
*/
private void _stop(JComponent c) {
if (component == c) {
if (timer != null) {
timer.stop();
}
timer = null;
event = null;
component = null;
}
}
/** {@collect.stats}
* Returns true if autoscrolling is currently running for the specified
* widget.
*/
private boolean _isRunning(JComponent c) {
return (c == component && timer != null && timer.isRunning());
}
/** {@collect.stats}
* MouseListener method, invokes start/stop as necessary.
*/
private void _processMouseDragged(MouseEvent e) {
JComponent component = (JComponent)e.getComponent();
boolean stop = true;
if (component.isShowing()) {
Rectangle visibleRect = component.getVisibleRect();
stop = visibleRect.contains(e.getX(), e.getY());
}
if (stop) {
_stop(component);
} else {
start(component, e);
}
}
//
// ActionListener
//
/** {@collect.stats}
* ActionListener method. Invoked when the Timer fires. This will scroll
* if necessary.
*/
public void actionPerformed(ActionEvent x) {
JComponent component = Autoscroller.component;
if (component == null || !component.isShowing() || (event == null)) {
_stop(component);
return;
}
Point screenLocation = component.getLocationOnScreen();
MouseEvent e = new MouseEvent(component, event.getID(),
event.getWhen(), event.getModifiers(),
event.getX() - screenLocation.x,
event.getY() - screenLocation.y,
event.getXOnScreen(),
event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(),
MouseEvent.NOBUTTON);
component.superProcessMouseMotionEvent(e);
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.