code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
/*
* Copyright (c) 2000, 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.util.*;
import javax.swing.event.*;
/** {@collect.stats}
* This class provides the ChangeListener part of the
* SpinnerModel interface that should be suitable for most concrete SpinnerModel
* implementations. Subclasses must provide an implementation of the
* <code>setValue</code>, <code>getValue</code>, <code>getNextValue</code> and
* <code>getPreviousValue</code> methods.
*
* @see JSpinner
* @see SpinnerModel
* @see SpinnerListModel
* @see SpinnerNumberModel
* @see SpinnerDateModel
*
* @author Hans Muller
* @since 1.4
*/
public abstract class AbstractSpinnerModel implements SpinnerModel
{
/** {@collect.stats}
* Only one ChangeEvent 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".
*/
private transient ChangeEvent changeEvent = null;
/** {@collect.stats}
* The list of ChangeListeners for this model. Subclasses may
* store their own listeners here.
*/
protected EventListenerList listenerList = new EventListenerList();
/** {@collect.stats}
* Adds a ChangeListener to the model's listener list. The
* ChangeListeners must be notified when the models value changes.
*
* @param l the ChangeListener to add
* @see #removeChangeListener
* @see SpinnerModel#addChangeListener
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a ChangeListener from the model's listener list.
*
* @param l the ChangeListener to remove
* @see #addChangeListener
* @see SpinnerModel#removeChangeListener
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this AbstractSpinnerModel with addChangeListener().
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Run each ChangeListeners stateChanged() method.
*
* @see #setValue
* @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}
* Return an array of all the listeners of the given type that
* were added to this model. For example to find all of the
* ChangeListeners added to this model:
* <pre>
* myAbstractSpinnerModel.getListeners(ChangeListener.class);
* </pre>
*
* @param listenerType the type of listeners to return, e.g. ChangeListener.class
* @return all of the objects receiving <em>listenerType</em> notifications
* from this model
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
}
|
Java
|
/*
* Copyright (c) 1998, 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.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.*;
import javax.swing.colorchooser.*;
import javax.swing.plaf.ColorChooserUI;
import javax.swing.event.*;
import javax.accessibility.*;
import sun.swing.SwingUtilities2;
/** {@collect.stats}
* <code>JColorChooser</code> provides a pane of controls designed to allow
* a user to manipulate and select a color.
* For information about using color choosers, see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/colorchooser.html">How to Use Color Choosers</a>,
* a section in <em>The Java Tutorial</em>.
*
* <p>
*
* This class provides three levels of API:
* <ol>
* <li>A static convenience method which shows a modal color-chooser
* dialog and returns the color selected by the user.
* <li>A static convenience method for creating a color-chooser dialog
* where <code>ActionListeners</code> can be specified to be invoked when
* the user presses one of the dialog buttons.
* <li>The ability to create instances of <code>JColorChooser</code> panes
* directly (within any container). <code>PropertyChange</code> listeners
* can be added to detect when the current "color" property changes.
* </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}.
*
*
* @beaninfo
* attribute: isContainer false
* description: A component that supports selecting a Color.
*
*
* @author James Gosling
* @author Amy Fowler
* @author Steve Wilson
*/
public class JColorChooser extends JComponent implements Accessible {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ColorChooserUI";
private ColorSelectionModel selectionModel;
private JComponent previewPanel;
private AbstractColorChooserPanel[] chooserPanels = new AbstractColorChooserPanel[0];
private boolean dragEnabled;
/** {@collect.stats}
* The selection model property name.
*/
public static final String SELECTION_MODEL_PROPERTY = "selectionModel";
/** {@collect.stats}
* The preview panel property name.
*/
public static final String PREVIEW_PANEL_PROPERTY = "previewPanel";
/** {@collect.stats}
* The chooserPanel array property name.
*/
public static final String CHOOSER_PANELS_PROPERTY = "chooserPanels";
/** {@collect.stats}
* Shows a modal color-chooser dialog and blocks until the
* dialog is hidden. If the user presses the "OK" button, then
* this method hides/disposes the dialog and returns the selected color.
* If the user presses the "Cancel" button or closes the dialog without
* pressing "OK", then this method hides/disposes the dialog and returns
* <code>null</code>.
*
* @param component the parent <code>Component</code> for the dialog
* @param title the String containing the dialog's title
* @param initialColor the initial Color set when the color-chooser is shown
* @return the selected color or <code>null</code> if the user opted out
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static Color showDialog(Component component,
String title, Color initialColor) throws HeadlessException {
final JColorChooser pane = new JColorChooser(initialColor != null?
initialColor : Color.white);
ColorTracker ok = new ColorTracker(pane);
JDialog dialog = createDialog(component, title, true, pane, ok, null);
dialog.addComponentListener(new ColorChooserDialog.DisposeOnClose());
dialog.show(); // blocks until user brings dialog down...
return ok.getColor();
}
/** {@collect.stats}
* Creates and returns a new dialog containing the specified
* <code>ColorChooser</code> pane along with "OK", "Cancel", and "Reset"
* buttons. If the "OK" or "Cancel" buttons are pressed, the dialog is
* automatically hidden (but not disposed). If the "Reset"
* button is pressed, the color-chooser's color will be reset to the
* color which was set the last time <code>show</code> was invoked on the
* dialog and the dialog will remain showing.
*
* @param c the parent component for the dialog
* @param title the title for the dialog
* @param modal a boolean. When true, the remainder of the program
* is inactive until the dialog is closed.
* @param chooserPane the color-chooser to be placed inside the dialog
* @param okListener the ActionListener invoked when "OK" is pressed
* @param cancelListener the ActionListener invoked when "Cancel" is pressed
* @return a new dialog containing the color-chooser pane
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static JDialog createDialog(Component c, String title, boolean modal,
JColorChooser chooserPane, ActionListener okListener,
ActionListener cancelListener) throws HeadlessException {
Window window = JOptionPane.getWindowForComponent(c);
ColorChooserDialog dialog;
if (window instanceof Frame) {
dialog = new ColorChooserDialog((Frame)window, title, modal, c, chooserPane,
okListener, cancelListener);
} else {
dialog = new ColorChooserDialog((Dialog)window, title, modal, c, chooserPane,
okListener, cancelListener);
}
return dialog;
}
/** {@collect.stats}
* Creates a color chooser pane with an initial color of white.
*/
public JColorChooser() {
this(Color.white);
}
/** {@collect.stats}
* Creates a color chooser pane with the specified initial color.
*
* @param initialColor the initial color set in the chooser
*/
public JColorChooser(Color initialColor) {
this( new DefaultColorSelectionModel(initialColor) );
}
/** {@collect.stats}
* Creates a color chooser pane with the specified
* <code>ColorSelectionModel</code>.
*
* @param model the <code>ColorSelectionModel</code> to be used
*/
public JColorChooser(ColorSelectionModel model) {
selectionModel = model;
updateUI();
dragEnabled = false;
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return the <code>ColorChooserUI</code> object that renders
* this component
*/
public ColorChooserUI getUI() {
return (ColorChooserUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the <code>ColorChooserUI</code> L&F object
* @see UIDefaults#getUI
*
* @beaninfo
* bound: true
* hidden: true
* description: The UI object that implements the color chooser's LookAndFeel.
*/
public void setUI(ColorChooserUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((ColorChooserUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "ColorChooserUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Gets the current color value from the color chooser.
* By default, this delegates to the model.
*
* @return the current color value of the color chooser
*/
public Color getColor() {
return selectionModel.getSelectedColor();
}
/** {@collect.stats}
* Sets the current color of the color chooser to the specified color.
* The <code>ColorSelectionModel</code> will fire a <code>ChangeEvent</code>
* @param color the color to be set in the color chooser
* @see JComponent#addPropertyChangeListener
*
* @beaninfo
* bound: false
* hidden: false
* description: The current color the chooser is to display.
*/
public void setColor(Color color) {
selectionModel.setSelectedColor(color);
}
/** {@collect.stats}
* Sets the current color of the color chooser to the
* specified RGB color. Note that the values of red, green,
* and blue should be between the numbers 0 and 255, inclusive.
*
* @param r an int specifying the amount of Red
* @param g an int specifying the amount of Green
* @param b an int specifying the amount of Blue
* @exception IllegalArgumentException if r,g,b values are out of range
* @see java.awt.Color
*/
public void setColor(int r, int g, int b) {
setColor(new Color(r,g,b));
}
/** {@collect.stats}
* Sets the current color of the color chooser to the
* specified color.
*
* @param c an integer value that sets the current color in the chooser
* where the low-order 8 bits specify the Blue value,
* the next 8 bits specify the Green value, and the 8 bits
* above that specify the Red value.
*/
public void setColor(int c) {
setColor((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF);
}
/** {@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
* when the user presses the mouse button over the preview panel.
* 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>
*
* @since 1.4
*
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #getDragEnabled
* @see #setTransferHandler
* @see TransferHandler
*
* @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;
}
/** {@collect.stats}
* Sets the current preview panel.
* This will fire a <code>PropertyChangeEvent</code> for the property
* named "previewPanel".
*
* @param preview the <code>JComponent</code> which displays the current color
* @see JComponent#addPropertyChangeListener
*
* @beaninfo
* bound: true
* hidden: true
* description: The UI component which displays the current color.
*/
public void setPreviewPanel(JComponent preview) {
if (previewPanel != preview) {
JComponent oldPreview = previewPanel;
previewPanel = preview;
firePropertyChange(JColorChooser.PREVIEW_PANEL_PROPERTY, oldPreview, preview);
}
}
/** {@collect.stats}
* Returns the preview panel that shows a chosen color.
*
* @return a <code>JComponent</code> object -- the preview panel
*/
public JComponent getPreviewPanel() {
return previewPanel;
}
/** {@collect.stats}
* Adds a color chooser panel to the color chooser.
*
* @param panel the <code>AbstractColorChooserPanel</code> to be added
*/
public void addChooserPanel( AbstractColorChooserPanel panel ) {
AbstractColorChooserPanel[] oldPanels = getChooserPanels();
AbstractColorChooserPanel[] newPanels = new AbstractColorChooserPanel[oldPanels.length+1];
System.arraycopy(oldPanels, 0, newPanels, 0, oldPanels.length);
newPanels[newPanels.length-1] = panel;
setChooserPanels(newPanels);
}
/** {@collect.stats}
* Removes the Color Panel specified.
*
* @param panel a string that specifies the panel to be removed
* @return the color panel
* @exception IllegalArgumentException if panel is not in list of
* known chooser panels
*/
public AbstractColorChooserPanel removeChooserPanel( AbstractColorChooserPanel panel ) {
int containedAt = -1;
for (int i = 0; i < chooserPanels.length; i++) {
if (chooserPanels[i] == panel) {
containedAt = i;
break;
}
}
if (containedAt == -1) {
throw new IllegalArgumentException("chooser panel not in this chooser");
}
AbstractColorChooserPanel[] newArray = new AbstractColorChooserPanel[chooserPanels.length-1];
if (containedAt == chooserPanels.length-1) { // at end
System.arraycopy(chooserPanels, 0, newArray, 0, newArray.length);
}
else if (containedAt == 0) { // at start
System.arraycopy(chooserPanels, 1, newArray, 0, newArray.length);
}
else { // in middle
System.arraycopy(chooserPanels, 0, newArray, 0, containedAt);
System.arraycopy(chooserPanels, containedAt+1,
newArray, containedAt, (chooserPanels.length - containedAt - 1));
}
setChooserPanels(newArray);
return panel;
}
/** {@collect.stats}
* Specifies the Color Panels used to choose a color value.
*
* @param panels an array of <code>AbstractColorChooserPanel</code>
* objects
*
* @beaninfo
* bound: true
* hidden: true
* description: An array of different chooser types.
*/
public void setChooserPanels( AbstractColorChooserPanel[] panels) {
AbstractColorChooserPanel[] oldValue = chooserPanels;
chooserPanels = panels;
firePropertyChange(CHOOSER_PANELS_PROPERTY, oldValue, panels);
}
/** {@collect.stats}
* Returns the specified color panels.
*
* @return an array of <code>AbstractColorChooserPanel</code> objects
*/
public AbstractColorChooserPanel[] getChooserPanels() {
return chooserPanels;
}
/** {@collect.stats}
* Returns the data model that handles color selections.
*
* @return a <code>ColorSelectionModel</code> object
*/
public ColorSelectionModel getSelectionModel() {
return selectionModel;
}
/** {@collect.stats}
* Sets the model containing the selected color.
*
* @param newModel the new <code>ColorSelectionModel</code> object
*
* @beaninfo
* bound: true
* hidden: true
* description: The model which contains the currently selected color.
*/
public void setSelectionModel(ColorSelectionModel newModel ) {
ColorSelectionModel oldModel = selectionModel;
selectionModel = newModel;
firePropertyChange(JColorChooser.SELECTION_MODEL_PROPERTY, oldModel, newModel);
}
/** {@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>JColorChooser</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>JColorChooser</code>
*/
protected String paramString() {
StringBuffer chooserPanelsString = new StringBuffer("");
for (int i=0; i<chooserPanels.length; i++) {
chooserPanelsString.append("[" + chooserPanels[i].toString()
+ "]");
}
String previewPanelString = (previewPanel != null ?
previewPanel.toString() : "");
return super.paramString() +
",chooserPanels=" + chooserPanelsString.toString() +
",previewPanel=" + previewPanelString;
}
/////////////////
// Accessibility support
////////////////
protected AccessibleContext accessibleContext = null;
/** {@collect.stats}
* Gets the AccessibleContext associated with this JColorChooser.
* For color choosers, the AccessibleContext takes the form of an
* AccessibleJColorChooser.
* A new AccessibleJColorChooser instance is created if necessary.
*
* @return an AccessibleJColorChooser that serves as the
* AccessibleContext of this JColorChooser
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJColorChooser();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JColorChooser</code> class. It provides an implementation of the
* Java Accessibility API appropriate to color chooser user-interface
* elements.
*/
protected class AccessibleJColorChooser extends AccessibleJComponent {
/** {@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.COLOR_CHOOSER;
}
} // inner class AccessibleJColorChooser
}
/*
* Class which builds a color chooser dialog consisting of
* a JColorChooser with "Ok", "Cancel", and "Reset" buttons.
*
* Note: This needs to be fixed to deal with localization!
*/
class ColorChooserDialog extends JDialog {
private Color initialColor;
private JColorChooser chooserPane;
private JButton cancelButton;
public ColorChooserDialog(Dialog owner, String title, boolean modal,
Component c, JColorChooser chooserPane,
ActionListener okListener, ActionListener cancelListener)
throws HeadlessException {
super(owner, title, modal);
initColorChooserDialog(c, chooserPane, okListener, cancelListener);
}
public ColorChooserDialog(Frame owner, String title, boolean modal,
Component c, JColorChooser chooserPane,
ActionListener okListener, ActionListener cancelListener)
throws HeadlessException {
super(owner, title, modal);
initColorChooserDialog(c, chooserPane, okListener, cancelListener);
}
protected void initColorChooserDialog(Component c, JColorChooser chooserPane,
ActionListener okListener, ActionListener cancelListener) {
//setResizable(false);
this.chooserPane = chooserPane;
String okString = UIManager.getString("ColorChooser.okText");
String cancelString = UIManager.getString("ColorChooser.cancelText");
String resetString = UIManager.getString("ColorChooser.resetText");
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(chooserPane, BorderLayout.CENTER);
/*
* Create Lower button panel
*/
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton okButton = new JButton(okString);
getRootPane().setDefaultButton(okButton);
okButton.setActionCommand("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hide();
}
});
if (okListener != null) {
okButton.addActionListener(okListener);
}
buttonPane.add(okButton);
cancelButton = new JButton(cancelString);
// The following few lines are used to register esc to close the dialog
Action cancelKeyAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
((AbstractButton)e.getSource()).fireActionPerformed(e);
}
};
KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
InputMap inputMap = cancelButton.getInputMap(JComponent.
WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = cancelButton.getActionMap();
if (inputMap != null && actionMap != null) {
inputMap.put(cancelKeyStroke, "cancel");
actionMap.put("cancel", cancelKeyAction);
}
// end esc handling
cancelButton.setActionCommand("cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hide();
}
});
if (cancelListener != null) {
cancelButton.addActionListener(cancelListener);
}
buttonPane.add(cancelButton);
JButton resetButton = new JButton(resetString);
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset();
}
});
int mnemonic = SwingUtilities2.getUIDefaultsInt("ColorChooser.resetMnemonic", -1);
if (mnemonic != -1) {
resetButton.setMnemonic(mnemonic);
}
buttonPane.add(resetButton);
contentPane.add(buttonPane, BorderLayout.SOUTH);
if (JDialog.isDefaultLookAndFeelDecorated()) {
boolean supportsWindowDecorations =
UIManager.getLookAndFeel().getSupportsWindowDecorations();
if (supportsWindowDecorations) {
getRootPane().setWindowDecorationStyle(JRootPane.COLOR_CHOOSER_DIALOG);
}
}
applyComponentOrientation(((c == null) ? getRootPane() : c).getComponentOrientation());
pack();
setLocationRelativeTo(c);
this.addWindowListener(new Closer());
}
public void show() {
initialColor = chooserPane.getColor();
super.show();
}
public void reset() {
chooserPane.setColor(initialColor);
}
class Closer extends WindowAdapter implements Serializable{
public void windowClosing(WindowEvent e) {
cancelButton.doClick(0);
Window w = e.getWindow();
w.hide();
}
}
static class DisposeOnClose extends ComponentAdapter implements Serializable{
public void componentHidden(ComponentEvent e) {
Window w = (Window)e.getComponent();
w.dispose();
}
}
}
class ColorTracker implements ActionListener, Serializable {
JColorChooser chooser;
Color color;
public ColorTracker(JColorChooser c) {
chooser = c;
}
public void actionPerformed(ActionEvent e) {
color = chooser.getColor();
}
public Color getColor() {
return color;
}
}
|
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.Color;
import java.awt.Graphics;
import java.text.Format;
import java.text.NumberFormat;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.event.*;
import javax.accessibility.*;
import javax.swing.plaf.ProgressBarUI;
/** {@collect.stats}
* A component that visually displays the progress of some task. As the task
* progresses towards completion, the progress bar displays the
* task's percentage of completion.
* This percentage is typically represented visually by a rectangle which
* starts out empty and gradually becomes filled in as the task progresses.
* In addition, the progress bar can display a textual representation of this
* percentage.
* <p>
* {@code JProgressBar} uses a {@code BoundedRangeModel} as its data model,
* with the {@code value} property representing the "current" state of the task,
* and the {@code minimum} and {@code maximum} properties representing the
* beginning and end points, respectively.
* <p>
* To indicate that a task of unknown length is executing,
* you can put a progress bar into indeterminate mode.
* While the bar is in indeterminate mode,
* it animates constantly to show that work is occurring.
* As soon as you can determine the task's length and amount of progress,
* you should update the progress bar's value
* and switch it back to determinate mode.
*
* <p>
*
* Here is an example of creating a progress bar,
* where <code>task</code> is an object (representing some piece of work)
* which returns information about the progress of the task:
*
*<pre>
*progressBar = new JProgressBar(0, task.getLengthOfTask());
*progressBar.setValue(0);
*progressBar.setStringPainted(true);
*</pre>
*
* Here is an example of querying the current state of the task, and using
* the returned value to update the progress bar:
*
*<pre>
*progressBar.setValue(task.getCurrent());
*</pre>
*
* Here is an example of putting a progress bar into
* indeterminate mode,
* and then switching back to determinate mode
* once the length of the task is known:
*
*<pre>
*progressBar = new JProgressBar();
*<em>...//when the task of (initially) unknown length begins:</em>
*progressBar.setIndeterminate(true);
*<em>...//do some work; get length of task...</em>
*progressBar.setMaximum(newLength);
*progressBar.setValue(newValue);
*progressBar.setIndeterminate(false);
*</pre>
*
* <p>
*
* For complete examples and further documentation see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html" target="_top">How to Monitor Progress</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 javax.swing.plaf.basic.BasicProgressBarUI
* @see javax.swing.BoundedRangeModel
* @see javax.swing.SwingWorker
*
* @beaninfo
* attribute: isContainer false
* description: A component that displays an integer value.
*
* @author Michael C. Albers
* @author Kathy Walrath
*/
public class JProgressBar extends JComponent implements SwingConstants, Accessible
{
/** {@collect.stats}
* @see #getUIClassID
*/
private static final String uiClassID = "ProgressBarUI";
/** {@collect.stats}
* Whether the progress bar is horizontal or vertical.
* The default is <code>HORIZONTAL</code>.
*
* @see #setOrientation
*/
protected int orientation;
/** {@collect.stats}
* Whether to display a border around the progress bar.
* The default is <code>true</code>.
*
* @see #setBorderPainted
*/
protected boolean paintBorder;
/** {@collect.stats}
* The object that holds the data for the progress bar.
*
* @see #setModel
*/
protected BoundedRangeModel model;
/** {@collect.stats}
* An optional string that can be displayed on the progress bar.
* The default is <code>null</code>. Setting this to a non-<code>null</code>
* value does not imply that the string will be displayed.
* To display the string, {@code paintString} must be {@code true}.
*
* @see #setString
* @see #setStringPainted
*/
protected String progressString;
/** {@collect.stats}
* Whether to display a string of text on the progress bar.
* The default is <code>false</code>.
* Setting this to <code>true</code> causes a textual
* display of the progress to be rendered on the progress bar. If
* the <code>progressString</code> is <code>null</code>,
* the percentage of completion is displayed on the progress bar.
* Otherwise, the <code>progressString</code> is
* rendered on the progress bar.
*
* @see #setStringPainted
* @see #setString
*/
protected boolean paintString;
/** {@collect.stats}
* The default minimum for a progress bar is 0.
*/
static final private int defaultMinimum = 0;
/** {@collect.stats}
* The default maximum for a progress bar is 100.
*/
static final private int defaultMaximum = 100;
/** {@collect.stats}
* The default orientation for a progress bar is <code>HORIZONTAL</code>.
*/
static final private int defaultOrientation = HORIZONTAL;
/** {@collect.stats}
* Only one <code>ChangeEvent</code> is needed per instance since the
* event's only interesting property is the immutable source, which
* is the progress bar.
* The event is lazily created the first time that an
* event notification is fired.
*
* @see #fireStateChanged
*/
protected transient ChangeEvent changeEvent = null;
/** {@collect.stats}
* Listens for change events sent by the progress bar's model,
* redispatching them
* to change-event listeners registered upon
* this progress bar.
*
* @see #createChangeListener
*/
protected ChangeListener changeListener = null;
/** {@collect.stats}
* Format used when displaying percent complete.
*/
private transient Format format;
/** {@collect.stats}
* Whether the progress bar is indeterminate (<code>true</code>) or
* normal (<code>false</code>); the default is <code>false</code>.
*
* @see #setIndeterminate
* @since 1.4
*/
private boolean indeterminate;
/** {@collect.stats}
* Creates a horizontal progress bar
* that displays a border but no progress string.
* The initial and minimum values are 0,
* and the maximum is 100.
*
* @see #setOrientation
* @see #setBorderPainted
* @see #setStringPainted
* @see #setString
* @see #setIndeterminate
*/
public JProgressBar()
{
this(defaultOrientation);
}
/** {@collect.stats}
* Creates a progress bar with the specified orientation,
* which can be
* either {@code SwingConstants.VERTICAL} or
* {@code SwingConstants.HORIZONTAL}.
* By default, a border is painted but a progress string is not.
* The initial and minimum values are 0,
* and the maximum is 100.
*
* @param orient the desired orientation of the progress bar
* @throws IllegalArgumentException if {@code orient} is an illegal value
*
* @see #setOrientation
* @see #setBorderPainted
* @see #setStringPainted
* @see #setString
* @see #setIndeterminate
*/
public JProgressBar(int orient)
{
this(orient, defaultMinimum, defaultMaximum);
}
/** {@collect.stats}
* Creates a horizontal progress bar
* with the specified minimum and maximum.
* Sets the initial value of the progress bar to the specified minimum.
* By default, a border is painted but a progress string is not.
* <p>
* The <code>BoundedRangeModel</code> that holds the progress bar's data
* handles any issues that may arise from improperly setting the
* minimum, initial, and maximum values on the progress bar.
* See the {@code BoundedRangeModel} documentation for details.
*
* @param min the minimum value of the progress bar
* @param max the maximum value of the progress bar
*
* @see BoundedRangeModel
* @see #setOrientation
* @see #setBorderPainted
* @see #setStringPainted
* @see #setString
* @see #setIndeterminate
*/
public JProgressBar(int min, int max)
{
this(defaultOrientation, min, max);
}
/** {@collect.stats}
* Creates a progress bar using the specified orientation,
* minimum, and maximum.
* By default, a border is painted but a progress string is not.
* Sets the initial value of the progress bar to the specified minimum.
* <p>
* The <code>BoundedRangeModel</code> that holds the progress bar's data
* handles any issues that may arise from improperly setting the
* minimum, initial, and maximum values on the progress bar.
* See the {@code BoundedRangeModel} documentation for details.
*
* @param orient the desired orientation of the progress bar
* @param min the minimum value of the progress bar
* @param max the maximum value of the progress bar
* @throws IllegalArgumentException if {@code orient} is an illegal value
*
* @see BoundedRangeModel
* @see #setOrientation
* @see #setBorderPainted
* @see #setStringPainted
* @see #setString
* @see #setIndeterminate
*/
public JProgressBar(int orient, int min, int max)
{
// Creating the model this way is a bit simplistic, but
// I believe that it is the the most common usage of this
// component - it's what people will expect.
setModel(new DefaultBoundedRangeModel(min, 0, min, max));
updateUI();
setOrientation(orient); // documented with set/getOrientation()
setBorderPainted(true); // documented with is/setBorderPainted()
setStringPainted(false); // see setStringPainted
setString(null); // see getString
setIndeterminate(false); // see setIndeterminate
}
/** {@collect.stats}
* Creates a horizontal progress bar
* that uses the specified model
* to hold the progress bar's data.
* By default, a border is painted but a progress string is not.
*
* @param newModel the data model for the progress bar
*
* @see #setOrientation
* @see #setBorderPainted
* @see #setStringPainted
* @see #setString
* @see #setIndeterminate
*/
public JProgressBar(BoundedRangeModel newModel)
{
setModel(newModel);
updateUI();
setOrientation(defaultOrientation); // see setOrientation()
setBorderPainted(true); // see setBorderPainted()
setStringPainted(false); // see setStringPainted
setString(null); // see getString
setIndeterminate(false); // see setIndeterminate
}
/** {@collect.stats}
* Returns {@code SwingConstants.VERTICAL} or
* {@code SwingConstants.HORIZONTAL}, depending on the orientation
* of the progress bar. The default orientation is
* {@code SwingConstants.HORIZONTAL}.
*
* @return <code>HORIZONTAL</code> or <code>VERTICAL</code>
* @see #setOrientation
*/
public int getOrientation() {
return orientation;
}
/** {@collect.stats}
* Sets the progress bar's orientation to <code>newOrientation</code>,
* which must be {@code SwingConstants.VERTICAL} or
* {@code SwingConstants.HORIZONTAL}. The default orientation
* is {@code SwingConstants.HORIZONTAL}.
*
* @param newOrientation <code>HORIZONTAL</code> or <code>VERTICAL</code>
* @exception IllegalArgumentException if <code>newOrientation</code>
* is an illegal value
* @see #getOrientation
*
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: Set the progress bar's orientation.
*/
public void setOrientation(int newOrientation) {
if (orientation != newOrientation) {
switch (newOrientation) {
case VERTICAL:
case HORIZONTAL:
int oldOrientation = orientation;
orientation = newOrientation;
firePropertyChange("orientation", oldOrientation, newOrientation);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
((oldOrientation == VERTICAL)
? AccessibleState.VERTICAL
: AccessibleState.HORIZONTAL),
((orientation == VERTICAL)
? AccessibleState.VERTICAL
: AccessibleState.HORIZONTAL));
}
break;
default:
throw new IllegalArgumentException(newOrientation +
" is not a legal orientation");
}
revalidate();
}
}
/** {@collect.stats}
* Returns the value of the <code>stringPainted</code> property.
*
* @return the value of the <code>stringPainted</code> property
* @see #setStringPainted
* @see #setString
*/
public boolean isStringPainted() {
return paintString;
}
/** {@collect.stats}
* Sets the value of the <code>stringPainted</code> property,
* which determines whether the progress bar
* should render a progress string.
* The default is <code>false</code>, meaning
* no string is painted.
* Some look and feels might not support progress strings
* or might support them only when the progress bar is in determinate mode.
*
* @param b <code>true</code> if the progress bar should render a string
* @see #isStringPainted
* @see #setString
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether the progress bar should render a string.
*/
public void setStringPainted(boolean b) {
//PENDING: specify that string not painted when in indeterminate mode?
// or just leave that to the L&F?
boolean oldValue = paintString;
paintString = b;
firePropertyChange("stringPainted", oldValue, paintString);
if (paintString != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns a {@code String} representation of the current progress.
* By default, this returns a simple percentage {@code String} based on
* the value returned from {@code getPercentComplete}. An example
* would be the "42%". You can change this by calling {@code setString}.
*
* @return the value of the progress string, or a simple percentage string
* if the progress string is {@code null}
* @see #setString
*/
public String getString(){
if (progressString != null) {
return progressString;
} else {
if (format == null) {
format = NumberFormat.getPercentInstance();
}
return format.format(new Double(getPercentComplete()));
}
}
/** {@collect.stats}
* Sets the value of the progress string. By default,
* this string is <code>null</code>, implying the built-in behavior of
* using a simple percent string.
* If you have provided a custom progress string and want to revert to
* the built-in behavior, set the string back to <code>null</code>.
* <p>
* The progress string is painted only if
* the <code>isStringPainted</code> method returns <code>true</code>.
*
* @param s the value of the progress string
* @see #getString
* @see #setStringPainted
* @see #isStringPainted
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Specifies the progress string to paint
*/
public void setString(String s){
String oldValue = progressString;
progressString = s;
firePropertyChange("string", oldValue, progressString);
if (progressString == null || oldValue == null || !progressString.equals(oldValue)) {
repaint();
}
}
/** {@collect.stats}
* Returns the percent complete for the progress bar.
* Note that this number is between 0.0 and 1.0.
*
* @return the percent complete for this progress bar
*/
public double getPercentComplete() {
long span = model.getMaximum() - model.getMinimum();
double currentValue = model.getValue();
double pc = (currentValue - model.getMinimum()) / span;
return pc;
}
/** {@collect.stats}
* Returns the <code>borderPainted</code> property.
*
* @return the value of the <code>borderPainted</code> property
* @see #setBorderPainted
* @beaninfo
* description: Does the progress bar paint its border
*/
public boolean isBorderPainted() {
return paintBorder;
}
/** {@collect.stats}
* Sets the <code>borderPainted</code> property, which is
* <code>true</code> if the progress bar should paint its border.
* The default value for this property is <code>true</code>.
* Some look and feels might not implement painted borders;
* they will ignore this property.
*
* @param b <code>true</code> if the progress bar
* should paint its border;
* otherwise, <code>false</code>
* @see #isBorderPainted
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether the progress bar should paint its border.
*/
public void setBorderPainted(boolean b) {
boolean oldValue = paintBorder;
paintBorder = b;
firePropertyChange("borderPainted", oldValue, paintBorder);
if (paintBorder != oldValue) {
repaint();
}
}
/** {@collect.stats}
* Paints the progress bar's border if the <code>borderPainted</code>
* property is <code>true</code>.
*
* @param g the <code>Graphics</code> context within which to paint the border
* @see #paint
* @see #setBorder
* @see #isBorderPainted
* @see #setBorderPainted
*/
protected void paintBorder(Graphics g) {
if (isBorderPainted()) {
super.paintBorder(g);
}
}
/** {@collect.stats}
* Returns the look-and-feel object that renders this component.
*
* @return the <code>ProgressBarUI</code> object that renders this component
*/
public ProgressBarUI getUI() {
return (ProgressBarUI)ui;
}
/** {@collect.stats}
* Sets the look-and-feel object that renders this component.
*
* @param ui a <code>ProgressBarUI</code> 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(ProgressBarUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((ProgressBarUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the look-and-feel class that renders this component.
*
* @return the string "ProgressBarUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
* @beaninfo
* expert: true
* description: A string that specifies the name of the look-and-feel class.
*/
public String getUIClassID() {
return uiClassID;
}
/* We pass each Change event to the listeners with the
* the progress bar as 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}.
*/
private class ModelListener implements ChangeListener, Serializable {
public void stateChanged(ChangeEvent e) {
fireStateChanged();
}
}
/** {@collect.stats}
* Subclasses that want to handle change events
* from the model differently
* can override this to return
* an instance of a custom <code>ChangeListener</code> implementation.
* The default {@code ChangeListener} simply calls the
* {@code fireStateChanged} method to forward {@code ChangeEvent}s
* to the {@code ChangeListener}s that have been added directly to the
* progress bar.
*
* @see #changeListener
* @see #fireStateChanged
* @see javax.swing.event.ChangeListener
* @see javax.swing.BoundedRangeModel
*/
protected ChangeListener createChangeListener() {
return new ModelListener();
}
/** {@collect.stats}
* Adds the specified <code>ChangeListener</code> to the progress bar.
*
* @param l the <code>ChangeListener</code> to add
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a <code>ChangeListener</code> from the progress bar.
*
* @param l the <code>ChangeListener</code> to remove
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this progress bar with <code>addChangeListener</code>.
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Send a {@code ChangeEvent}, whose source is this {@code JProgressBar}, to
* all {@code ChangeListener}s that have registered interest in
* {@code ChangeEvent}s.
* This method is called each time a {@code ChangeEvent} is received from
* the model.
* <p>
*
* The event instance is created if necessary, and stored in
* {@code changeEvent}.
*
* @see #addChangeListener
* @see EventListenerList
*/
protected void fireStateChanged() {
// 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]==ChangeListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/** {@collect.stats}
* Returns the data model used by this progress bar.
*
* @return the <code>BoundedRangeModel</code> currently in use
* @see #setModel
* @see BoundedRangeModel
*/
public BoundedRangeModel getModel() {
return model;
}
/** {@collect.stats}
* Sets the data model used by the <code>JProgressBar</code>.
* Note that the {@code BoundedRangeModel}'s {@code extent} is not used,
* and is set to {@code 0}.
*
* @param newModel the <code>BoundedRangeModel</code> to use
*
* @beaninfo
* expert: true
* description: The data model used by the JProgressBar.
*/
public void setModel(BoundedRangeModel newModel) {
// PENDING(???) setting the same model to multiple bars is broken; listeners
BoundedRangeModel oldModel = getModel();
if (newModel != oldModel) {
if (oldModel != null) {
oldModel.removeChangeListener(changeListener);
changeListener = null;
}
model = newModel;
if (newModel != null) {
changeListener = createChangeListener();
newModel.addChangeListener(changeListener);
}
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
(oldModel== null
? null : new Integer(oldModel.getValue())),
(newModel== null
? null : new Integer(newModel.getValue())));
}
if (model != null) {
model.setExtent(0);
}
repaint();
}
}
/* All of the model methods are implemented by delegation. */
/** {@collect.stats}
* Returns the progress bar's current {@code value}
* from the <code>BoundedRangeModel</code>.
* The value is always between the
* minimum and maximum values, inclusive.
*
* @return the current value of the progress bar
* @see #setValue
* @see BoundedRangeModel#getValue
*/
public int getValue() { return getModel().getValue(); }
/** {@collect.stats}
* Returns the progress bar's {@code minimum} value
* from the <code>BoundedRangeModel</code>.
*
* @return the progress bar's minimum value
* @see #setMinimum
* @see BoundedRangeModel#getMinimum
*/
public int getMinimum() { return getModel().getMinimum(); }
/** {@collect.stats}
* Returns the progress bar's {@code maximum} value
* from the <code>BoundedRangeModel</code>.
*
* @return the progress bar's maximum value
* @see #setMaximum
* @see BoundedRangeModel#getMaximum
*/
public int getMaximum() { return getModel().getMaximum(); }
/** {@collect.stats}
* Sets the progress bar's current value to {@code n}. This method
* forwards the new value to the model.
* <p>
* The data model (an instance of {@code BoundedRangeModel})
* handles any mathematical
* issues arising from assigning faulty values. See the
* {@code BoundedRangeModel} documentation for details.
* <p>
* If the new value is different from the previous value,
* all change listeners are notified.
*
* @param n the new value
* @see #getValue
* @see #addChangeListener
* @see BoundedRangeModel#setValue
* @beaninfo
* preferred: true
* description: The progress bar's current value.
*/
public void setValue(int n) {
BoundedRangeModel brm = getModel();
int oldValue = brm.getValue();
brm.setValue(n);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
new Integer(oldValue),
new Integer(brm.getValue()));
}
}
/** {@collect.stats}
* Sets the progress bar's minimum value
* (stored in the progress bar's data model) to <code>n</code>.
* <p>
* The data model (a <code>BoundedRangeModel</code> instance)
* handles any mathematical
* issues arising from assigning faulty values.
* See the {@code BoundedRangeModel} documentation for details.
* <p>
* If the minimum value is different from the previous minimum,
* all change listeners are notified.
*
* @param n the new minimum
* @see #getMinimum
* @see #addChangeListener
* @see BoundedRangeModel#setMinimum
* @beaninfo
* preferred: true
* description: The progress bar's minimum value.
*/
public void setMinimum(int n) { getModel().setMinimum(n); }
/** {@collect.stats}
* Sets the progress bar's maximum value
* (stored in the progress bar's data model) to <code>n</code>.
* <p>
* The underlying <code>BoundedRangeModel</code> handles any mathematical
* issues arising from assigning faulty values.
* See the {@code BoundedRangeModel} documentation for details.
* <p>
* If the maximum value is different from the previous maximum,
* all change listeners are notified.
*
* @param n the new maximum
* @see #getMaximum
* @see #addChangeListener
* @see BoundedRangeModel#setMaximum
* @beaninfo
* preferred: true
* description: The progress bar's maximum value.
*/
public void setMaximum(int n) { getModel().setMaximum(n); }
/** {@collect.stats}
* Sets the <code>indeterminate</code> property of the progress bar,
* which determines whether the progress bar is in determinate
* or indeterminate mode.
* An indeterminate progress bar continuously displays animation
* indicating that an operation of unknown length is occurring.
* By default, this property is <code>false</code>.
* Some look and feels might not support indeterminate progress bars;
* they will ignore this property.
*
* <p>
*
* See
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html" target="_top">How to Monitor Progress</a>
* for examples of using indeterminate progress bars.
*
* @param newValue <code>true</code> if the progress bar
* should change to indeterminate mode;
* <code>false</code> if it should revert to normal.
*
* @see #isIndeterminate
* @see javax.swing.plaf.basic.BasicProgressBarUI
*
* @since 1.4
*
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Set whether the progress bar is indeterminate (true)
* or normal (false).
*/
public void setIndeterminate(boolean newValue) {
boolean oldValue = indeterminate;
indeterminate = newValue;
firePropertyChange("indeterminate", oldValue, indeterminate);
}
/** {@collect.stats}
* Returns the value of the <code>indeterminate</code> property.
*
* @return the value of the <code>indeterminate</code> property
* @see #setIndeterminate
*
* @since 1.4
*
* @beaninfo
* description: Is the progress bar indeterminate (true)
* or normal (false)?
*/
public boolean isIndeterminate() {
return indeterminate;
}
/** {@collect.stats}
* 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}
* Returns a string representation of this <code>JProgressBar</code>.
* This method is intended to be used only for debugging purposes. 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>JProgressBar</code>
*/
protected String paramString() {
String orientationString = (orientation == HORIZONTAL ?
"HORIZONTAL" : "VERTICAL");
String paintBorderString = (paintBorder ?
"true" : "false");
String progressStringString = (progressString != null ?
progressString : "");
String paintStringString = (paintString ?
"true" : "false");
String indeterminateString = (indeterminate ?
"true" : "false");
return super.paramString() +
",orientation=" + orientationString +
",paintBorder=" + paintBorderString +
",paintString=" + paintStringString +
",progressString=" + progressStringString +
",indeterminateString=" + indeterminateString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with this
* <code>JProgressBar</code>. For progress bars, the
* <code>AccessibleContext</code> takes the form of an
* <code>AccessibleJProgressBar</code>.
* A new <code>AccessibleJProgressBar</code> instance is created if necessary.
*
* @return an <code>AccessibleJProgressBar</code> that serves as the
* <code>AccessibleContext</code> of this <code>JProgressBar</code>
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this ProgressBar.
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJProgressBar();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JProgressBar</code> class. It provides an implementation of the
* Java Accessibility API appropriate to progress 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 AccessibleJProgressBar extends AccessibleJComponent
implements AccessibleValue {
/** {@collect.stats}
* Gets the state set of this object.
*
* @return an instance of AccessibleState containing the current state
* of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (getModel().getValueIsAdjusting()) {
states.add(AccessibleState.BUSY);
}
if (getOrientation() == VERTICAL) {
states.add(AccessibleState.VERTICAL);
} else {
states.add(AccessibleState.HORIZONTAL);
}
return states;
}
/** {@collect.stats}
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PROGRESS_BAR;
}
/** {@collect.stats}
* Gets the <code>AccessibleValue</code> associated with this object. In the
* implementation of the Java Accessibility API for this class,
* returns this object, which is responsible for implementing the
* <code>AccessibleValue</code> interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
/** {@collect.stats}
* Gets the accessible value of this object.
*
* @return the current value of this object
*/
public Number getCurrentAccessibleValue() {
return new Integer(getValue());
}
/** {@collect.stats}
* Sets the value of this object as a <code>Number</code>.
*
* @return <code>true</code> if the value was set
*/
public boolean setCurrentAccessibleValue(Number n) {
// TIGER- 4422535
if (n == null) {
return false;
}
setValue(n.intValue());
return true;
}
/** {@collect.stats}
* Gets the minimum accessible value of this object.
*
* @return the minimum value of this object
*/
public Number getMinimumAccessibleValue() {
return new Integer(getMinimum());
}
/** {@collect.stats}
* Gets the maximum accessible value of this object.
*
* @return the maximum value of this object
*/
public Number getMaximumAccessibleValue() {
// TIGER - 4422362
return new Integer(model.getMaximum() - model.getExtent());
}
} // AccessibleJProgressBar
}
|
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.AWTEvent;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import javax.accessibility.*;
import java.lang.ref.WeakReference;
/** {@collect.stats}
* An implementation of a menu -- a popup window containing
* <code>JMenuItem</code>s that
* is displayed when the user selects an item on the <code>JMenuBar</code>.
* In addition to <code>JMenuItem</code>s, a <code>JMenu</code> can
* also contain <code>JSeparator</code>s.
* <p>
* In essence, a menu is a button with an associated <code>JPopupMenu</code>.
* When the "button" is pressed, the <code>JPopupMenu</code> appears. If the
* "button" is on the <code>JMenuBar</code>, the menu is a top-level window.
* If the "button" is another menu item, then the <code>JPopupMenu</code> is
* "pull-right" menu.
* <p>
* Menus 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 menu has many benefits beyond directly
* configuring a menu. 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>
* For information and examples of using menus see
* <a href="http://java.sun.com/doc/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 popup window containing menu items displayed in a menu bar.
*
* @author Georges Saab
* @author David Karlton
* @author Arnaud Weber
* @see JMenuItem
* @see JSeparator
* @see JMenuBar
* @see JPopupMenu
*/
public class JMenu extends JMenuItem implements Accessible,MenuElement
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "MenuUI";
/*
* The popup menu portion of the menu.
*/
private JPopupMenu popupMenu;
/*
* The button's model listeners. Default is <code>null</code>.
*/
private ChangeListener menuChangeListener = null;
/*
* Only one <code>MenuEvent</code> is needed for each menu since the
* event's only state is the source property. The source of events
* generated is always "this". Default is <code>null</code>.
*/
private MenuEvent menuEvent = null;
/* Registry of listeners created for <code>Action-JMenuItem</code>
* linkage. This is needed so that references can
* be cleaned up at remove time to allow garbage collection
* Default is <code>null</code>.
*/
private static Hashtable listenerRegistry = null;
/*
* Used by the look and feel (L&F) code to handle
* implementation specific menu behaviors.
*/
private int delay;
/*
* Location of the popup component. Location is <code>null</code>
* if it was not customized by <code>setMenuLocation</code>
*/
private Point customMenuLocation = 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}
* Constructs a new <code>JMenu</code> with no text.
*/
public JMenu() {
this("");
}
/** {@collect.stats}
* Constructs a new <code>JMenu</code> with the supplied string
* as its text.
*
* @param s the text for the menu label
*/
public JMenu(String s) {
super(s);
}
/** {@collect.stats}
* Constructs a menu whose properties are taken from the
* <code>Action</code> supplied.
* @param a an <code>Action</code>
*
* @since 1.3
*/
public JMenu(Action a) {
this();
setAction(a);
}
/** {@collect.stats}
* Constructs a new <code>JMenu</code> with the supplied string as
* its text and specified as a tear-off menu or not.
*
* @param s the text for the menu label
* @param b can the menu be torn off (not yet implemented)
*/
public JMenu(String s, boolean b) {
this(s);
}
/** {@collect.stats}
* Overriden to do nothing. We want JMenu to be focusable, but
* <code>JMenuItem</code> doesn't want to be, thus we override this
* do nothing. We don't invoke <code>setFocusable(true)</code> after
* super's constructor has completed as this has the side effect that
* <code>JMenu</code> will be considered traversable via the
* keyboard, which we don't want. Making a Component traversable by
* the keyboard after invoking <code>setFocusable(true)</code> is OK,
* as <code>setFocusable</code> is new API
* and is speced as such, but internally we don't want to use it like
* this else we change the keyboard traversability.
*/
void initFocusability() {
}
/** {@collect.stats}
* Resets the UI property with a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((MenuItemUI)UIManager.getUI(this));
if ( popupMenu != null )
{
popupMenu.setUI((PopupMenuUI)UIManager.getUI(popupMenu));
}
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "MenuUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
// public void repaint(long tm, int x, int y, int width, int height) {
// Thread.currentThread().dumpStack();
// super.repaint(tm,x,y,width,height);
// }
/** {@collect.stats}
* Sets the data model for the "menu button" -- the label
* that the user clicks to open or close the menu.
*
* @param newModel the <code>ButtonModel</code>
* @see #getModel
* @beaninfo
* description: The menu's model
* bound: true
* expert: true
* hidden: true
*/
public void setModel(ButtonModel newModel) {
ButtonModel oldModel = getModel();
super.setModel(newModel);
if (oldModel != null && menuChangeListener != null) {
oldModel.removeChangeListener(menuChangeListener);
menuChangeListener = null;
}
model = newModel;
if (newModel != null) {
menuChangeListener = createMenuChangeListener();
newModel.addChangeListener(menuChangeListener);
}
}
/** {@collect.stats}
* Returns true if the menu is currently selected (highlighted).
*
* @return true if the menu is selected, else false
*/
public boolean isSelected() {
return getModel().isSelected();
}
/** {@collect.stats}
* Sets the selection status of the menu.
*
* @param b true to select (highlight) the menu; false to de-select
* the menu
* @beaninfo
* description: When the menu is selected, its popup child is shown.
* expert: true
* hidden: true
*/
public void setSelected(boolean b) {
ButtonModel model = getModel();
boolean oldValue = model.isSelected();
// TIGER - 4840653
// Removed code which fired an AccessibleState.SELECTED
// PropertyChangeEvent since this resulted in two
// identical events being fired since
// AbstractButton.fireItemStateChanged also fires the
// same event. This caused screen readers to speak the
// name of the item twice.
if (b != model.isSelected()) {
getModel().setSelected(b);
}
}
/** {@collect.stats}
* Returns true if the menu's popup window is visible.
*
* @return true if the menu is visible, else false
*/
public boolean isPopupMenuVisible() {
ensurePopupMenuCreated();
return popupMenu.isVisible();
}
/** {@collect.stats}
* Sets the visibility of the menu's popup. If the menu is
* not enabled, this method will have no effect.
*
* @param b a boolean value -- true to make the menu visible,
* false to hide it
* @beaninfo
* description: The popup menu's visibility
* expert: true
* hidden: true
*/
public void setPopupMenuVisible(boolean b) {
if (DEBUG) {
System.out.println("in JMenu.setPopupMenuVisible " + b);
// Thread.dumpStack();
}
boolean isVisible = isPopupMenuVisible();
if (b != isVisible && (isEnabled() || !b)) {
ensurePopupMenuCreated();
if ((b==true) && isShowing()) {
// Set location of popupMenu (pulldown or pullright)
Point p = getCustomMenuLocation();
if (p == null) {
p = getPopupMenuOrigin();
}
getPopupMenu().show(this, p.x, p.y);
} else {
getPopupMenu().setVisible(false);
}
}
}
/** {@collect.stats}
* Computes the origin for the <code>JMenu</code>'s popup menu.
* This method uses Look and Feel properties named
* <code>Menu.menuPopupOffsetX</code>,
* <code>Menu.menuPopupOffsetY</code>,
* <code>Menu.submenuPopupOffsetX</code>, and
* <code>Menu.submenuPopupOffsetY</code>
* to adjust the exact location of popup.
*
* @return a <code>Point</code> in the coordinate space of the
* menu which should be used as the origin
* of the <code>JMenu</code>'s popup menu
*
* @since 1.3
*/
protected Point getPopupMenuOrigin() {
int x = 0;
int y = 0;
JPopupMenu pm = getPopupMenu();
// Figure out the sizes needed to caclulate the menu position
Dimension s = getSize();
Dimension pmSize = pm.getSize();
// For the first time the menu is popped up,
// the size has not yet been initiated
if (pmSize.width==0) {
pmSize = pm.getPreferredSize();
}
Point position = getLocationOnScreen();
Toolkit toolkit = Toolkit.getDefaultToolkit();
GraphicsConfiguration gc = getGraphicsConfiguration();
Rectangle screenBounds = new Rectangle(toolkit.getScreenSize());
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
for(int i = 0; i < gd.length; i++) {
if(gd[i].getType() == GraphicsDevice.TYPE_RASTER_SCREEN) {
GraphicsConfiguration dgc =
gd[i].getDefaultConfiguration();
if(dgc.getBounds().contains(position)) {
gc = dgc;
break;
}
}
}
if (gc != null) {
screenBounds = gc.getBounds();
// take screen insets (e.g. taskbar) into account
Insets screenInsets = toolkit.getScreenInsets(gc);
screenBounds.width -=
Math.abs(screenInsets.left + screenInsets.right);
screenBounds.height -=
Math.abs(screenInsets.top + screenInsets.bottom);
position.x -= Math.abs(screenInsets.left);
position.y -= Math.abs(screenInsets.top);
}
Container parent = getParent();
if (parent instanceof JPopupMenu) {
// We are a submenu (pull-right)
int xOffset = UIManager.getInt("Menu.submenuPopupOffsetX");
int yOffset = UIManager.getInt("Menu.submenuPopupOffsetY");
if( SwingUtilities.isLeftToRight(this) ) {
// First determine x:
x = s.width + xOffset; // Prefer placement to the right
if (position.x + x + pmSize.width >= screenBounds.width
+ screenBounds.x &&
// popup doesn't fit - place it wherever there's more room
screenBounds.width - s.width < 2*(position.x
- screenBounds.x)) {
x = 0 - xOffset - pmSize.width;
}
} else {
// First determine x:
x = 0 - xOffset - pmSize.width; // Prefer placement to the left
if (position.x + x < screenBounds.x &&
// popup doesn't fit - place it wherever there's more room
screenBounds.width - s.width > 2*(position.x -
screenBounds.x)) {
x = s.width + xOffset;
}
}
// Then the y:
y = yOffset; // Prefer dropping down
if (position.y + y + pmSize.height >= screenBounds.height
+ screenBounds.y &&
// popup doesn't fit - place it wherever there's more room
screenBounds.height - s.height < 2*(position.y
- screenBounds.y)) {
y = s.height - yOffset - pmSize.height;
}
} else {
// We are a toplevel menu (pull-down)
int xOffset = UIManager.getInt("Menu.menuPopupOffsetX");
int yOffset = UIManager.getInt("Menu.menuPopupOffsetY");
if( SwingUtilities.isLeftToRight(this) ) {
// First determine the x:
x = xOffset; // Extend to the right
if (position.x + x + pmSize.width >= screenBounds.width
+ screenBounds.x &&
// popup doesn't fit - place it wherever there's more room
screenBounds.width - s.width < 2*(position.x
- screenBounds.x)) {
x = s.width - xOffset - pmSize.width;
}
} else {
// First determine the x:
x = s.width - xOffset - pmSize.width; // Extend to the left
if (position.x + x < screenBounds.x &&
// popup doesn't fit - place it wherever there's more room
screenBounds.width - s.width > 2*(position.x
- screenBounds.x)) {
x = xOffset;
}
}
// Then the y:
y = s.height + yOffset; // Prefer dropping down
if (position.y + y + pmSize.height >= screenBounds.height &&
// popup doesn't fit - place it wherever there's more room
screenBounds.height - s.height < 2*(position.y
- screenBounds.y)) {
y = 0 - yOffset - pmSize.height; // Otherwise drop 'up'
}
}
return new Point(x,y);
}
/** {@collect.stats}
* Returns the suggested delay, in milliseconds, before submenus
* are popped up or down.
* Each look and feel (L&F) may determine its own policy for
* observing the <code>delay</code> property.
* In most cases, the delay is not observed for top level menus
* or while dragging. The default for <code>delay</code> is 0.
* This method is a property of the look and feel code and is used
* to manage the idiosyncracies of the various UI implementations.
*
*
* @return the <code>delay</code> property
*/
public int getDelay() {
return delay;
}
/** {@collect.stats}
* Sets the suggested delay before the menu's <code>PopupMenu</code>
* is popped up or down. Each look and feel (L&F) may determine
* it's own policy for observing the delay property. In most cases,
* the delay is not observed for top level menus or while dragging.
* This method is a property of the look and feel code and is used
* to manage the idiosyncracies of the various UI implementations.
*
* @param d the number of milliseconds to delay
* @exception IllegalArgumentException if <code>d</code>
* is less than 0
* @beaninfo
* description: The delay between menu selection and making the popup menu visible
* expert: true
*/
public void setDelay(int d) {
if (d < 0)
throw new IllegalArgumentException("Delay must be a positive integer");
delay = d;
}
/** {@collect.stats}
* The window-closing listener for the popup.
*
* @see WinListener
*/
protected WinListener popupListener;
private void ensurePopupMenuCreated() {
if (popupMenu == null) {
final JMenu thisMenu = this;
this.popupMenu = new JPopupMenu();
popupMenu.setInvoker(this);
popupListener = createWinListener(popupMenu);
}
}
/*
* Return the customized location of the popup component.
*/
private Point getCustomMenuLocation() {
return customMenuLocation;
}
/** {@collect.stats}
* Sets the location of the popup component.
*
* @param x the x coordinate of the popup's new position
* @param y the y coordinate of the popup's new position
*/
public void setMenuLocation(int x, int y) {
customMenuLocation = new Point(x, y);
if (popupMenu != null)
popupMenu.setLocation(x, y);
}
/** {@collect.stats}
* Appends a menu item to the end of this menu.
* Returns the menu item added.
*
* @param menuItem the <code>JMenuitem</code> to be added
* @return the <code>JMenuItem</code> added
*/
public JMenuItem add(JMenuItem menuItem) {
ensurePopupMenuCreated();
return popupMenu.add(menuItem);
}
/** {@collect.stats}
* Appends a component to the end of this menu.
* Returns the component added.
*
* @param c the <code>Component</code> to add
* @return the <code>Component</code> added
*/
public Component add(Component c) {
ensurePopupMenuCreated();
popupMenu.add(c);
return c;
}
/** {@collect.stats}
* Adds the specified component to this container at the given
* position. If <code>index</code> equals -1, the component will
* be appended to the end.
* @param c the <code>Component</code> to add
* @param index the position at which to insert the component
* @return the <code>Component</code> added
* @see #remove
* @see java.awt.Container#add(Component, int)
*/
public Component add(Component c, int index) {
ensurePopupMenuCreated();
popupMenu.add(c, index);
return c;
}
/** {@collect.stats}
* Creates a new menu item with the specified text and appends
* it to the end of this menu.
*
* @param s the string for the menu item to be added
*/
public JMenuItem add(String s) {
return add(new JMenuItem(s));
}
/** {@collect.stats}
* Creates a new menu item attached to the specified
* <code>Action</code> object and appends it to the end of this menu.
*
* @param a the <code>Action</code> for the menu item to be added
* @see Action
*/
public JMenuItem add(Action a) {
JMenuItem mi = createActionComponent(a);
mi.setAction(a);
add(mi);
return mi;
}
/** {@collect.stats}
* Factory method which creates the <code>JMenuItem</code> for
* <code>Action</code>s added to the <code>JMenu</code>.
*
* @param a the <code>Action</code> for the menu item to be added
* @return the new menu item
* @see Action
*
* @since 1.3
*/
protected JMenuItem createActionComponent(Action a) {
JMenuItem mi = new JMenuItem() {
protected PropertyChangeListener createActionPropertyChangeListener(Action a) {
PropertyChangeListener pcl = createActionChangeListener(this);
if (pcl == null) {
pcl = super.createActionPropertyChangeListener(a);
}
return pcl;
}
};
mi.setHorizontalTextPosition(JButton.TRAILING);
mi.setVerticalTextPosition(JButton.CENTER);
return mi;
}
/** {@collect.stats}
* Returns a properly configured <code>PropertyChangeListener</code>
* which updates the control as changes to the <code>Action</code> occur.
*/
protected PropertyChangeListener createActionChangeListener(JMenuItem b) {
return b.createActionPropertyChangeListener0(b.getAction());
}
/** {@collect.stats}
* Appends a new separator to the end of the menu.
*/
public void addSeparator()
{
ensurePopupMenuCreated();
popupMenu.addSeparator();
}
/** {@collect.stats}
* Inserts a new menu item with the specified text at a
* given position.
*
* @param s the text for the menu item to add
* @param pos an integer specifying the position at which to add the
* new menu item
* @exception IllegalArgumentException when the value of
* <code>pos</code> < 0
*/
public void insert(String s, int pos) {
if (pos < 0) {
throw new IllegalArgumentException("index less than zero.");
}
ensurePopupMenuCreated();
popupMenu.insert(new JMenuItem(s), pos);
}
/** {@collect.stats}
* Inserts the specified <code>JMenuitem</code> at a given position.
*
* @param mi the <code>JMenuitem</code> to add
* @param pos an integer specifying the position at which to add the
* new <code>JMenuitem</code>
* @return the new menu item
* @exception IllegalArgumentException if the value of
* <code>pos</code> < 0
*/
public JMenuItem insert(JMenuItem mi, int pos) {
if (pos < 0) {
throw new IllegalArgumentException("index less than zero.");
}
ensurePopupMenuCreated();
popupMenu.insert(mi, pos);
return mi;
}
/** {@collect.stats}
* Inserts a new menu item attached to the specified <code>Action</code>
* object at a given position.
*
* @param a the <code>Action</code> object for the menu item to add
* @param pos an integer specifying the position at which to add the
* new menu item
* @exception IllegalArgumentException if the value of
* <code>pos</code> < 0
*/
public JMenuItem insert(Action a, int pos) {
if (pos < 0) {
throw new IllegalArgumentException("index less than zero.");
}
ensurePopupMenuCreated();
JMenuItem mi = new JMenuItem(a);
mi.setHorizontalTextPosition(JButton.TRAILING);
mi.setVerticalTextPosition(JButton.CENTER);
popupMenu.insert(mi, pos);
return mi;
}
/** {@collect.stats}
* Inserts a separator at the specified position.
*
* @param index an integer specifying the position at which to
* insert the menu separator
* @exception IllegalArgumentException if the value of
* <code>index</code> < 0
*/
public void insertSeparator(int index) {
if (index < 0) {
throw new IllegalArgumentException("index less than zero.");
}
ensurePopupMenuCreated();
popupMenu.insert( new JPopupMenu.Separator(), index );
}
/** {@collect.stats}
* Returns the <code>JMenuItem</code> at the specified position.
* If the component at <code>pos</code> is not a menu item,
* <code>null</code> is returned.
* This method is included for AWT compatibility.
*
* @param pos an integer specifying the position
* @exception IllegalArgumentException if the value of
* <code>pos</code> < 0
* @return the menu item at the specified position; or <code>null</code>
* if the item as the specified position is not a menu item
*/
public JMenuItem getItem(int pos) {
if (pos < 0) {
throw new IllegalArgumentException("index less than zero.");
}
Component c = getMenuComponent(pos);
if (c instanceof JMenuItem) {
JMenuItem mi = (JMenuItem) c;
return mi;
}
// 4173633
return null;
}
/** {@collect.stats}
* Returns the number of items on the menu, including separators.
* This method is included for AWT compatibility.
*
* @return an integer equal to the number of items on the menu
* @see #getMenuComponentCount
*/
public int getItemCount() {
return getMenuComponentCount();
}
/** {@collect.stats}
* Returns true if the menu can be torn off. This method is not
* yet implemented.
*
* @return true if the menu can be torn off, else false
* @exception Error if invoked -- this method is not yet implemented
*/
public boolean isTearOff() {
throw new Error("boolean isTearOff() {} not yet implemented");
}
/** {@collect.stats}
* Removes the specified menu item from this menu. If there is no
* popup menu, this method will have no effect.
*
* @param item the <code>JMenuItem</code> to be removed from the menu
*/
public void remove(JMenuItem item) {
if (popupMenu != null)
popupMenu.remove(item);
}
/** {@collect.stats}
* Removes the menu item at the specified index from this menu.
*
* @param pos the position of the item to be removed
* @exception IllegalArgumentException if the value of
* <code>pos</code> < 0, or if <code>pos</code>
* is greater than the number of menu items
*/
public void remove(int pos) {
if (pos < 0) {
throw new IllegalArgumentException("index less than zero.");
}
if (pos > getItemCount()) {
throw new IllegalArgumentException("index greater than the number of items.");
}
if (popupMenu != null)
popupMenu.remove(pos);
}
/** {@collect.stats}
* Removes the component <code>c</code> from this menu.
*
* @param c the component to be removed
*/
public void remove(Component c) {
if (popupMenu != null)
popupMenu.remove(c);
}
/** {@collect.stats}
* Removes all menu items from this menu.
*/
public void removeAll() {
if (popupMenu != null)
popupMenu.removeAll();
}
/** {@collect.stats}
* Returns the number of components on the menu.
*
* @return an integer containing the number of components on the menu
*/
public int getMenuComponentCount() {
int componentCount = 0;
if (popupMenu != null)
componentCount = popupMenu.getComponentCount();
return componentCount;
}
/** {@collect.stats}
* Returns the component at position <code>n</code>.
*
* @param n the position of the component to be returned
* @return the component requested, or <code>null</code>
* if there is no popup menu
*
*/
public Component getMenuComponent(int n) {
if (popupMenu != null)
return popupMenu.getComponent(n);
return null;
}
/** {@collect.stats}
* Returns an array of <code>Component</code>s of the menu's
* subcomponents. Note that this returns all <code>Component</code>s
* in the popup menu, including separators.
*
* @return an array of <code>Component</code>s or an empty array
* if there is no popup menu
*/
public Component[] getMenuComponents() {
if (popupMenu != null)
return popupMenu.getComponents();
return new Component[0];
}
/** {@collect.stats}
* Returns true if the menu is a 'top-level menu', that is, if it is
* the direct child of a menubar.
*
* @return true if the menu is activated from the menu bar;
* false if the menu is activated from a menu item
* on another menu
*/
public boolean isTopLevelMenu() {
if (getParent() instanceof JMenuBar)
return true;
return false;
}
/** {@collect.stats}
* Returns true if the specified component exists in the
* submenu hierarchy.
*
* @param c the <code>Component</code> to be tested
* @return true if the <code>Component</code> exists, false otherwise
*/
public boolean isMenuComponent(Component c) {
// Are we in the MenuItem part of the menu
if (c == this)
return true;
// Are we in the PopupMenu?
if (c instanceof JPopupMenu) {
JPopupMenu comp = (JPopupMenu) c;
if (comp == this.getPopupMenu())
return true;
}
// Are we in a Component on the PopupMenu
int ncomponents = this.getMenuComponentCount();
Component[] component = this.getMenuComponents();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = component[i];
// Are we in the current component?
if (comp == c)
return true;
// Hmmm, what about Non-menu containers?
// Recursive call for the Menu case
if (comp instanceof JMenu) {
JMenu subMenu = (JMenu) comp;
if (subMenu.isMenuComponent(c))
return true;
}
}
return false;
}
/*
* Returns a point in the coordinate space of this menu's popupmenu
* which corresponds to the point <code>p</code> in the menu's
* coordinate space.
*
* @param p the point to be translated
* @return the point in the coordinate space of this menu's popupmenu
*/
private Point translateToPopupMenu(Point p) {
return translateToPopupMenu(p.x, p.y);
}
/*
* Returns a point in the coordinate space of this menu's popupmenu
* which corresponds to the point (x,y) in the menu's coordinate space.
*
* @param x the x coordinate of the point to be translated
* @param y the y coordinate of the point to be translated
* @return the point in the coordinate space of this menu's popupmenu
*/
private Point translateToPopupMenu(int x, int y) {
int newX;
int newY;
if (getParent() instanceof JPopupMenu) {
newX = x - getSize().width;
newY = y;
} else {
newX = x;
newY = y - getSize().height;
}
return new Point(newX, newY);
}
/** {@collect.stats}
* Returns the popupmenu associated with this menu. If there is
* no popupmenu, it will create one.
*/
public JPopupMenu getPopupMenu() {
ensurePopupMenuCreated();
return popupMenu;
}
/** {@collect.stats}
* Adds a listener for menu events.
*
* @param l the listener to be added
*/
public void addMenuListener(MenuListener l) {
listenerList.add(MenuListener.class, l);
}
/** {@collect.stats}
* Removes a listener for menu events.
*
* @param l the listener to be removed
*/
public void removeMenuListener(MenuListener l) {
listenerList.remove(MenuListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>MenuListener</code>s added
* to this JMenu with addMenuListener().
*
* @return all of the <code>MenuListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public MenuListener[] getMenuListeners() {
return (MenuListener[])listenerList.getListeners(MenuListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is created lazily.
*
* @exception Error if there is a <code>null</code> listener
* @see EventListenerList
*/
protected void fireMenuSelected() {
if (DEBUG) {
System.out.println("In JMenu.fireMenuSelected");
}
// 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]==MenuListener.class) {
if (listeners[i+1]== null) {
throw new Error(getText() +" has a NULL Listener!! " + i);
} else {
// Lazily create the event:
if (menuEvent == null)
menuEvent = new MenuEvent(this);
((MenuListener)listeners[i+1]).menuSelected(menuEvent);
}
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is created lazily.
*
* @exception Error if there is a <code>null</code> listener
* @see EventListenerList
*/
protected void fireMenuDeselected() {
if (DEBUG) {
System.out.println("In JMenu.fireMenuDeselected");
}
// 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]==MenuListener.class) {
if (listeners[i+1]== null) {
throw new Error(getText() +" has a NULL Listener!! " + i);
} else {
// Lazily create the event:
if (menuEvent == null)
menuEvent = new MenuEvent(this);
((MenuListener)listeners[i+1]).menuDeselected(menuEvent);
}
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is created lazily.
*
* @exception Error if there is a <code>null</code> listener
* @see EventListenerList
*/
protected void fireMenuCanceled() {
if (DEBUG) {
System.out.println("In JMenu.fireMenuCanceled");
}
// 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]==MenuListener.class) {
if (listeners[i+1]== null) {
throw new Error(getText() +" has a NULL Listener!! "
+ i);
} else {
// Lazily create the event:
if (menuEvent == null)
menuEvent = new MenuEvent(this);
((MenuListener)listeners[i+1]).menuCanceled(menuEvent);
}
}
}
}
// Overriden to do nothing, JMenu doesn't support an accelerator
void configureAcceleratorFromAction(Action a) {
}
class MenuChangeListener implements ChangeListener, Serializable {
boolean isSelected = false;
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
boolean modelSelected = model.isSelected();
if (modelSelected != isSelected) {
if (modelSelected == true) {
fireMenuSelected();
} else {
fireMenuDeselected();
}
isSelected = modelSelected;
}
}
}
private ChangeListener createMenuChangeListener() {
return new MenuChangeListener();
}
/** {@collect.stats}
* Creates a window-closing listener for the popup.
*
* @param p the <code>JPopupMenu</code>
* @return the new window-closing listener
*
* @see WinListener
*/
protected WinListener createWinListener(JPopupMenu p) {
return new WinListener(p);
}
/** {@collect.stats}
* A listener class that watches for a popup window closing.
* When the popup is closing, the listener deselects the menu.
* <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 WinListener extends WindowAdapter implements Serializable {
JPopupMenu popupMenu;
/** {@collect.stats}
* Create the window listener for the specified popup.
* @since 1.4
*/
public WinListener(JPopupMenu p) {
this.popupMenu = p;
}
/** {@collect.stats}
* Deselect the menu when the popup is closed from outside.
*/
public void windowClosing(WindowEvent e) {
setSelected(false);
}
}
/** {@collect.stats}
* Messaged when the menubar selection changes to activate or
* deactivate this menu.
* Overrides <code>JMenuItem.menuSelectionChanged</code>.
*
* @param isIncluded true if this menu is active, false if
* it is not
*/
public void menuSelectionChanged(boolean isIncluded) {
if (DEBUG) {
System.out.println("In JMenu.menuSelectionChanged to " + isIncluded);
}
setSelected(isIncluded);
}
/** {@collect.stats}
* Returns an array of <code>MenuElement</code>s containing the submenu
* for this menu component. If popup menu is <code>null</code> returns
* an empty array. This method is required to conform to the
* <code>MenuElement</code> interface. Note that since
* <code>JSeparator</code>s do not conform to the <code>MenuElement</code>
* interface, this array will only contain <code>JMenuItem</code>s.
*
* @return an array of <code>MenuElement</code> objects
*/
public MenuElement[] getSubElements() {
if(popupMenu == null)
return new MenuElement[0];
else {
MenuElement result[] = new MenuElement[1];
result[0] = popupMenu;
return result;
}
}
// implements javax.swing.MenuElement
/** {@collect.stats}
* Returns the <code>java.awt.Component</code> used to
* paint this <code>MenuElement</code>.
* The returned component is used to convert events and detect if
* an event is inside a menu component.
*/
public Component getComponent() {
return this;
}
/** {@collect.stats}
* Sets the <code>ComponentOrientation</code> property of this menu
* and all components contained within it. This includes all
* components returned by {@link #getMenuComponents getMenuComponents}.
*
* @param o the new component orientation of this menu and
* the components contained within it.
* @exception NullPointerException if <code>orientation</code> is null.
* @see java.awt.Component#setComponentOrientation
* @see java.awt.Component#getComponentOrientation
* @since 1.4
*/
public void applyComponentOrientation(ComponentOrientation o) {
super.applyComponentOrientation(o);
if ( popupMenu != null ) {
int ncomponents = getMenuComponentCount();
for (int i = 0 ; i < ncomponents ; ++i) {
getMenuComponent(i).applyComponentOrientation(o);
}
popupMenu.setComponentOrientation(o);
}
}
public void setComponentOrientation(ComponentOrientation o) {
super.setComponentOrientation(o);
if ( popupMenu != null ) {
popupMenu.setComponentOrientation(o);
}
}
/** {@collect.stats}
* <code>setAccelerator</code> is not defined for <code>JMenu</code>.
* Use <code>setMnemonic</code> instead.
* @param keyStroke the keystroke combination which will invoke
* the <code>JMenuItem</code>'s actionlisteners
* without navigating the menu hierarchy
* @exception Error if invoked -- this method is not defined for JMenu.
* Use <code>setMnemonic</code> instead
*
* @beaninfo
* description: The keystroke combination which will invoke the JMenuItem's
* actionlisteners without navigating the menu hierarchy
* hidden: true
*/
public void setAccelerator(KeyStroke keyStroke) {
throw new Error("setAccelerator() is not defined for JMenu. Use setMnemonic() instead.");
}
/** {@collect.stats}
* Processes key stroke events such as mnemonics and accelerators.
*
* @param evt the key event to be processed
*/
protected void processKeyEvent(KeyEvent evt) {
MenuSelectionManager.defaultManager().processKeyEvent(evt);
if (evt.isConsumed())
return;
super.processKeyEvent(evt);
}
/** {@collect.stats}
* Programmatically performs a "click". This overrides the method
* <code>AbstractButton.doClick</code> in order to make the menu pop up.
* @param pressTime indicates the number of milliseconds the
* button was pressed for
*/
public void doClick(int pressTime) {
MenuElement me[] = buildMenuElementArray(this);
MenuSelectionManager.defaultManager().setSelectedPath(me);
}
/*
* Build an array of menu elements - from <code>PopupMenu</code> to
* the root <code>JMenuBar</code>.
* @param leaf the leaf node from which to start building up the array
* @return the array of menu items
*/
private MenuElement[] buildMenuElementArray(JMenu leaf) {
Vector elements = new Vector();
Component current = leaf.getPopupMenu();
JPopupMenu pop;
JMenu menu;
JMenuBar bar;
while (true) {
if (current instanceof JPopupMenu) {
pop = (JPopupMenu) current;
elements.insertElementAt(pop, 0);
current = pop.getInvoker();
} else if (current instanceof JMenu) {
menu = (JMenu) current;
elements.insertElementAt(menu, 0);
current = menu.getParent();
} else if (current instanceof JMenuBar) {
bar = (JMenuBar) current;
elements.insertElementAt(bar, 0);
MenuElement me[] = new MenuElement[elements.size()];
elements.copyInto(me);
return me;
}
}
}
/** {@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>JMenu</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 JMenu.
*/
protected String paramString() {
return super.paramString();
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JMenu.
* For JMenus, the AccessibleContext takes the form of an
* AccessibleJMenu.
* A new AccessibleJMenu instance is created if necessary.
*
* @return an AccessibleJMenu that serves as the
* AccessibleContext of this JMenu
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJMenu();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JMenu</code> class. It provides an implementation of the
* Java Accessibility API appropriate to menu 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 AccessibleJMenu extends AccessibleJMenuItem
implements AccessibleSelection {
/** {@collect.stats}
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
Component[] children = getMenuComponents();
int count = 0;
for (int j = 0; j < children.length; j++) {
if (children[j] instanceof Accessible) {
count++;
}
}
return count;
}
/** {@collect.stats}
* Returns the nth Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
Component[] children = getMenuComponents();
int count = 0;
for (int j = 0; j < children.length; j++) {
if (children[j] instanceof Accessible) {
if (count == i) {
if (children[j] instanceof JComponent) {
// FIXME: [[[WDW - probably should set this when
// the component is added to the menu. I tried
// to do this in most cases, but the separators
// added by addSeparator are hard to get to.]]]
AccessibleContext ac = ((Accessible) children[j]).getAccessibleContext();
ac.setAccessibleParent(JMenu.this);
}
return (Accessible) children[j];
} else {
count++;
}
}
}
return null;
}
/** {@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.MENU;
}
/** {@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 sub-menu is currently selected in this menu.
*
* @return 1 if a menu is currently selected, else 0
*/
public int getAccessibleSelectionCount() {
MenuElement me[] =
MenuSelectionManager.defaultManager().getSelectedPath();
if (me != null) {
for (int i = 0; i < me.length; i++) {
if (me[i] == JMenu.this) { // this menu is selected
if (i+1 < me.length) {
return 1;
}
}
}
}
return 0;
}
/** {@collect.stats}
* Returns the currently selected sub-menu if one is selected,
* otherwise null (there can only be one selection, and it can
* only be a sub-menu, as otherwise menu items don't remain
* selected).
*/
public Accessible getAccessibleSelection(int i) {
// if i is a sub-menu & popped, return it
if (i < 0 || i >= getItemCount()) {
return null;
}
MenuElement me[] =
MenuSelectionManager.defaultManager().getSelectedPath();
if (me != null) {
for (int j = 0; j < me.length; j++) {
if (me[j] == JMenu.this) { // this menu is selected
// so find the next JMenuItem in the MenuElement
// array, and return it!
while (++j < me.length) {
if (me[j] instanceof JMenuItem) {
return (Accessible) me[j];
}
}
}
}
}
return null;
}
/** {@collect.stats}
* Returns true if the current child of this object is selected
* (that is, if this child is a popped-up submenu).
*
* @param i the zero-based index of the child in this Accessible
* object.
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
// if i is a sub-menu and is pop-ed up, return true, else false
MenuElement me[] =
MenuSelectionManager.defaultManager().getSelectedPath();
if (me != null) {
JMenuItem mi = JMenu.this.getItem(i);
for (int j = 0; j < me.length; j++) {
if (me[j] == mi) {
return true;
}
}
}
return false;
}
/** {@collect.stats}
* Selects the <code>i</code>th menu in the menu.
* If that item is a submenu,
* it will pop up in response. If a different item is already
* popped up, this will force it to close. If this is a sub-menu
* that is already popped up (selected), this method has no
* effect.
*
* @param i the index of the item to be selected
* @see #getAccessibleStateSet
*/
public void addAccessibleSelection(int i) {
if (i < 0 || i >= getItemCount()) {
return;
}
JMenuItem mi = getItem(i);
if (mi != null) {
if (mi instanceof JMenu) {
MenuElement me[] = buildMenuElementArray((JMenu) mi);
MenuSelectionManager.defaultManager().setSelectedPath(me);
} else {
MenuSelectionManager.defaultManager().setSelectedPath(null);
}
}
}
/** {@collect.stats}
* Removes the nth item from the selection. In general, menus
* can only have one item within them selected at a time
* (e.g. one sub-menu popped open).
*
* @param i the zero-based index of the selected item
*/
public void removeAccessibleSelection(int i) {
if (i < 0 || i >= getItemCount()) {
return;
}
JMenuItem mi = getItem(i);
if (mi != null && mi instanceof JMenu) {
if (((JMenu) mi).isSelected()) {
MenuElement old[] =
MenuSelectionManager.defaultManager().getSelectedPath();
MenuElement me[] = new MenuElement[old.length-2];
for (int j = 0; j < old.length -2; j++) {
me[j] = old[j];
}
MenuSelectionManager.defaultManager().setSelectedPath(me);
}
}
}
/** {@collect.stats}
* Clears the selection in the object, so that nothing in the
* object is selected. This will close any open sub-menu.
*/
public void clearAccessibleSelection() {
// if this menu is selected, reset selection to only go
// to this menu; else do nothing
MenuElement old[] =
MenuSelectionManager.defaultManager().getSelectedPath();
if (old != null) {
for (int j = 0; j < old.length; j++) {
if (old[j] == JMenu.this) { // menu is in the selection!
MenuElement me[] = new MenuElement[j+1];
System.arraycopy(old, 0, me, 0, j);
me[j] = JMenu.this.getPopupMenu();
MenuSelectionManager.defaultManager().setSelectedPath(me);
}
}
}
}
/** {@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() {
}
} // inner class AccessibleJMenu
}
|
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.*;
/** {@collect.stats}
* Defines the data model used by components like <code>Slider</code>s
* and <code>ProgressBar</code>s.
* Defines four interrelated integer properties: minimum, maximum, extent
* and value. These four integers define two nested ranges like this:
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
* The outer range is <code>minimum,maximum</code> and the inner
* range is <code>value,value+extent</code>. The inner range
* must lie within the outer one, i.e. <code>value</code> must be
* less than or equal to <code>maximum</code> and <code>value+extent</code>
* must greater than or equal to <code>minimum</code>, and <code>maximum</code>
* must be greater than or equal to <code>minimum</code>.
* There are a few features of this model that one might find a little
* surprising. These quirks exist for the convenience of the
* Swing BoundedRangeModel clients, such as <code>Slider</code> and
* <code>ScrollBar</code>.
* <ul>
* <li>
* The minimum and maximum set methods "correct" the other
* three properties to accommodate their new value argument. For
* example setting the model's minimum may change its maximum, value,
* and extent properties (in that order), to maintain the constraints
* specified above.
*
* <li>
* The value and extent set methods "correct" their argument to
* fit within the limits defined by the other three properties.
* For example if <code>value == maximum</code>, <code>setExtent(10)</code>
* would change the extent (back) to zero.
*
* <li>
* The four BoundedRangeModel values are defined as Java Beans properties
* however Swing ChangeEvents are used to notify clients of changes rather
* than PropertyChangeEvents. This was done to keep the overhead of monitoring
* a BoundedRangeModel low. Changes are often reported at MouseDragged rates.
* </ul>
*
* <p>
*
* For an example of specifying custom bounded range models used by sliders,
* see <a
href="http://java.sun.com/docs/books/tutorial/uiswing/overview/anatomy.html">The Anatomy of a Swing-Based Program</a>
* in <em>The Java Tutorial.</em>
*
* @author Hans Muller
* @see DefaultBoundedRangeModel
*/
public interface BoundedRangeModel
{
/** {@collect.stats}
* Returns the minimum acceptable value.
*
* @return the value of the minimum property
* @see #setMinimum
*/
int getMinimum();
/** {@collect.stats}
* Sets the model's minimum to <I>newMinimum</I>. The
* other three properties may be changed as well, to ensure
* that:
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
* <p>
* Notifies any listeners if the model changes.
*
* @param newMinimum the model's new minimum
* @see #getMinimum
* @see #addChangeListener
*/
void setMinimum(int newMinimum);
/** {@collect.stats}
* Returns the model's maximum. Note that the upper
* limit on the model's value is (maximum - extent).
*
* @return the value of the maximum property.
* @see #setMaximum
* @see #setExtent
*/
int getMaximum();
/** {@collect.stats}
* Sets the model's maximum to <I>newMaximum</I>. The other
* three properties may be changed as well, to ensure that
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
* <p>
* Notifies any listeners if the model changes.
*
* @param newMaximum the model's new maximum
* @see #getMaximum
* @see #addChangeListener
*/
void setMaximum(int newMaximum);
/** {@collect.stats}
* Returns the model's current value. Note that the upper
* limit on the model's value is <code>maximum - extent</code>
* and the lower limit is <code>minimum</code>.
*
* @return the model's value
* @see #setValue
*/
int getValue();
/** {@collect.stats}
* Sets the model's current value to <code>newValue</code> if <code>newValue</code>
* satisfies the model's constraints. Those constraints are:
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
* Otherwise, if <code>newValue</code> is less than <code>minimum</code>
* it's set to <code>minimum</code>, if its greater than
* <code>maximum</code> then it's set to <code>maximum</code>, and
* if it's greater than <code>value+extent</code> then it's set to
* <code>value+extent</code>.
* <p>
* When a BoundedRange model is used with a scrollbar the value
* specifies the origin of the scrollbar knob (aka the "thumb" or
* "elevator"). The value usually represents the origin of the
* visible part of the object being scrolled.
* <p>
* Notifies any listeners if the model changes.
*
* @param newValue the model's new value
* @see #getValue
*/
void setValue(int newValue);
/** {@collect.stats}
* This attribute indicates that any upcoming changes to the value
* of the model should be considered a single event. This attribute
* will be set to true at the start of a series of changes to the value,
* and will be set to false when the value has finished changing. Normally
* this allows a listener to only take action when the final value change in
* committed, instead of having to do updates for all intermediate values.
* <p>
* Sliders and scrollbars use this property when a drag is underway.
*
* @param b true if the upcoming changes to the value property are part of a series
*/
void setValueIsAdjusting(boolean b);
/** {@collect.stats}
* Returns true if the current changes to the value property are part
* of a series of changes.
*
* @return the valueIsAdjustingProperty.
* @see #setValueIsAdjusting
*/
boolean getValueIsAdjusting();
/** {@collect.stats}
* Returns the model's extent, the length of the inner range that
* begins at the model's value.
*
* @return the value of the model's extent property
* @see #setExtent
* @see #setValue
*/
int getExtent();
/** {@collect.stats}
* Sets the model's extent. The <I>newExtent</I> is forced to
* be greater than or equal to zero and less than or equal to
* maximum - value.
* <p>
* When a BoundedRange model is used with a scrollbar the extent
* defines the length of the scrollbar knob (aka the "thumb" or
* "elevator"). The extent usually represents how much of the
* object being scrolled is visible. When used with a slider,
* the extent determines how much the value can "jump", for
* example when the user presses PgUp or PgDn.
* <p>
* Notifies any listeners if the model changes.
*
* @param newExtent the model's new extent
* @see #getExtent
* @see #setValue
*/
void setExtent(int newExtent);
/** {@collect.stats}
* This method sets all of the model's data with a single method call.
* The method results in a single change event being generated. This is
* convenient when you need to adjust all the model data simultaneously and
* do not want individual change events to occur.
*
* @param value an int giving the current value
* @param extent an int giving the amount by which the value can "jump"
* @param min an int giving the minimum value
* @param max an int giving the maximum value
* @param adjusting a boolean, true if a series of changes are in
* progress
*
* @see #setValue
* @see #setExtent
* @see #setMinimum
* @see #setMaximum
* @see #setValueIsAdjusting
*/
void setRangeProperties(int value, int extent, int min, int max, boolean adjusting);
/** {@collect.stats}
* Adds a ChangeListener to the model's listener list.
*
* @param x the ChangeListener to add
* @see #removeChangeListener
*/
void addChangeListener(ChangeListener x);
/** {@collect.stats}
* Removes a ChangeListener from the model's listener list.
*
* @param x the ChangeListener to remove
* @see #addChangeListener
*/
void removeChangeListener(ChangeListener x);
}
|
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.util.ArrayList;
import java.util.Hashtable;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.accessibility.*;
/** {@collect.stats}
* <code>JLayeredPane</code> adds depth to a JFC/Swing container,
* allowing components to overlap each other when needed.
* An <code>Integer</code> object specifies each component's depth in the
* container, where higher-numbered components sit "on top" of other
* components.
* For task-oriented documentation and examples of using layered panes see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html">How to Use a Layered Pane</a>,
* a section in <em>The Java Tutorial</em>.
* <P>
* <TABLE ALIGN="RIGHT" BORDER="0" SUMMARY="layout">
* <TR>
* <TD ALIGN="CENTER">
* <P ALIGN="CENTER"><IMG SRC="doc-files/JLayeredPane-1.gif"
* alt="The following text describes this image."
* WIDTH="269" HEIGHT="264" ALIGN="BOTTOM" BORDER="0">
* </TD>
* </TR>
* </TABLE>
* For convenience, <code>JLayeredPane</code> divides the depth-range
* into several different layers. Putting a component into one of those
* layers makes it easy to ensure that components overlap properly,
* without having to worry about specifying numbers for specific depths:
* <DL>
* <DT><FONT SIZE="2">DEFAULT_LAYER</FONT></DT>
* <DD>The standard layer, where most components go. This the bottommost
* layer.
* <DT><FONT SIZE="2">PALETTE_LAYER</FONT></DT>
* <DD>The palette layer sits over the default layer. Useful for floating
* toolbars and palettes, so they can be positioned above other components.
* <DT><FONT SIZE="2">MODAL_LAYER</FONT></DT>
* <DD>The layer used for modal dialogs. They will appear on top of any
* toolbars, palettes, or standard components in the container.
* <DT><FONT SIZE="2">POPUP_LAYER</FONT></DT>
* <DD>The popup layer displays above dialogs. That way, the popup windows
* associated with combo boxes, tooltips, and other help text will appear
* above the component, palette, or dialog that generated them.
* <DT><FONT SIZE="2">DRAG_LAYER</FONT></DT>
* <DD>When dragging a component, reassigning it to the drag layer ensures
* that it is positioned over every other component in the container. When
* finished dragging, it can be reassigned to its normal layer.
* </DL>
* The <code>JLayeredPane</code> methods <code>moveToFront(Component)</code>,
* <code>moveToBack(Component)</code> and <code>setPosition</code> can be used
* to reposition a component within its layer. The <code>setLayer</code> method
* can also be used to change the component's current layer.
*
* <h2>Details</h2>
* <code>JLayeredPane</code> manages its list of children like
* <code>Container</code>, but allows for the definition of a several
* layers within itself. Children in the same layer are managed exactly
* like the normal <code>Container</code> object,
* with the added feature that when children components overlap, children
* in higher layers display above the children in lower layers.
* <p>
* Each layer is a distinct integer number. The layer attribute can be set
* on a <code>Component</code> by passing an <code>Integer</code>
* object during the add call.<br> For example:
* <PRE>
* layeredPane.add(child, JLayeredPane.DEFAULT_LAYER);
* or
* layeredPane.add(child, new Integer(10));
* </PRE>
* The layer attribute can also be set on a Component by calling<PRE>
* layeredPaneParent.setLayer(child, 10)</PRE>
* on the <code>JLayeredPane</code> that is the parent of component. The layer
* should be set <i>before</i> adding the child to the parent.
* <p>
* Higher number layers display above lower number layers. So, using
* numbers for the layers and letters for individual components, a
* representative list order would look like this:<PRE>
* 5a, 5b, 5c, 2a, 2b, 2c, 1a </PRE>
* where the leftmost components are closest to the top of the display.
* <p>
* A component can be moved to the top or bottom position within its
* layer by calling <code>moveToFront</code> or <code>moveToBack</code>.
* <p>
* The position of a component within a layer can also be specified directly.
* Valid positions range from 0 up to one less than the number of
* components in that layer. A value of -1 indicates the bottommost
* position. A value of 0 indicates the topmost position. Unlike layer
* numbers, higher position values are <i>lower</i> in the display.
* <blockquote>
* <b>Note:</b> This sequence (defined by java.awt.Container) is the reverse
* of the layer numbering sequence. Usually though, you will use <code>moveToFront</code>,
* <code>moveToBack</code>, and <code>setLayer</code>.
* </blockquote>
* Here are some examples using the method add(Component, layer, position):
* Calling add(5x, 5, -1) results in:<PRE>
* 5a, 5b, 5c, 5x, 2a, 2b, 2c, 1a </PRE>
*
* Calling add(5z, 5, 2) results in:<PRE>
* 5a, 5b, 5z, 5c, 5x, 2a, 2b, 2c, 1a </PRE>
*
* Calling add(3a, 3, 7) results in:<PRE>
* 5a, 5b, 5z, 5c, 5x, 3a, 2a, 2b, 2c, 1a </PRE>
*
* Using normal paint/event mechanics results in 1a appearing at the bottom
* and 5a being above all other components.
* <p>
* <b>Note:</b> that these layers are simply a logical construct and LayoutManagers
* will affect all child components of this container without regard for
* layer settings.
* <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}.
*
* @author David Kloba
*/
public class JLayeredPane extends JComponent implements Accessible {
/// Watch the values in getObjectForLayer()
/** {@collect.stats} Convenience object defining the Default layer. Equivalent to new Integer(0).*/
public final static Integer DEFAULT_LAYER = new Integer(0);
/** {@collect.stats} Convenience object defining the Palette layer. Equivalent to new Integer(100).*/
public final static Integer PALETTE_LAYER = new Integer(100);
/** {@collect.stats} Convenience object defining the Modal layer. Equivalent to new Integer(200).*/
public final static Integer MODAL_LAYER = new Integer(200);
/** {@collect.stats} Convenience object defining the Popup layer. Equivalent to new Integer(300).*/
public final static Integer POPUP_LAYER = new Integer(300);
/** {@collect.stats} Convenience object defining the Drag layer. Equivalent to new Integer(400).*/
public final static Integer DRAG_LAYER = new Integer(400);
/** {@collect.stats} Convenience object defining the Frame Content layer.
* This layer is normally only use to positon the contentPane and menuBar
* components of JFrame.
* Equivalent to new Integer(-30000).
* @see JFrame
*/
public final static Integer FRAME_CONTENT_LAYER = new Integer(-30000);
/** {@collect.stats} Bound property */
public final static String LAYER_PROPERTY = "layeredContainerLayer";
// Hashtable to store layer values for non-JComponent components
private Hashtable<Component,Integer> componentToLayer;
private boolean optimizedDrawingPossible = true;
//////////////////////////////////////////////////////////////////////////////
//// Container Override methods
//////////////////////////////////////////////////////////////////////////////
/** {@collect.stats} Create a new JLayeredPane */
public JLayeredPane() {
setLayout(null);
}
private void validateOptimizedDrawing() {
boolean layeredComponentFound = false;
synchronized(getTreeLock()) {
Integer layer = null;
for (Component c : getComponents()) {
layer = null;
if(c instanceof JInternalFrame || (c instanceof JComponent &&
(layer = (Integer)((JComponent)c).getClientProperty(
LAYER_PROPERTY)) != null)) {
if(layer != null && layer.equals(FRAME_CONTENT_LAYER))
continue;
layeredComponentFound = true;
break;
}
}
}
if(layeredComponentFound)
optimizedDrawingPossible = false;
else
optimizedDrawingPossible = true;
}
protected void addImpl(Component comp, Object constraints, int index) {
int layer = DEFAULT_LAYER.intValue();
int pos;
if(constraints instanceof Integer) {
layer = ((Integer)constraints).intValue();
setLayer(comp, layer);
} else
layer = getLayer(comp);
pos = insertIndexForLayer(layer, index);
super.addImpl(comp, constraints, pos);
comp.validate();
comp.repaint();
validateOptimizedDrawing();
}
/** {@collect.stats}
* Remove the indexed component from this pane.
* This is the absolute index, ignoring layers.
*
* @param index an int specifying the component to remove
* @see #getIndexOf
*/
public void remove(int index) {
Component c = getComponent(index);
super.remove(index);
if (c != null && !(c instanceof JComponent)) {
getComponentToLayer().remove(c);
}
validateOptimizedDrawing();
}
/** {@collect.stats}
* Removes all the components from this container.
*
* @since 1.5
*/
public void removeAll() {
Component[] children = getComponents();
Hashtable cToL = getComponentToLayer();
for (int counter = children.length - 1; counter >= 0; counter--) {
Component c = children[counter];
if (c != null && !(c instanceof JComponent)) {
cToL.remove(c);
}
}
super.removeAll();
}
/** {@collect.stats}
* Returns false if components in the pane can overlap, which makes
* optimized drawing impossible. Otherwise, returns true.
*
* @return false if components can overlap, else true
* @see JComponent#isOptimizedDrawingEnabled
*/
public boolean isOptimizedDrawingEnabled() {
return optimizedDrawingPossible;
}
//////////////////////////////////////////////////////////////////////////////
//// New methods for managing layers
//////////////////////////////////////////////////////////////////////////////
/** {@collect.stats} Sets the layer property on a JComponent. This method does not cause
* any side effects like setLayer() (painting, add/remove, etc).
* Normally you should use the instance method setLayer(), in order to
* get the desired side-effects (like repainting).
*
* @param c the JComponent to move
* @param layer an int specifying the layer to move it to
* @see #setLayer
*/
public static void putLayer(JComponent c, int layer) {
/// MAKE SURE THIS AND setLayer(Component c, int layer, int position) are SYNCED
Integer layerObj;
layerObj = new Integer(layer);
c.putClientProperty(LAYER_PROPERTY, layerObj);
}
/** {@collect.stats} Gets the layer property for a JComponent, it
* does not cause any side effects like setLayer(). (painting, add/remove, etc)
* Normally you should use the instance method getLayer().
*
* @param c the JComponent to check
* @return an int specifying the component's layer
*/
public static int getLayer(JComponent c) {
Integer i;
if((i = (Integer)c.getClientProperty(LAYER_PROPERTY)) != null)
return i.intValue();
return DEFAULT_LAYER.intValue();
}
/** {@collect.stats} Convenience method that returns the first JLayeredPane which
* contains the specified component. Note that all JFrames have a
* JLayeredPane at their root, so any component in a JFrame will
* have a JLayeredPane parent.
*
* @param c the Component to check
* @return the JLayeredPane that contains the component, or
* null if no JLayeredPane is found in the component
* hierarchy
* @see JFrame
* @see JRootPane
*/
public static JLayeredPane getLayeredPaneAbove(Component c) {
if(c == null) return null;
Component parent = c.getParent();
while(parent != null && !(parent instanceof JLayeredPane))
parent = parent.getParent();
return (JLayeredPane)parent;
}
/** {@collect.stats} Sets the layer attribute on the specified component,
* making it the bottommost component in that layer.
* Should be called before adding to parent.
*
* @param c the Component to set the layer for
* @param layer an int specifying the layer to set, where
* lower numbers are closer to the bottom
*/
public void setLayer(Component c, int layer) {
setLayer(c, layer, -1);
}
/** {@collect.stats} Sets the layer attribute for the specified component and
* also sets its position within that layer.
*
* @param c the Component to set the layer for
* @param layer an int specifying the layer to set, where
* lower numbers are closer to the bottom
* @param position an int specifying the position within the
* layer, where 0 is the topmost position and -1
* is the bottommost position
*/
public void setLayer(Component c, int layer, int position) {
Integer layerObj;
layerObj = getObjectForLayer(layer);
if(layer == getLayer(c) && position == getPosition(c)) {
repaint(c.getBounds());
return;
}
/// MAKE SURE THIS AND putLayer(JComponent c, int layer) are SYNCED
if(c instanceof JComponent)
((JComponent)c).putClientProperty(LAYER_PROPERTY, layerObj);
else
getComponentToLayer().put((Component)c, layerObj);
if(c.getParent() == null || c.getParent() != this) {
repaint(c.getBounds());
return;
}
int index = insertIndexForLayer(c, layer, position);
setComponentZOrder(c, index);
repaint(c.getBounds());
}
/** {@collect.stats}
* Returns the layer attribute for the specified Component.
*
* @param c the Component to check
* @return an int specifying the component's current layer
*/
public int getLayer(Component c) {
Integer i;
if(c instanceof JComponent)
i = (Integer)((JComponent)c).getClientProperty(LAYER_PROPERTY);
else
i = (Integer)getComponentToLayer().get((Component)c);
if(i == null)
return DEFAULT_LAYER.intValue();
return i.intValue();
}
/** {@collect.stats}
* Returns the index of the specified Component.
* This is the absolute index, ignoring layers.
* Index numbers, like position numbers, have the topmost component
* at index zero. Larger numbers are closer to the bottom.
*
* @param c the Component to check
* @return an int specifying the component's index
*/
public int getIndexOf(Component c) {
int i, count;
count = getComponentCount();
for(i = 0; i < count; i++) {
if(c == getComponent(i))
return i;
}
return -1;
}
/** {@collect.stats}
* Moves the component to the top of the components in its current layer
* (position 0).
*
* @param c the Component to move
* @see #setPosition(Component, int)
*/
public void moveToFront(Component c) {
setPosition(c, 0);
}
/** {@collect.stats}
* Moves the component to the bottom of the components in its current layer
* (position -1).
*
* @param c the Component to move
* @see #setPosition(Component, int)
*/
public void moveToBack(Component c) {
setPosition(c, -1);
}
/** {@collect.stats}
* Moves the component to <code>position</code> within its current layer,
* where 0 is the topmost position within the layer and -1 is the bottommost
* position.
* <p>
* <b>Note:</b> Position numbering is defined by java.awt.Container, and
* is the opposite of layer numbering. Lower position numbers are closer
* to the top (0 is topmost), and higher position numbers are closer to
* the bottom.
*
* @param c the Component to move
* @param position an int in the range -1..N-1, where N is the number of
* components in the component's current layer
*/
public void setPosition(Component c, int position) {
setLayer(c, getLayer(c), position);
}
/** {@collect.stats}
* Get the relative position of the component within its layer.
*
* @param c the Component to check
* @return an int giving the component's position, where 0 is the
* topmost position and the highest index value = the count
* count of components at that layer, minus 1
*
* @see #getComponentCountInLayer
*/
public int getPosition(Component c) {
int i, count, startLayer, curLayer, startLocation, pos = 0;
count = getComponentCount();
startLocation = getIndexOf(c);
if(startLocation == -1)
return -1;
startLayer = getLayer(c);
for(i = startLocation - 1; i >= 0; i--) {
curLayer = getLayer(getComponent(i));
if(curLayer == startLayer)
pos++;
else
return pos;
}
return pos;
}
/** {@collect.stats} Returns the highest layer value from all current children.
* Returns 0 if there are no children.
*
* @return an int indicating the layer of the topmost component in the
* pane, or zero if there are no children
*/
public int highestLayer() {
if(getComponentCount() > 0)
return getLayer(getComponent(0));
return 0;
}
/** {@collect.stats} Returns the lowest layer value from all current children.
* Returns 0 if there are no children.
*
* @return an int indicating the layer of the bottommost component in the
* pane, or zero if there are no children
*/
public int lowestLayer() {
int count = getComponentCount();
if(count > 0)
return getLayer(getComponent(count-1));
return 0;
}
/** {@collect.stats}
* Returns the number of children currently in the specified layer.
*
* @param layer an int specifying the layer to check
* @return an int specifying the number of components in that layer
*/
public int getComponentCountInLayer(int layer) {
int i, count, curLayer;
int layerCount = 0;
count = getComponentCount();
for(i = 0; i < count; i++) {
curLayer = getLayer(getComponent(i));
if(curLayer == layer) {
layerCount++;
/// Short circut the counting when we have them all
} else if(layerCount > 0 || curLayer < layer) {
break;
}
}
return layerCount;
}
/** {@collect.stats}
* Returns an array of the components in the specified layer.
*
* @param layer an int specifying the layer to check
* @return an array of Components contained in that layer
*/
public Component[] getComponentsInLayer(int layer) {
int i, count, curLayer;
int layerCount = 0;
Component[] results;
results = new Component[getComponentCountInLayer(layer)];
count = getComponentCount();
for(i = 0; i < count; i++) {
curLayer = getLayer(getComponent(i));
if(curLayer == layer) {
results[layerCount++] = getComponent(i);
/// Short circut the counting when we have them all
} else if(layerCount > 0 || curLayer < layer) {
break;
}
}
return results;
}
/** {@collect.stats}
* Paints this JLayeredPane within the specified graphics context.
*
* @param g the Graphics context within which to paint
*/
public void paint(Graphics g) {
if(isOpaque()) {
Rectangle r = g.getClipBounds();
Color c = getBackground();
if(c == null)
c = Color.lightGray;
g.setColor(c);
if (r != null) {
g.fillRect(r.x, r.y, r.width, r.height);
}
else {
g.fillRect(0, 0, getWidth(), getHeight());
}
}
super.paint(g);
}
//////////////////////////////////////////////////////////////////////////////
//// Implementation Details
//////////////////////////////////////////////////////////////////////////////
/** {@collect.stats}
* Returns the hashtable that maps components to layers.
*
* @return the Hashtable used to map components to their layers
*/
protected Hashtable<Component,Integer> getComponentToLayer() {
if(componentToLayer == null)
componentToLayer = new Hashtable<Component,Integer>(4);
return componentToLayer;
}
/** {@collect.stats}
* Returns the Integer object associated with a specified layer.
*
* @param layer an int specifying the layer
* @return an Integer object for that layer
*/
protected Integer getObjectForLayer(int layer) {
Integer layerObj;
switch(layer) {
case 0:
layerObj = DEFAULT_LAYER;
break;
case 100:
layerObj = PALETTE_LAYER;
break;
case 200:
layerObj = MODAL_LAYER;
break;
case 300:
layerObj = POPUP_LAYER;
break;
case 400:
layerObj = DRAG_LAYER;
break;
default:
layerObj = new Integer(layer);
}
return layerObj;
}
/** {@collect.stats}
* Primitive method that determines the proper location to
* insert a new child based on layer and position requests.
*
* @param layer an int specifying the layer
* @param position an int specifying the position within the layer
* @return an int giving the (absolute) insertion-index
*
* @see #getIndexOf
*/
protected int insertIndexForLayer(int layer, int position) {
return insertIndexForLayer(null, layer, position);
}
/** {@collect.stats}
* This method is an extended version of insertIndexForLayer()
* to support setLayer which uses Container.setZOrder which does
* not remove the component from the containment heirarchy though
* we need to ignore it when calculating the insertion index.
*
* @param comp component to ignore when determining index
* @param layer an int specifying the layer
* @param position an int specifying the position within the layer
* @return an int giving the (absolute) insertion-index
*
* @see #getIndexOf
*/
private int insertIndexForLayer(Component comp, int layer, int position) {
int i, count, curLayer;
int layerStart = -1;
int layerEnd = -1;
int componentCount = getComponentCount();
ArrayList<Component> compList =
new ArrayList<Component>(componentCount);
for (int index = 0; index < componentCount; index++) {
if (getComponent(index) != comp) {
compList.add(getComponent(index));
}
}
count = compList.size();
for (i = 0; i < count; i++) {
curLayer = getLayer(compList.get(i));
if (layerStart == -1 && curLayer == layer) {
layerStart = i;
}
if (curLayer < layer) {
if (i == 0) {
// layer is greater than any current layer
// [ ASSERT(layer > highestLayer()) ]
layerStart = 0;
layerEnd = 0;
} else {
layerEnd = i;
}
break;
}
}
// layer requested is lower than any current layer
// [ ASSERT(layer < lowestLayer()) ]
// put it on the bottom of the stack
if (layerStart == -1 && layerEnd == -1)
return count;
// In the case of a single layer entry handle the degenerative cases
if (layerStart != -1 && layerEnd == -1)
layerEnd = count;
if (layerEnd != -1 && layerStart == -1)
layerStart = layerEnd;
// If we are adding to the bottom, return the last element
if (position == -1)
return layerEnd;
// Otherwise make sure the requested position falls in the
// proper range
if (position > -1 && layerStart + position <= layerEnd)
return layerStart + position;
// Otherwise return the end of the layer
return layerEnd;
}
/** {@collect.stats}
* Returns a string representation of this JLayeredPane. 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 JLayeredPane.
*/
protected String paramString() {
String optimizedDrawingPossibleString = (optimizedDrawingPossible ?
"true" : "false");
return super.paramString() +
",optimizedDrawingPossible=" + optimizedDrawingPossibleString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JLayeredPane.
* For layered panes, the AccessibleContext takes the form of an
* AccessibleJLayeredPane.
* A new AccessibleJLayeredPane instance is created if necessary.
*
* @return an AccessibleJLayeredPane that serves as the
* AccessibleContext of this JLayeredPane
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJLayeredPane();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JLayeredPane</code> class. It provides an implementation of the
* Java Accessibility API appropriate to layered 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 AccessibleJLayeredPane extends AccessibleJComponent {
/** {@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.LAYERED_PANE;
}
}
}
|
Java
|
/*
* Copyright (c) 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;
import java.awt.Component;
import java.awt.FocusTraversalPolicy;
/** {@collect.stats}
* A FocusTraversalPolicy which can optionally provide an algorithm for
* determining a JInternalFrame's initial Component. The initial Component is
* the first to receive focus when the JInternalFrame is first selected. By
* default, this is the same as the JInternalFrame's default Component to
* focus.
*
* @author David Mendenhall
*
* @since 1.4
*/
public abstract class InternalFrameFocusTraversalPolicy
extends FocusTraversalPolicy
{
/** {@collect.stats}
* Returns the Component that should receive the focus when a
* JInternalFrame is selected for the first time. Once the JInternalFrame
* has been selected by a call to <code>setSelected(true)</code>, the
* initial Component will not be used again. Instead, if the JInternalFrame
* loses and subsequently regains selection, or is made invisible or
* undisplayable and subsequently made visible and displayable, the
* JInternalFrame's most recently focused Component will become the focus
* owner. The default implementation of this method returns the
* JInternalFrame's default Component to focus.
*
* @param frame the JInternalFrame whose initial Component is to be
* returned
* @return the Component that should receive the focus when frame is
* selected for the first time, or null if no suitable Component
* can be found
* @see JInternalFrame#getMostRecentFocusOwner
* @throws IllegalArgumentException if window is null
*/
public Component getInitialComponent(JInternalFrame frame) {
return getDefaultComponent(frame);
}
}
|
Java
|
/*
* Copyright (c) 1997, 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;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JComponent;
import javax.swing.border.*;
/** {@collect.stats}
* Factory class for vending standard <code>Border</code> objects. Wherever
* possible, this factory will hand out references to shared
* <code>Border</code> instances.
* For further information and examples 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>.
*
* @author David Kloba
*/
public class BorderFactory
{
/** {@collect.stats} Don't let anyone instantiate this class */
private BorderFactory() {
}
//// LineBorder ///////////////////////////////////////////////////////////////
/** {@collect.stats}
* Creates a line border withe the specified color.
*
* @param color a <code>Color</code> to use for the line
* @return the <code>Border</code> object
*/
public static Border createLineBorder(Color color) {
return new LineBorder(color, 1);
}
/** {@collect.stats}
* Creates a line border with the specified color
* and width. The width applies to all four sides of the
* border. To specify widths individually for the top,
* bottom, left, and right, use
* {@link #createMatteBorder(int,int,int,int,Color)}.
*
* @param color a <code>Color</code> to use for the line
* @param thickness an integer specifying the width in pixels
* @return the <code>Border</code> object
*/
public static Border createLineBorder(Color color, int thickness) {
return new LineBorder(color, thickness);
}
// public static Border createLineBorder(Color color, int thickness,
// boolean drawRounded) {
// return new JLineBorder(color, thickness, drawRounded);
// }
//// BevelBorder /////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
static final Border sharedRaisedBevel = new BevelBorder(BevelBorder.RAISED);
static final Border sharedLoweredBevel = new BevelBorder(BevelBorder.LOWERED);
/** {@collect.stats}
* Creates a border with a raised beveled edge, using
* brighter shades of the component's current background color
* for highlighting, and darker shading for shadows.
* (In a raised border, highlights are on top and shadows
* are underneath.)
*
* @return the <code>Border</code> object
*/
public static Border createRaisedBevelBorder() {
return createSharedBevel(BevelBorder.RAISED);
}
/** {@collect.stats}
* Creates a border with a lowered beveled edge, using
* brighter shades of the component's current background color
* for highlighting, and darker shading for shadows.
* (In a lowered border, shadows are on top and highlights
* are underneath.)
*
* @return the <code>Border</code> object
*/
public static Border createLoweredBevelBorder() {
return createSharedBevel(BevelBorder.LOWERED);
}
/** {@collect.stats}
* Creates a beveled border of the specified type, using
* brighter shades of the component's current background color
* for highlighting, and darker shading for shadows.
* (In a lowered border, shadows are on top and highlights
* are underneath.)
*
* @param type an integer specifying either
* <code>BevelBorder.LOWERED</code> or
* <code>BevelBorder.RAISED</code>
* @return the <code>Border</code> object
*/
public static Border createBevelBorder(int type) {
return createSharedBevel(type);
}
/** {@collect.stats}
* Creates a beveled border of the specified type, using
* the specified highlighting and shadowing. The outer
* edge of the highlighted area uses a brighter shade of
* the highlight color. The inner edge of the shadow area
* uses a brighter shade of the shadow color.
*
* @param type an integer specifying either
* <code>BevelBorder.LOWERED</code> or
* <code>BevelBorder.RAISED</code>
* @param highlight a <code>Color</code> object for highlights
* @param shadow a <code>Color</code> object for shadows
* @return the <code>Border</code> object
*/
public static Border createBevelBorder(int type, Color highlight, Color shadow) {
return new BevelBorder(type, highlight, shadow);
}
/** {@collect.stats}
* Creates a beveled border of the specified type, using
* the specified colors for the inner and outer highlight
* and shadow areas.
* <p>
* Note: The shadow inner and outer colors are
* switched for a lowered bevel border.
*
* @param type an integer specifying either
* <code>BevelBorder.LOWERED</code> or
* <code>BevelBorder.RAISED</code>
* @param highlightOuter a <code>Color</code> object for the
* outer edge of the highlight area
* @param highlightInner a <code>Color</code> object for the
* inner edge of the highlight area
* @param shadowOuter a <code>Color</code> object for the
* outer edge of the shadow area
* @param shadowInner a <code>Color</code> object for the
* inner edge of the shadow area
* @return the <code>Border</code> object
*/
public static Border createBevelBorder(int type,
Color highlightOuter, Color highlightInner,
Color shadowOuter, Color shadowInner) {
return new BevelBorder(type, highlightOuter, highlightInner,
shadowOuter, shadowInner);
}
static Border createSharedBevel(int type) {
if(type == BevelBorder.RAISED) {
return sharedRaisedBevel;
} else if(type == BevelBorder.LOWERED) {
return sharedLoweredBevel;
}
return null;
}
//// EtchedBorder ///////////////////////////////////////////////////////////
static final Border sharedEtchedBorder = new EtchedBorder();
private static Border sharedRaisedEtchedBorder;
/** {@collect.stats}
* Creates a border with an "etched" look using
* the component's current background color for
* highlighting and shading.
*
* @return the <code>Border</code> object
*/
public static Border createEtchedBorder() {
return sharedEtchedBorder;
}
/** {@collect.stats}
* Creates a border with an "etched" look using
* the specified highlighting and shading colors.
*
* @param highlight a <code>Color</code> object for the border highlights
* @param shadow a <code>Color</code> object for the border shadows
* @return the <code>Border</code> object
*/
public static Border createEtchedBorder(Color highlight, Color shadow) {
return new EtchedBorder(highlight, shadow);
}
/** {@collect.stats}
* Creates a border with an "etched" look using
* the component's current background color for
* highlighting and shading.
*
* @param type one of <code>EtchedBorder.RAISED</code>, or
* <code>EtchedBorder.LOWERED</code>
* @return the <code>Border</code> object
* @exception IllegalArgumentException if type is not either
* <code>EtchedBorder.RAISED</code> or
* <code>EtchedBorder.LOWERED</code>
* @since 1.3
*/
public static Border createEtchedBorder(int type) {
switch (type) {
case EtchedBorder.RAISED:
if (sharedRaisedEtchedBorder == null) {
sharedRaisedEtchedBorder = new EtchedBorder
(EtchedBorder.RAISED);
}
return sharedRaisedEtchedBorder;
case EtchedBorder.LOWERED:
return sharedEtchedBorder;
default:
throw new IllegalArgumentException("type must be one of EtchedBorder.RAISED or EtchedBorder.LOWERED");
}
}
/** {@collect.stats}
* Creates a border with an "etched" look using
* the specified highlighting and shading colors.
*
* @param type one of <code>EtchedBorder.RAISED</code>, or
* <code>EtchedBorder.LOWERED</code>
* @param highlight a <code>Color</code> object for the border highlights
* @param shadow a <code>Color</code> object for the border shadows
* @return the <code>Border</code> object
* @since 1.3
*/
public static Border createEtchedBorder(int type, Color highlight,
Color shadow) {
return new EtchedBorder(type, highlight, shadow);
}
//// TitledBorder ////////////////////////////////////////////////////////////
/** {@collect.stats}
* Creates a new titled border with the specified title,
* the default border type (determined by the current look and feel),
* the default text position (sitting on the top line),
* the default justification (leading), and the default
* font and text color (determined by the current look and feel).
*
* @param title a <code>String</code> containing the text of the title
* @return the <code>TitledBorder</code> object
*/
public static TitledBorder createTitledBorder(String title) {
return new TitledBorder(title);
}
/** {@collect.stats}
* Creates a new titled border with an empty title,
* the specified border object,
* the default text position (sitting on the top line),
* the default justification (leading), and the default
* font and text color (determined by the current look and feel).
*
* @param border the <code>Border</code> object to add the title to; if
* <code>null</code> the <code>Border</code> is determined
* by the current look and feel.
* @return the <code>TitledBorder</code> object
*/
public static TitledBorder createTitledBorder(Border border) {
return new TitledBorder(border);
}
/** {@collect.stats}
* Adds a title to an existing border,
* with default positioning (sitting on the top line),
* default justification (leading) and the default
* font and text color (determined by the current look and feel).
*
* @param border the <code>Border</code> object to add the title to
* @param title a <code>String</code> containing the text of the title
* @return the <code>TitledBorder</code> object
*/
public static TitledBorder createTitledBorder(Border border,
String title) {
return new TitledBorder(border, title);
}
/** {@collect.stats}
* Adds a title to an existing border, with the specified
* positioning and using the default
* font and text color (determined by the current look and feel).
*
* @param border the <code>Border</code> object to add the title to
* @param title a <code>String</code> containing the text of the title
* @param titleJustification an integer specifying the justification
* of the title -- one of the following:
*<ul>
*<li><code>TitledBorder.LEFT</code>
*<li><code>TitledBorder.CENTER</code>
*<li><code>TitledBorder.RIGHT</code>
*<li><code>TitledBorder.LEADING</code>
*<li><code>TitledBorder.TRAILING</code>
*<li><code>TitledBorder.DEFAULT_JUSTIFICATION</code> (leading)
*</ul>
* @param titlePosition an integer specifying the vertical position of
* the text in relation to the border -- one of the following:
*<ul>
*<li><code> TitledBorder.ABOVE_TOP</code>
*<li><code>TitledBorder.TOP</code> (sitting on the top line)
*<li><code>TitledBorder.BELOW_TOP</code>
*<li><code>TitledBorder.ABOVE_BOTTOM</code>
*<li><code>TitledBorder.BOTTOM</code> (sitting on the bottom line)
*<li><code>TitledBorder.BELOW_BOTTOM</code>
*<li><code>TitledBorder.DEFAULT_POSITION</code> (top)
*</ul>
* @return the <code>TitledBorder</code> object
*/
public static TitledBorder createTitledBorder(Border border,
String title,
int titleJustification,
int titlePosition) {
return new TitledBorder(border, title, titleJustification,
titlePosition);
}
/** {@collect.stats}
* Adds a title to an existing border, with the specified
* positioning and font, and using the default text color
* (determined by the current look and feel).
*
* @param border the <code>Border</code> object to add the title to
* @param title a <code>String</code> containing the text of the title
* @param titleJustification an integer specifying the justification
* of the title -- one of the following:
*<ul>
*<li><code>TitledBorder.LEFT</code>
*<li><code>TitledBorder.CENTER</code>
*<li><code>TitledBorder.RIGHT</code>
*<li><code>TitledBorder.LEADING</code>
*<li><code>TitledBorder.TRAILING</code>
*<li><code>TitledBorder.DEFAULT_JUSTIFICATION</code> (leading)
*</ul>
* @param titlePosition an integer specifying the vertical position of
* the text in relation to the border -- one of the following:
*<ul>
*<li><code> TitledBorder.ABOVE_TOP</code>
*<li><code>TitledBorder.TOP</code> (sitting on the top line)
*<li><code>TitledBorder.BELOW_TOP</code>
*<li><code>TitledBorder.ABOVE_BOTTOM</code>
*<li><code>TitledBorder.BOTTOM</code> (sitting on the bottom line)
*<li><code>TitledBorder.BELOW_BOTTOM</code>
*<li><code>TitledBorder.DEFAULT_POSITION</code> (top)
*</ul>
* @param titleFont a Font object specifying the title font
* @return the TitledBorder object
*/
public static TitledBorder createTitledBorder(Border border,
String title,
int titleJustification,
int titlePosition,
Font titleFont) {
return new TitledBorder(border, title, titleJustification,
titlePosition, titleFont);
}
/** {@collect.stats}
* Adds a title to an existing border, with the specified
* positioning, font and color.
*
* @param border the <code>Border</code> object to add the title to
* @param title a <code>String</code> containing the text of the title
* @param titleJustification an integer specifying the justification
* of the title -- one of the following:
*<ul>
*<li><code>TitledBorder.LEFT</code>
*<li><code>TitledBorder.CENTER</code>
*<li><code>TitledBorder.RIGHT</code>
*<li><code>TitledBorder.LEADING</code>
*<li><code>TitledBorder.TRAILING</code>
*<li><code>TitledBorder.DEFAULT_JUSTIFICATION</code> (leading)
*</ul>
* @param titlePosition an integer specifying the vertical position of
* the text in relation to the border -- one of the following:
*<ul>
*<li><code> TitledBorder.ABOVE_TOP</code>
*<li><code>TitledBorder.TOP</code> (sitting on the top line)
*<li><code>TitledBorder.BELOW_TOP</code>
*<li><code>TitledBorder.ABOVE_BOTTOM</code>
*<li><code>TitledBorder.BOTTOM</code> (sitting on the bottom line)
*<li><code>TitledBorder.BELOW_BOTTOM</code>
*<li><code>TitledBorder.DEFAULT_POSITION</code> (top)
*</ul>
* @param titleFont a <code>Font</code> object specifying the title font
* @param titleColor a <code>Color</code> object specifying the title color
* @return the <code>TitledBorder</code> object
*/
public static TitledBorder createTitledBorder(Border border,
String title,
int titleJustification,
int titlePosition,
Font titleFont,
Color titleColor) {
return new TitledBorder(border, title, titleJustification,
titlePosition, titleFont, titleColor);
}
//// EmptyBorder ///////////////////////////////////////////////////////////
final static Border emptyBorder = new EmptyBorder(0, 0, 0, 0);
/** {@collect.stats}
* Creates an empty border that takes up no space. (The width
* of the top, bottom, left, and right sides are all zero.)
*
* @return the <code>Border</code> object
*/
public static Border createEmptyBorder() {
return emptyBorder;
}
/** {@collect.stats}
* Creates an empty border that takes up space but which does
* no drawing, specifying the width of the top, left, bottom, and
* right sides.
*
* @param top an integer specifying the width of the top,
* in pixels
* @param left an integer specifying the width of the left side,
* in pixels
* @param bottom an integer specifying the width of the bottom,
* in pixels
* @param right an integer specifying the width of the right side,
* in pixels
* @return the <code>Border</code> object
*/
public static Border createEmptyBorder(int top, int left,
int bottom, int right) {
return new EmptyBorder(top, left, bottom, right);
}
//// CompoundBorder ////////////////////////////////////////////////////////
/** {@collect.stats}
* Creates a compound border with a <code>null</code> inside edge and a
* <code>null</code> outside edge.
*
* @return the <code>CompoundBorder</code> object
*/
public static CompoundBorder createCompoundBorder() {
return new CompoundBorder();
}
/** {@collect.stats}
* Creates a compound border specifying the border objects to use
* for the outside and inside edges.
*
* @param outsideBorder a <code>Border</code> object for the outer
* edge of the compound border
* @param insideBorder a <code>Border</code> object for the inner
* edge of the compound border
* @return the <code>CompoundBorder</code> object
*/
public static CompoundBorder createCompoundBorder(Border outsideBorder,
Border insideBorder) {
return new CompoundBorder(outsideBorder, insideBorder);
}
//// MatteBorder ////////////////////////////////////////////////////////
/** {@collect.stats}
* Creates a matte-look border using a solid color. (The difference between
* this border and a line border is that you can specify the individual
* border dimensions.)
*
* @param top an integer specifying the width of the top,
* in pixels
* @param left an integer specifying the width of the left side,
* in pixels
* @param bottom an integer specifying the width of the right side,
* in pixels
* @param right an integer specifying the width of the bottom,
* in pixels
* @param color a <code>Color</code> to use for the border
* @return the <code>MatteBorder</code> object
*/
public static MatteBorder createMatteBorder(int top, int left, int bottom, int right,
Color color) {
return new MatteBorder(top, left, bottom, right, color);
}
/** {@collect.stats}
* Creates a matte-look border that consists of multiple tiles of a
* specified icon. Multiple copies of the icon are placed side-by-side
* to fill up the border area.
* <p>
* Note:<br>
* If the icon doesn't load, the border area is painted gray.
*
* @param top an integer specifying the width of the top,
* in pixels
* @param left an integer specifying the width of the left side,
* in pixels
* @param bottom an integer specifying the width of the right side,
* in pixels
* @param right an integer specifying the width of the bottom,
* in pixels
* @param tileIcon the <code>Icon</code> object used for the border tiles
* @return the <code>MatteBorder</code> object
*/
public static MatteBorder createMatteBorder(int top, int left, int bottom, int right,
Icon tileIcon) {
return new MatteBorder(top, left, bottom, right, tileIcon);
}
}
|
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;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Insets;
import java.awt.LayoutManager2;
import java.awt.Rectangle;
import java.util.*;
/** {@collect.stats}
* A <code>SpringLayout</code> lays out the children of its associated container
* according to a set of constraints.
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/layout/spring.html">How to Use SpringLayout</a>
* in <em>The Java Tutorial</em> for examples of using
* <code>SpringLayout</code>.
*
* <p>
* Each constraint,
* represented by a <code>Spring</code> object,
* controls the vertical or horizontal distance
* between two component edges.
* The edges can belong to
* any child of the container,
* or to the container itself.
* For example,
* the allowable width of a component
* can be expressed using a constraint
* that controls the distance between the west (left) and east (right)
* edges of the component.
* The allowable <em>y</em> coordinates for a component
* can be expressed by constraining the distance between
* the north (top) edge of the component
* and the north edge of its container.
*
* <P>
* Every child of a <code>SpringLayout</code>-controlled container,
* as well as the container itself,
* has exactly one set of constraints
* associated with it.
* These constraints are represented by
* a <code>SpringLayout.Constraints</code> object.
* By default,
* <code>SpringLayout</code> creates constraints
* that make their associated component
* have the minimum, preferred, and maximum sizes
* returned by the component's
* {@link java.awt.Component#getMinimumSize},
* {@link java.awt.Component#getPreferredSize}, and
* {@link java.awt.Component#getMaximumSize}
* methods. The <em>x</em> and <em>y</em> positions are initially not
* constrained, so that until you constrain them the <code>Component</code>
* will be positioned at 0,0 relative to the <code>Insets</code> of the
* parent <code>Container</code>.
*
* <p>
* You can change
* a component's constraints in several ways.
* You can
* use one of the
* {@link #putConstraint putConstraint}
* methods
* to establish a spring
* linking the edges of two components within the same container.
* Or you can get the appropriate <code>SpringLayout.Constraints</code>
* object using
* {@link #getConstraints getConstraints}
* and then modify one or more of its springs.
* Or you can get the spring for a particular edge of a component
* using {@link #getConstraint getConstraint},
* and modify it.
* You can also associate
* your own <code>SpringLayout.Constraints</code> object
* with a component by specifying the constraints object
* when you add the component to its container
* (using
* {@link Container#add(Component, Object)}).
*
* <p>
* The <code>Spring</code> object representing each constraint
* has a minimum, preferred, maximum, and current value.
* The current value of the spring
* is somewhere between the minimum and maximum values,
* according to the formula given in the
* {@link Spring#sum} method description.
* When the minimum, preferred, and maximum values are the same,
* the current value is always equal to them;
* this inflexible spring is called a <em>strut</em>.
* You can create struts using the factory method
* {@link Spring#constant(int)}.
* The <code>Spring</code> class also provides factory methods
* for creating other kinds of springs,
* including springs that depend on other springs.
*
* <p>
* In a <code>SpringLayout</code>, the position of each edge is dependent on
* the position of just one other edge. If a constraint is subsequently added
* to create a new binding for an edge, the previous binding is discarded
* and the edge remains dependent on a single edge.
* Springs should only be attached
* between edges of the container and its immediate children; the behavior
* of the <code>SpringLayout</code> when presented with constraints linking
* the edges of components from different containers (either internal or
* external) is undefined.
*
* <h3>
* SpringLayout vs. Other Layout Managers
* </h3>
*
* <blockquote>
* <hr>
* <strong>Note:</strong>
* Unlike many layout managers,
* <code>SpringLayout</code> doesn't automatically set the location of
* the components it manages.
* If you hand-code a GUI that uses <code>SpringLayout</code>,
* remember to initialize component locations by constraining the west/east
* and north/south locations.
* <p>
* Depending on the constraints you use,
* you may also need to set the size of the container explicitly.
* <hr>
* </blockquote>
*
* <p>
* Despite the simplicity of <code>SpringLayout</code>,
* it can emulate the behavior of most other layout managers.
* For some features,
* such as the line breaking provided by <code>FlowLayout</code>,
* you'll need to
* create a special-purpose subclass of the <code>Spring</code> class.
*
* <p>
* <code>SpringLayout</code> also provides a way to solve
* many of the difficult layout
* problems that cannot be solved by nesting combinations
* of <code>Box</code>es. That said, <code>SpringLayout</code> honors the
* <code>LayoutManager2</code> contract correctly and so can be nested with
* other layout managers -- a technique that can be preferable to
* creating the constraints implied by the other layout managers.
* <p>
* The asymptotic complexity of the layout operation of a <code>SpringLayout</code>
* is linear in the number of constraints (and/or components).
* <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 Spring
* @see SpringLayout.Constraints
*
* @author Philip Milne
* @author Scott Violet
* @author Joe Winchester
* @since 1.4
*/
public class SpringLayout implements LayoutManager2 {
private Map componentConstraints = new HashMap();
private Spring cyclicReference = Spring.constant(Spring.UNSET);
private Set cyclicSprings;
private Set acyclicSprings;
/** {@collect.stats}
* Specifies the top edge of a component's bounding rectangle.
*/
public static final String NORTH = "North";
/** {@collect.stats}
* Specifies the bottom edge of a component's bounding rectangle.
*/
public static final String SOUTH = "South";
/** {@collect.stats}
* Specifies the right edge of a component's bounding rectangle.
*/
public static final String EAST = "East";
/** {@collect.stats}
* Specifies the left edge of a component's bounding rectangle.
*/
public static final String WEST = "West";
/** {@collect.stats}
* Specifies the horizontal center of a component's bounding rectangle.
*
* @since 1.6
*/
public static final String HORIZONTAL_CENTER = "HorizontalCenter";
/** {@collect.stats}
* Specifies the vertical center of a component's bounding rectangle.
*
* @since 1.6
*/
public static final String VERTICAL_CENTER = "VerticalCenter";
/** {@collect.stats}
* Specifies the baseline of a component.
*
* @since 1.6
*/
public static final String BASELINE = "Baseline";
/** {@collect.stats}
* Specifies the width of a component's bounding rectangle.
*
* @since 1.6
*/
public static final String WIDTH = "Width";
/** {@collect.stats}
* Specifies the height of a component's bounding rectangle.
*
* @since 1.6
*/
public static final String HEIGHT = "Height";
private static String[] ALL_HORIZONTAL = {WEST, WIDTH, EAST, HORIZONTAL_CENTER};
private static String[] ALL_VERTICAL = {NORTH, HEIGHT, SOUTH, VERTICAL_CENTER, BASELINE};
/** {@collect.stats}
* A <code>Constraints</code> object holds the
* constraints that govern the way a component's size and position
* change in a container controlled by a <code>SpringLayout</code>.
* A <code>Constraints</code> object is
* like a <code>Rectangle</code>, in that it
* has <code>x</code>, <code>y</code>,
* <code>width</code>, and <code>height</code> properties.
* In the <code>Constraints</code> object, however,
* these properties have
* <code>Spring</code> values instead of integers.
* In addition,
* a <code>Constraints</code> object
* can be manipulated as four edges
* -- north, south, east, and west --
* using the <code>constraint</code> property.
*
* <p>
* The following formulas are always true
* for a <code>Constraints</code> object (here WEST and <code>x</code> are synonyms, as are and NORTH and <code>y</code>):
*
* <pre>
* EAST = WEST + WIDTH
* SOUTH = NORTH + HEIGHT
* HORIZONTAL_CENTER = WEST + WIDTH/2
* VERTICAL_CENTER = NORTH + HEIGHT/2
* ABSOLUTE_BASELINE = NORTH + RELATIVE_BASELINE*
* </pre>
* <p>
* For example, if you have specified the WIDTH and WEST (X) location
* the EAST is calculated as WEST + WIDTH. If you instead specified
* the WIDTH and EAST locations the WEST (X) location is then calculated
* as EAST - WIDTH.
* <p>
* [RELATIVE_BASELINE is a private constraint that is set automatically when
* the SpringLayout.Constraints(Component) constuctor is called or when
* a constraints object is registered with a SpringLayout object.]
* <p>
* <b>Note</b>: In this document,
* operators represent methods
* in the <code>Spring</code> class.
* For example, "a + b" is equal to
* <code>Spring.sum(a, b)</code>,
* and "a - b" is equal to
* <code>Spring.sum(a, Spring.minus(b))</code>.
* See the
* {@link Spring <code>Spring</code> API documentation}
* for further details
* of spring arithmetic.
*
* <p>
*
* Because a <code>Constraints</code> object's properties --
* representing its edges, size, and location -- can all be set
* independently and yet are interrelated,
* a <code>Constraints</code> object can become <em>over-constrained</em>.
* For example, if the <code>WEST</code>, <code>WIDTH</code> and
* <code>EAST</code> edges are all set, steps must be taken to ensure that
* the first of the formulas above holds. To do this, the
* <code>Constraints</code>
* object throws away the <em>least recently set</em>
* constraint so as to make the formulas hold.
* @since 1.4
*/
public static class Constraints {
private Spring x;
private Spring y;
private Spring width;
private Spring height;
private Spring east;
private Spring south;
private Spring horizontalCenter;
private Spring verticalCenter;
private Spring baseline;
private List<String> horizontalHistory = new ArrayList<String>(2);
private List<String> verticalHistory = new ArrayList<String>(2);
// Used for baseline calculations
private Component c;
/** {@collect.stats}
* Creates an empty <code>Constraints</code> object.
*/
public Constraints() {
}
/** {@collect.stats}
* Creates a <code>Constraints</code> object with the
* specified values for its
* <code>x</code> and <code>y</code> properties.
* The <code>height</code> and <code>width</code> springs
* have <code>null</code> values.
*
* @param x the spring controlling the component's <em>x</em> value
* @param y the spring controlling the component's <em>y</em> value
*/
public Constraints(Spring x, Spring y) {
setX(x);
setY(y);
}
/** {@collect.stats}
* Creates a <code>Constraints</code> object with the
* specified values for its
* <code>x</code>, <code>y</code>, <code>width</code>,
* and <code>height</code> properties.
* Note: If the <code>SpringLayout</code> class
* encounters <code>null</code> values in the
* <code>Constraints</code> object of a given component,
* it replaces them with suitable defaults.
*
* @param x the spring value for the <code>x</code> property
* @param y the spring value for the <code>y</code> property
* @param width the spring value for the <code>width</code> property
* @param height the spring value for the <code>height</code> property
*/
public Constraints(Spring x, Spring y, Spring width, Spring height) {
setX(x);
setY(y);
setWidth(width);
setHeight(height);
}
/** {@collect.stats}
* Creates a <code>Constraints</code> object with
* suitable <code>x</code>, <code>y</code>, <code>width</code> and
* <code>height</code> springs for component, <code>c</code>.
* The <code>x</code> and <code>y</code> springs are constant
* springs initialised with the component's location at
* the time this method is called. The <code>width</code> and
* <code>height</code> springs are special springs, created by
* the <code>Spring.width()</code> and <code>Spring.height()</code>
* methods, which track the size characteristics of the component
* when they change.
*
* @param c the component whose characteristics will be reflected by this Constraints object
* @throws NullPointerException if <code>c</code> is null.
* @since 1.5
*/
public Constraints(Component c) {
this.c = c;
setX(Spring.constant(c.getX()));
setY(Spring.constant(c.getY()));
setWidth(Spring.width(c));
setHeight(Spring.height(c));
}
private void pushConstraint(String name, Spring value, boolean horizontal) {
boolean valid = true;
List<String> history = horizontal ? horizontalHistory :
verticalHistory;
if (history.contains(name)) {
history.remove(name);
valid = false;
} else if (history.size() == 2 && value != null) {
history.remove(0);
valid = false;
}
if (value != null) {
history.add(name);
}
if (!valid) {
String[] all = horizontal ? ALL_HORIZONTAL : ALL_VERTICAL;
for (int i = 0; i < all.length; i++) {
String s = all[i];
if (!history.contains(s)) {
setConstraint(s, null);
}
}
}
}
private Spring sum(Spring s1, Spring s2) {
return (s1 == null || s2 == null) ? null : Spring.sum(s1, s2);
}
private Spring difference(Spring s1, Spring s2) {
return (s1 == null || s2 == null) ? null : Spring.difference(s1, s2);
}
private Spring scale(Spring s, float factor) {
return (s == null) ? null : Spring.scale(s, factor);
}
private int getBaselineFromHeight(int height) {
if (height < 0) {
// Bad Scott, Bad Scott!
return -c.getBaseline(c.getPreferredSize().width,
-height);
}
return c.getBaseline(c.getPreferredSize().width, height);
}
private int getHeightFromBaseLine(int baseline) {
Dimension prefSize = c.getPreferredSize();
int prefHeight = prefSize.height;
int prefBaseline = c.getBaseline(prefSize.width, prefHeight);
if (prefBaseline == baseline) {
// If prefBaseline < 0, then no baseline, assume preferred
// height.
// If prefBaseline == baseline, then specified baseline
// matches preferred baseline, return preferred height
return prefHeight;
}
// Valid baseline
switch(c.getBaselineResizeBehavior()) {
case CONSTANT_DESCENT:
return prefHeight + (baseline - prefBaseline);
case CENTER_OFFSET:
return prefHeight + 2 * (baseline - prefBaseline);
case CONSTANT_ASCENT:
// Component baseline and specified baseline will NEVER
// match, fall through to default
default: // OTHER
// No way to map from baseline to height.
}
return Integer.MIN_VALUE;
}
private Spring heightToRelativeBaseline(Spring s) {
return new Spring.SpringMap(s) {
protected int map(int i) {
return getBaselineFromHeight(i);
}
protected int inv(int i) {
return getHeightFromBaseLine(i);
}
};
}
private Spring relativeBaselineToHeight(Spring s) {
return new Spring.SpringMap(s) {
protected int map(int i) {
return getHeightFromBaseLine(i);
}
protected int inv(int i) {
return getBaselineFromHeight(i);
}
};
}
private boolean defined(List history, String s1, String s2) {
return history.contains(s1) && history.contains(s2);
}
/** {@collect.stats}
* Sets the <code>x</code> property,
* which controls the <code>x</code> value
* of a component's location.
*
* @param x the spring controlling the <code>x</code> value
* of a component's location
*
* @see #getX
* @see SpringLayout.Constraints
*/
public void setX(Spring x) {
this.x = x;
pushConstraint(WEST, x, true);
}
/** {@collect.stats}
* Returns the value of the <code>x</code> property.
*
* @return the spring controlling the <code>x</code> value
* of a component's location
*
* @see #setX
* @see SpringLayout.Constraints
*/
public Spring getX() {
if (x == null) {
if (defined(horizontalHistory, EAST, WIDTH)) {
x = difference(east, width);
} else if (defined(horizontalHistory, HORIZONTAL_CENTER, WIDTH)) {
x = difference(horizontalCenter, scale(width, 0.5f));
} else if (defined(horizontalHistory, HORIZONTAL_CENTER, EAST)) {
x = difference(scale(horizontalCenter, 2f), east);
}
}
return x;
}
/** {@collect.stats}
* Sets the <code>y</code> property,
* which controls the <code>y</code> value
* of a component's location.
*
* @param y the spring controlling the <code>y</code> value
* of a component's location
*
* @see #getY
* @see SpringLayout.Constraints
*/
public void setY(Spring y) {
this.y = y;
pushConstraint(NORTH, y, false);
}
/** {@collect.stats}
* Returns the value of the <code>y</code> property.
*
* @return the spring controlling the <code>y</code> value
* of a component's location
*
* @see #setY
* @see SpringLayout.Constraints
*/
public Spring getY() {
if (y == null) {
if (defined(verticalHistory, SOUTH, HEIGHT)) {
y = difference(south, height);
} else if (defined(verticalHistory, VERTICAL_CENTER, HEIGHT)) {
y = difference(verticalCenter, scale(height, 0.5f));
} else if (defined(verticalHistory, VERTICAL_CENTER, SOUTH)) {
y = difference(scale(verticalCenter, 2f), south);
} else if (defined(verticalHistory, BASELINE, HEIGHT)) {
y = difference(baseline, heightToRelativeBaseline(height));
} else if (defined(verticalHistory, BASELINE, SOUTH)) {
y = scale(difference(baseline, heightToRelativeBaseline(south)), 2f);
/*
} else if (defined(verticalHistory, BASELINE, VERTICAL_CENTER)) {
y = scale(difference(baseline, heightToRelativeBaseline(scale(verticalCenter, 2))), 1f/(1-2*0.5f));
*/
}
}
return y;
}
/** {@collect.stats}
* Sets the <code>width</code> property,
* which controls the width of a component.
*
* @param width the spring controlling the width of this
* <code>Constraints</code> object
*
* @see #getWidth
* @see SpringLayout.Constraints
*/
public void setWidth(Spring width) {
this.width = width;
pushConstraint(WIDTH, width, true);
}
/** {@collect.stats}
* Returns the value of the <code>width</code> property.
*
* @return the spring controlling the width of a component
*
* @see #setWidth
* @see SpringLayout.Constraints
*/
public Spring getWidth() {
if (width == null) {
if (horizontalHistory.contains(EAST)) {
width = difference(east, getX());
} else if (horizontalHistory.contains(HORIZONTAL_CENTER)) {
width = scale(difference(horizontalCenter, getX()), 2f);
}
}
return width;
}
/** {@collect.stats}
* Sets the <code>height</code> property,
* which controls the height of a component.
*
* @param height the spring controlling the height of this <code>Constraints</code>
* object
*
* @see #getHeight
* @see SpringLayout.Constraints
*/
public void setHeight(Spring height) {
this.height = height;
pushConstraint(HEIGHT, height, false);
}
/** {@collect.stats}
* Returns the value of the <code>height</code> property.
*
* @return the spring controlling the height of a component
*
* @see #setHeight
* @see SpringLayout.Constraints
*/
public Spring getHeight() {
if (height == null) {
if (verticalHistory.contains(SOUTH)) {
height = difference(south, getY());
} else if (verticalHistory.contains(VERTICAL_CENTER)) {
height = scale(difference(verticalCenter, getY()), 2f);
} else if (verticalHistory.contains(BASELINE)) {
height = relativeBaselineToHeight(difference(baseline, getY()));
}
}
return height;
}
private void setEast(Spring east) {
this.east = east;
pushConstraint(EAST, east, true);
}
private Spring getEast() {
if (east == null) {
east = sum(getX(), getWidth());
}
return east;
}
private void setSouth(Spring south) {
this.south = south;
pushConstraint(SOUTH, south, false);
}
private Spring getSouth() {
if (south == null) {
south = sum(getY(), getHeight());
}
return south;
}
private Spring getHorizontalCenter() {
if (horizontalCenter == null) {
horizontalCenter = sum(getX(), scale(getWidth(), 0.5f));
}
return horizontalCenter;
}
private void setHorizontalCenter(Spring horizontalCenter) {
this.horizontalCenter = horizontalCenter;
pushConstraint(HORIZONTAL_CENTER, horizontalCenter, true);
}
private Spring getVerticalCenter() {
if (verticalCenter == null) {
verticalCenter = sum(getY(), scale(getHeight(), 0.5f));
}
return verticalCenter;
}
private void setVerticalCenter(Spring verticalCenter) {
this.verticalCenter = verticalCenter;
pushConstraint(VERTICAL_CENTER, verticalCenter, false);
}
private Spring getBaseline() {
if (baseline == null) {
baseline = sum(getY(), heightToRelativeBaseline(getHeight()));
}
return baseline;
}
private void setBaseline(Spring baseline) {
this.baseline = baseline;
pushConstraint(BASELINE, baseline, false);
}
/** {@collect.stats}
* Sets the spring controlling the specified edge.
* The edge must have one of the following values:
* <code>SpringLayout.NORTH</code>,
* <code>SpringLayout.SOUTH</code>,
* <code>SpringLayout.EAST</code>,
* <code>SpringLayout.WEST</code>,
* <code>SpringLayout.HORIZONTAL_CENTER</code>,
* <code>SpringLayout.VERTICAL_CENTER</code>,
* <code>SpringLayout.BASELINE</code>,
* <code>SpringLayout.WIDTH</code> or
* <code>SpringLayout.HEIGHT</code>.
* For any other <code>String</code> value passed as the edge,
* no action is taken. For a <code>null</code> edge, a
* <code>NullPointerException</code> is thrown.
*
* @param edgeName the edge to be set
* @param s the spring controlling the specified edge
*
* @throws NullPointerException if <code>edgeName</code> is <code>null</code>
*
* @see #getConstraint
* @see #NORTH
* @see #SOUTH
* @see #EAST
* @see #WEST
* @see #HORIZONTAL_CENTER
* @see #VERTICAL_CENTER
* @see #BASELINE
* @see #WIDTH
* @see #HEIGHT
* @see SpringLayout.Constraints
*/
public void setConstraint(String edgeName, Spring s) {
edgeName = edgeName.intern();
if (edgeName == WEST) {
setX(s);
} else if (edgeName == NORTH) {
setY(s);
} else if (edgeName == EAST) {
setEast(s);
} else if (edgeName == SOUTH) {
setSouth(s);
} else if (edgeName == HORIZONTAL_CENTER) {
setHorizontalCenter(s);
} else if (edgeName == WIDTH) {
setWidth(s);
} else if (edgeName == HEIGHT) {
setHeight(s);
} else if (edgeName == VERTICAL_CENTER) {
setVerticalCenter(s);
} else if (edgeName == BASELINE) {
setBaseline(s);
}
}
/** {@collect.stats}
* Returns the value of the specified edge, which may be
* a derived value, or even <code>null</code>.
* The edge must have one of the following values:
* <code>SpringLayout.NORTH</code>,
* <code>SpringLayout.SOUTH</code>,
* <code>SpringLayout.EAST</code>,
* <code>SpringLayout.WEST</code>,
* <code>SpringLayout.HORIZONTAL_CENTER</code>,
* <code>SpringLayout.VERTICAL_CENTER</code>,
* <code>SpringLayout.BASELINE</code>,
* <code>SpringLayout.WIDTH</code> or
* <code>SpringLayout.HEIGHT</code>.
* For any other <code>String</code> value passed as the edge,
* <code>null</code> will be returned. Throws
* <code>NullPointerException</code> for a <code>null</code> edge.
*
* @param edgeName the edge whose value
* is to be returned
*
* @return the spring controlling the specified edge, may be <code>null</code>
*
* @throws NullPointerException if <code>edgeName</code> is <code>null</code>
*
* @see #setConstraint
* @see #NORTH
* @see #SOUTH
* @see #EAST
* @see #WEST
* @see #HORIZONTAL_CENTER
* @see #VERTICAL_CENTER
* @see #BASELINE
* @see #WIDTH
* @see #HEIGHT
* @see SpringLayout.Constraints
*/
public Spring getConstraint(String edgeName) {
edgeName = edgeName.intern();
return (edgeName == WEST) ? getX() :
(edgeName == NORTH) ? getY() :
(edgeName == EAST) ? getEast() :
(edgeName == SOUTH) ? getSouth() :
(edgeName == WIDTH) ? getWidth() :
(edgeName == HEIGHT) ? getHeight() :
(edgeName == HORIZONTAL_CENTER) ? getHorizontalCenter() :
(edgeName == VERTICAL_CENTER) ? getVerticalCenter() :
(edgeName == BASELINE) ? getBaseline() :
null;
}
/*pp*/ void reset() {
Spring[] allSprings = {x, y, width, height, east, south,
horizontalCenter, verticalCenter, baseline};
for (int i = 0; i < allSprings.length; i++) {
Spring s = allSprings[i];
if (s != null) {
s.setValue(Spring.UNSET);
}
}
}
}
private static class SpringProxy extends Spring {
private String edgeName;
private Component c;
private SpringLayout l;
public SpringProxy(String edgeName, Component c, SpringLayout l) {
this.edgeName = edgeName;
this.c = c;
this.l = l;
}
private Spring getConstraint() {
return l.getConstraints(c).getConstraint(edgeName);
}
public int getMinimumValue() {
return getConstraint().getMinimumValue();
}
public int getPreferredValue() {
return getConstraint().getPreferredValue();
}
public int getMaximumValue() {
return getConstraint().getMaximumValue();
}
public int getValue() {
return getConstraint().getValue();
}
public void setValue(int size) {
getConstraint().setValue(size);
}
/*pp*/ boolean isCyclic(SpringLayout l) {
return l.isCyclic(getConstraint());
}
public String toString() {
return "SpringProxy for " + edgeName + " edge of " + c.getName() + ".";
}
}
/** {@collect.stats}
* Constructs a new <code>SpringLayout</code>.
*/
public SpringLayout() {}
private void resetCyclicStatuses() {
cyclicSprings = new HashSet();
acyclicSprings = new HashSet();
}
private void setParent(Container p) {
resetCyclicStatuses();
Constraints pc = getConstraints(p);
pc.setX(Spring.constant(0));
pc.setY(Spring.constant(0));
// The applyDefaults() method automatically adds width and
// height springs that delegate their calculations to the
// getMinimumSize(), getPreferredSize() and getMaximumSize()
// methods of the relevant component. In the case of the
// parent this will cause an infinite loop since these
// methods, in turn, delegate their calculations to the
// layout manager. Check for this case and replace the
// the springs that would cause this problem with a
// constant springs that supply default values.
Spring width = pc.getWidth();
if (width instanceof Spring.WidthSpring && ((Spring.WidthSpring)width).c == p) {
pc.setWidth(Spring.constant(0, 0, Integer.MAX_VALUE));
}
Spring height = pc.getHeight();
if (height instanceof Spring.HeightSpring && ((Spring.HeightSpring)height).c == p) {
pc.setHeight(Spring.constant(0, 0, Integer.MAX_VALUE));
}
}
/*pp*/ boolean isCyclic(Spring s) {
if (s == null) {
return false;
}
if (cyclicSprings.contains(s)) {
return true;
}
if (acyclicSprings.contains(s)) {
return false;
}
cyclicSprings.add(s);
boolean result = s.isCyclic(this);
if (!result) {
acyclicSprings.add(s);
cyclicSprings.remove(s);
}
else {
System.err.println(s + " is cyclic. ");
}
return result;
}
private Spring abandonCycles(Spring s) {
return isCyclic(s) ? cyclicReference : s;
}
// LayoutManager methods.
/** {@collect.stats}
* Has no effect,
* since this layout manager does not
* use a per-component string.
*/
public void addLayoutComponent(String name, Component c) {}
/** {@collect.stats}
* Removes the constraints associated with the specified component.
*
* @param c the component being removed from the container
*/
public void removeLayoutComponent(Component c) {
componentConstraints.remove(c);
}
private static Dimension addInsets(int width, int height, Container p) {
Insets i = p.getInsets();
return new Dimension(width + i.left + i.right, height + i.top + i.bottom);
}
public Dimension minimumLayoutSize(Container parent) {
setParent(parent);
Constraints pc = getConstraints(parent);
return addInsets(abandonCycles(pc.getWidth()).getMinimumValue(),
abandonCycles(pc.getHeight()).getMinimumValue(),
parent);
}
public Dimension preferredLayoutSize(Container parent) {
setParent(parent);
Constraints pc = getConstraints(parent);
return addInsets(abandonCycles(pc.getWidth()).getPreferredValue(),
abandonCycles(pc.getHeight()).getPreferredValue(),
parent);
}
// LayoutManager2 methods.
public Dimension maximumLayoutSize(Container parent) {
setParent(parent);
Constraints pc = getConstraints(parent);
return addInsets(abandonCycles(pc.getWidth()).getMaximumValue(),
abandonCycles(pc.getHeight()).getMaximumValue(),
parent);
}
/** {@collect.stats}
* If <code>constraints</code> is an instance of
* <code>SpringLayout.Constraints</code>,
* associates the constraints with the specified component.
* <p>
* @param component the component being added
* @param constraints the component's constraints
*
* @see SpringLayout.Constraints
*/
public void addLayoutComponent(Component component, Object constraints) {
if (constraints instanceof Constraints) {
putConstraints(component, (Constraints)constraints);
}
}
/** {@collect.stats}
* Returns 0.5f (centered).
*/
public float getLayoutAlignmentX(Container p) {
return 0.5f;
}
/** {@collect.stats}
* Returns 0.5f (centered).
*/
public float getLayoutAlignmentY(Container p) {
return 0.5f;
}
public void invalidateLayout(Container p) {}
// End of LayoutManger2 methods
/** {@collect.stats}
* Links edge <code>e1</code> of component <code>c1</code> to
* edge <code>e2</code> of component <code>c2</code>,
* with a fixed distance between the edges. This
* constraint will cause the assignment
* <pre>
* value(e1, c1) = value(e2, c2) + pad</pre>
* to take place during all subsequent layout operations.
* <p>
* @param e1 the edge of the dependent
* @param c1 the component of the dependent
* @param pad the fixed distance between dependent and anchor
* @param e2 the edge of the anchor
* @param c2 the component of the anchor
*
* @see #putConstraint(String, Component, Spring, String, Component)
*/
public void putConstraint(String e1, Component c1, int pad, String e2, Component c2) {
putConstraint(e1, c1, Spring.constant(pad), e2, c2);
}
/** {@collect.stats}
* Links edge <code>e1</code> of component <code>c1</code> to
* edge <code>e2</code> of component <code>c2</code>. As edge
* <code>(e2, c2)</code> changes value, edge <code>(e1, c1)</code> will
* be calculated by taking the (spring) sum of <code>(e2, c2)</code>
* and <code>s</code>.
* Each edge must have one of the following values:
* <code>SpringLayout.NORTH</code>,
* <code>SpringLayout.SOUTH</code>,
* <code>SpringLayout.EAST</code>,
* <code>SpringLayout.WEST</code>,
* <code>SpringLayout.VERTICAL_CENTER</code>,
* <code>SpringLayout.HORIZONTAL_CENTER</code> or
* <code>SpringLayout.BASELINE</code>.
* <p>
* @param e1 the edge of the dependent
* @param c1 the component of the dependent
* @param s the spring linking dependent and anchor
* @param e2 the edge of the anchor
* @param c2 the component of the anchor
*
* @see #putConstraint(String, Component, int, String, Component)
* @see #NORTH
* @see #SOUTH
* @see #EAST
* @see #WEST
* @see #VERTICAL_CENTER
* @see #HORIZONTAL_CENTER
* @see #BASELINE
*/
public void putConstraint(String e1, Component c1, Spring s, String e2, Component c2) {
putConstraint(e1, c1, Spring.sum(s, getConstraint(e2, c2)));
}
private void putConstraint(String e, Component c, Spring s) {
if (s != null) {
getConstraints(c).setConstraint(e, s);
}
}
private Constraints applyDefaults(Component c, Constraints constraints) {
if (constraints == null) {
constraints = new Constraints();
}
if (constraints.c == null) {
constraints.c = c;
}
if (constraints.horizontalHistory.size() < 2) {
applyDefaults(constraints, WEST, Spring.constant(0), WIDTH,
Spring.width(c), constraints.horizontalHistory);
}
if (constraints.verticalHistory.size() < 2) {
applyDefaults(constraints, NORTH, Spring.constant(0), HEIGHT,
Spring.height(c), constraints.verticalHistory);
}
return constraints;
}
private void applyDefaults(Constraints constraints, String name1,
Spring spring1, String name2, Spring spring2,
List<String> history) {
if (history.size() == 0) {
constraints.setConstraint(name1, spring1);
constraints.setConstraint(name2, spring2);
} else {
// At this point there must be exactly one constraint defined already.
// Check width/height first.
if (constraints.getConstraint(name2) == null) {
constraints.setConstraint(name2, spring2);
} else {
// If width/height is already defined, install a default for x/y.
constraints.setConstraint(name1, spring1);
}
// Either way, leave the user's constraint topmost on the stack.
Collections.rotate(history, 1);
}
}
private void putConstraints(Component component, Constraints constraints) {
componentConstraints.put(component, applyDefaults(component, constraints));
}
/** {@collect.stats}
* Returns the constraints for the specified component.
* Note that,
* unlike the <code>GridBagLayout</code>
* <code>getConstraints</code> method,
* this method does not clone constraints.
* If no constraints
* have been associated with this component,
* this method
* returns a default constraints object positioned at
* 0,0 relative to the parent's Insets and its width/height
* constrained to the minimum, maximum, and preferred sizes of the
* component. The size characteristics
* are not frozen at the time this method is called;
* instead this method returns a constraints object
* whose characteristics track the characteristics
* of the component as they change.
*
* @param c the component whose constraints will be returned
*
* @return the constraints for the specified component
*/
public Constraints getConstraints(Component c) {
Constraints result = (Constraints)componentConstraints.get(c);
if (result == null) {
if (c instanceof javax.swing.JComponent) {
Object cp = ((javax.swing.JComponent)c).getClientProperty(SpringLayout.class);
if (cp instanceof Constraints) {
return applyDefaults(c, (Constraints)cp);
}
}
result = new Constraints();
putConstraints(c, result);
}
return result;
}
/** {@collect.stats}
* Returns the spring controlling the distance between
* the specified edge of
* the component and the top or left edge of its parent. This
* method, instead of returning the current binding for the
* edge, returns a proxy that tracks the characteristics
* of the edge even if the edge is subsequently rebound.
* Proxies are intended to be used in builder envonments
* where it is useful to allow the user to define the
* constraints for a layout in any order. Proxies do, however,
* provide the means to create cyclic dependencies amongst
* the constraints of a layout. Such cycles are detected
* internally by <code>SpringLayout</code> so that
* the layout operation always terminates.
*
* @param edgeName must be one of
* <code>SpringLayout.NORTH</code>,
* <code>SpringLayout.SOUTH</code>,
* <code>SpringLayout.EAST</code>,
* <code>SpringLayout.WEST</code>,
* <code>SpringLayout.VERTICAL_CENTER</code>,
* <code>SpringLayout.HORIZONTAL_CENTER</code> or
* <code>SpringLayout.BASELINE</code>
* @param c the component whose edge spring is desired
*
* @return a proxy for the spring controlling the distance between the
* specified edge and the top or left edge of its parent
*
* @see #NORTH
* @see #SOUTH
* @see #EAST
* @see #WEST
* @see #VERTICAL_CENTER
* @see #HORIZONTAL_CENTER
* @see #BASELINE
*/
public Spring getConstraint(String edgeName, Component c) {
// The interning here is unnecessary; it was added for efficiency.
edgeName = edgeName.intern();
return new SpringProxy(edgeName, c, this);
}
public void layoutContainer(Container parent) {
setParent(parent);
int n = parent.getComponentCount();
getConstraints(parent).reset();
for (int i = 0 ; i < n ; i++) {
getConstraints(parent.getComponent(i)).reset();
}
Insets insets = parent.getInsets();
Constraints pc = getConstraints(parent);
abandonCycles(pc.getX()).setValue(0);
abandonCycles(pc.getY()).setValue(0);
abandonCycles(pc.getWidth()).setValue(parent.getWidth() -
insets.left - insets.right);
abandonCycles(pc.getHeight()).setValue(parent.getHeight() -
insets.top - insets.bottom);
for (int i = 0 ; i < n ; i++) {
Component c = parent.getComponent(i);
Constraints cc = getConstraints(c);
int x = abandonCycles(cc.getX()).getValue();
int y = abandonCycles(cc.getY()).getValue();
int width = abandonCycles(cc.getWidth()).getValue();
int height = abandonCycles(cc.getHeight()).getValue();
c.setBounds(insets.left + x, insets.top + y, width, height);
}
}
}
|
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;
/** {@collect.stats}
* A data model for a combo box. This interface extends <code>ListDataModel</code>
* and adds the concept of a <i>selected item</i>. The selected item is generally
* the item which is visible in the combo box display area.
* <p>
* The selected item may not necessarily be managed by the underlying
* <code>ListModel</code>. This disjoint behavior allows for the temporary
* storage and retrieval of a selected item in the model.
*
* @author Arnaud Weber
*/
public interface ComboBoxModel extends ListModel {
/** {@collect.stats}
* Set the selected item. The implementation of this method should notify
* all registered <code>ListDataListener</code>s that the contents
* have changed.
*
* @param anItem the list object to select or <code>null</code>
* to clear the selection
*/
void setSelectedItem(Object anItem);
/** {@collect.stats}
* Returns the selected item
* @return The selected item or <code>null</code> if there is no selection
*/
Object getSelectedItem();
}
|
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 javax.swing.plaf.*;
import javax.accessibility.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* <code>JPanel</code> is a generic lightweight container.
* For examples and task-oriented documentation for JPanel, see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/panel.html">How to Use Panels</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
* description: A generic lightweight container.
*
* @author Arnaud Weber
* @author Steve Wilson
*/
public class JPanel extends JComponent implements Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "PanelUI";
/** {@collect.stats}
* Creates a new JPanel with the specified layout manager and buffering
* strategy.
*
* @param layout the LayoutManager to use
* @param isDoubleBuffered a boolean, true for double-buffering, which
* uses additional memory space to achieve fast, flicker-free
* updates
*/
public JPanel(LayoutManager layout, boolean isDoubleBuffered) {
setLayout(layout);
setDoubleBuffered(isDoubleBuffered);
setUIProperty("opaque", Boolean.TRUE);
updateUI();
}
/** {@collect.stats}
* Create a new buffered JPanel with the specified layout manager
*
* @param layout the LayoutManager to use
*/
public JPanel(LayoutManager layout) {
this(layout, true);
}
/** {@collect.stats}
* Creates a new <code>JPanel</code> with <code>FlowLayout</code>
* and the specified buffering strategy.
* If <code>isDoubleBuffered</code> is true, the <code>JPanel</code>
* will use a double buffer.
*
* @param isDoubleBuffered a boolean, true for double-buffering, which
* uses additional memory space to achieve fast, flicker-free
* updates
*/
public JPanel(boolean isDoubleBuffered) {
this(new FlowLayout(), isDoubleBuffered);
}
/** {@collect.stats}
* Creates a new <code>JPanel</code> with a double buffer
* and a flow layout.
*/
public JPanel() {
this(true);
}
/** {@collect.stats}
* Resets the UI property with a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((PanelUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the look and feel (L&F) object that renders this component.
*
* @return the PanelUI object that renders this component
* @since 1.4
*/
public PanelUI getUI() {
return (PanelUI)ui;
}
/** {@collect.stats}
* Sets the look and feel (L&F) object that renders this component.
*
* @param ui the PanelUI L&F object
* @see UIDefaults#getUI
* @since 1.4
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(PanelUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Returns a string that specifies the name of the L&F class
* that renders this component.
*
* @return "PanelUI"
* @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}
* 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}
* Returns a string representation of this JPanel. 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 JPanel.
*/
protected String paramString() {
return super.paramString();
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JPanel.
* For JPanels, the AccessibleContext takes the form of an
* AccessibleJPanel.
* A new AccessibleJPanel instance is created if necessary.
*
* @return an AccessibleJPanel that serves as the
* AccessibleContext of this JPanel
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJPanel();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JPanel</code> class. It provides an implementation of the
* Java Accessibility API appropriate to panel 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 AccessibleJPanel extends AccessibleJComponent {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PANEL;
}
}
}
|
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.awt.image.*;
import java.io.Serializable;
import java.util.EventListener;
import javax.swing.event.*;
/** {@collect.stats}
* The default implementation of a <code>Button</code> component's data model.
* <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 DefaultButtonModel implements ButtonModel, Serializable {
/** {@collect.stats} The bitmask used to store the state of the button. */
protected int stateMask = 0;
/** {@collect.stats} The action command string fired by the button. */
protected String actionCommand = null;
/** {@collect.stats} The button group that the button belongs to. */
protected ButtonGroup group = null;
/** {@collect.stats} The button's mnemonic. */
protected int mnemonic = 0;
/** {@collect.stats}
* Only one <code>ChangeEvent</code> is needed per button model
* instance since the event's only state is the source property.
* The source of events generated is always "this".
*/
protected transient ChangeEvent changeEvent = null;
/** {@collect.stats} Stores the listeners on this model. */
protected EventListenerList listenerList = new EventListenerList();
// controls the usage of the MenuItem.disabledAreNavigable UIDefaults
// property in the setArmed() method
private boolean menuItem = false;
/** {@collect.stats}
* Constructs a <code>DefaultButtonModel</code>.
*
*/
public DefaultButtonModel() {
stateMask = 0;
setEnabled(true);
}
/** {@collect.stats}
* Identifies the "armed" bit in the bitmask, which
* indicates partial commitment towards choosing/triggering
* the button.
*/
public final static int ARMED = 1 << 0;
/** {@collect.stats}
* Identifies the "selected" bit in the bitmask, which
* indicates that the button has been selected. Only needed for
* certain types of buttons - such as radio button or check box.
*/
public final static int SELECTED = 1 << 1;
/** {@collect.stats}
* Identifies the "pressed" bit in the bitmask, which
* indicates that the button is pressed.
*/
public final static int PRESSED = 1 << 2;
/** {@collect.stats}
* Identifies the "enabled" bit in the bitmask, which
* indicates that the button can be selected by
* an input device (such as a mouse pointer).
*/
public final static int ENABLED = 1 << 3;
/** {@collect.stats}
* Identifies the "rollover" bit in the bitmask, which
* indicates that the mouse is over the button.
*/
public final static int ROLLOVER = 1 << 4;
/** {@collect.stats}
* {@inheritDoc}
*/
public void setActionCommand(String actionCommand) {
this.actionCommand = actionCommand;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public String getActionCommand() {
return actionCommand;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public boolean isArmed() {
return (stateMask & ARMED) != 0;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public boolean isSelected() {
return (stateMask & SELECTED) != 0;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public boolean isEnabled() {
return (stateMask & ENABLED) != 0;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public boolean isPressed() {
return (stateMask & PRESSED) != 0;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public boolean isRollover() {
return (stateMask & ROLLOVER) != 0;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void setArmed(boolean b) {
if(isMenuItem() &&
UIManager.getBoolean("MenuItem.disabledAreNavigable")) {
if ((isArmed() == b)) {
return;
}
} else {
if ((isArmed() == b) || !isEnabled()) {
return;
}
}
if (b) {
stateMask |= ARMED;
} else {
stateMask &= ~ARMED;
}
fireStateChanged();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void setEnabled(boolean b) {
if(isEnabled() == b) {
return;
}
if (b) {
stateMask |= ENABLED;
} else {
stateMask &= ~ENABLED;
// unarm and unpress, just in case
stateMask &= ~ARMED;
stateMask &= ~PRESSED;
}
fireStateChanged();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void setSelected(boolean b) {
if (this.isSelected() == b) {
return;
}
if (b) {
stateMask |= SELECTED;
} else {
stateMask &= ~SELECTED;
}
fireItemStateChanged(
new ItemEvent(this,
ItemEvent.ITEM_STATE_CHANGED,
this,
b ? ItemEvent.SELECTED : ItemEvent.DESELECTED));
fireStateChanged();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void setPressed(boolean b) {
if((isPressed() == b) || !isEnabled()) {
return;
}
if (b) {
stateMask |= PRESSED;
} else {
stateMask &= ~PRESSED;
}
if(!isPressed() && isArmed()) {
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent) {
modifiers = ((InputEvent)currentEvent).getModifiers();
} else if (currentEvent instanceof ActionEvent) {
modifiers = ((ActionEvent)currentEvent).getModifiers();
}
fireActionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
getActionCommand(),
EventQueue.getMostRecentEventTime(),
modifiers));
}
fireStateChanged();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void setRollover(boolean b) {
if((isRollover() == b) || !isEnabled()) {
return;
}
if (b) {
stateMask |= ROLLOVER;
} else {
stateMask &= ~ROLLOVER;
}
fireStateChanged();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void setMnemonic(int key) {
mnemonic = key;
fireStateChanged();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public int getMnemonic() {
return mnemonic;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the change listeners
* registered on this <code>DefaultButtonModel</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}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is created lazily.
*
* @see EventListenerList
*/
protected void fireStateChanged() {
// 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]==ChangeListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void removeActionListener(ActionListener l) {
listenerList.remove(ActionListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the action listeners
* registered on this <code>DefaultButtonModel</code>.
*
* @return all of this model'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.
*
* @param e the <code>ActionEvent</code> to deliver to listeners
* @see EventListenerList
*/
protected void fireActionPerformed(ActionEvent 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]==ActionListener.class) {
// Lazily create the event:
// if (changeEvent == null)
// changeEvent = new ChangeEvent(this);
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void addItemListener(ItemListener l) {
listenerList.add(ItemListener.class, l);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void removeItemListener(ItemListener l) {
listenerList.remove(ItemListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the item listeners
* registered on this <code>DefaultButtonModel</code>.
*
* @return all of this model's <code>ItemListener</code>s
* or an empty
* array if no item listeners are currently registered
*
* @see #addItemListener
* @see #removeItemListener
*
* @since 1.4
*/
public ItemListener[] getItemListeners() {
return (ItemListener[])listenerList.getListeners(ItemListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param e the <code>ItemEvent</code> to deliver to listeners
* @see EventListenerList
*/
protected void fireItemStateChanged(ItemEvent 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]==ItemListener.class) {
// Lazily create the event:
// if (changeEvent == null)
// changeEvent = new ChangeEvent(this);
((ItemListener)listeners[i+1]).itemStateChanged(e);
}
}
}
/** {@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>DefaultButtonModel</code>
* instance <code>m</code>
* for its action listeners
* with the following code:
*
* <pre>ActionListener[] als = (ActionListener[])(m.getListeners(ActionListener.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 #getActionListeners
* @see #getChangeListeners
* @see #getItemListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
/** {@collect.stats} Overridden to return <code>null</code>. */
public Object[] getSelectedObjects() {
return null;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void setGroup(ButtonGroup group) {
this.group = group;
}
/** {@collect.stats}
* Returns the group that the button belongs to.
* Normally used with radio buttons, which are mutually
* exclusive within their group.
*
* @return the <code>ButtonGroup</code> that the button belongs to
*
* @since 1.3
*/
public ButtonGroup getGroup() {
return group;
}
boolean isMenuItem() {
return menuItem;
}
void setMenuItem(boolean menuItem) {
this.menuItem = menuItem;
}
}
|
Java
|
/*
* Copyright (c) 1997, 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;
/** {@collect.stats} DesktopManager objects are owned by a JDesktopPane object. They are responsible
* for implementing L&F specific behaviors for the JDesktopPane. JInternalFrame
* implementations should delegate specific behaviors to the DesktopManager. For
* instance, if a JInternalFrame was asked to iconify, it should try:
* <PRE>
* getDesktopPane().getDesktopManager().iconifyFrame(frame);
* </PRE>
* This delegation allows each L&F to provide custom behaviors for desktop-specific
* actions. (For example, how and where the internal frame's icon would appear.)
* <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
* @see JInternalFrame.JDesktopIcon
*
* @author David Kloba
*/
public interface DesktopManager
{
/** {@collect.stats} If possible, display this frame in an appropriate location.
* Normally, this is not called, as the creator of the JInternalFrame
* will add the frame to the appropriate parent.
*/
void openFrame(JInternalFrame f);
/** {@collect.stats} Generally, this call should remove the frame from it's parent. */
void closeFrame(JInternalFrame f);
/** {@collect.stats} Generally, the frame should be resized to match it's parents bounds. */
void maximizeFrame(JInternalFrame f);
/** {@collect.stats} Generally, this indicates that the frame should be restored to it's
* size and position prior to a maximizeFrame() call.
*/
void minimizeFrame(JInternalFrame f);
/** {@collect.stats} Generally, remove this frame from it's parent and add an iconic representation. */
void iconifyFrame(JInternalFrame f);
/** {@collect.stats} Generally, remove any iconic representation that is present and restore the
* frame to it's original size and location.
*/
void deiconifyFrame(JInternalFrame f);
/** {@collect.stats}
* Generally, indicate that this frame has focus. This is usually called after
* the JInternalFrame's IS_SELECTED_PROPERTY has been set to true.
*/
void activateFrame(JInternalFrame f);
/** {@collect.stats}
* Generally, indicate that this frame has lost focus. This is usually called
* after the JInternalFrame's IS_SELECTED_PROPERTY has been set to false.
*/
void deactivateFrame(JInternalFrame f);
/** {@collect.stats} This method is normally called when the user has indicated that
* they will begin dragging a component around. This method should be called
* prior to any dragFrame() calls to allow the DesktopManager to prepare any
* necessary state. Normally <b>f</b> will be a JInternalFrame.
*/
void beginDraggingFrame(JComponent f);
/** {@collect.stats} The user has moved the frame. Calls to this method will be preceded by calls
* to beginDraggingFrame().
* Normally <b>f</b> will be a JInternalFrame.
*/
void dragFrame(JComponent f, int newX, int newY);
/** {@collect.stats} This method signals the end of the dragging session. Any state maintained by
* the DesktopManager can be removed here. Normally <b>f</b> will be a JInternalFrame.
*/
void endDraggingFrame(JComponent f);
/** {@collect.stats} This methods is normally called when the user has indicated that
* they will begin resizing the frame. This method should be called
* prior to any resizeFrame() calls to allow the DesktopManager to prepare any
* necessary state. Normally <b>f</b> will be a JInternalFrame.
*/
void beginResizingFrame(JComponent f, int direction);
/** {@collect.stats} The user has resized the component. Calls to this method will be preceded by calls
* to beginResizingFrame().
* Normally <b>f</b> will be a JInternalFrame.
*/
void resizeFrame(JComponent f, int newX, int newY, int newWidth, int newHeight);
/** {@collect.stats} This method signals the end of the resize session. Any state maintained by
* the DesktopManager can be removed here. Normally <b>f</b> will be a JInternalFrame.
*/
void endResizingFrame(JComponent f);
/** {@collect.stats} This is a primitive reshape method.*/
void setBoundsForFrame(JComponent f, int newX, int newY, int newWidth, int newHeight);
}
|
Java
|
/*
* Copyright (c) 1997, 2010, 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.accessibility.*;
import java.awt.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* <code>JSplitPane</code> is used to divide two (and only two)
* <code>Component</code>s. The two <code>Component</code>s
* are graphically divided based on the look and feel
* implementation, and the two <code>Component</code>s can then be
* interactively resized by the user.
* Information on using <code>JSplitPane</code> is in
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/splitpane.html">How to Use Split Panes</a> in
* <em>The Java Tutorial</em>.
* <p>
* The two <code>Component</code>s in a split pane can be aligned
* left to right using
* <code>JSplitPane.HORIZONTAL_SPLIT</code>, or top to bottom using
* <code>JSplitPane.VERTICAL_SPLIT</code>.
* The preferred way to change the size of the <code>Component</code>s
* is to invoke
* <code>setDividerLocation</code> where <code>location</code> is either
* the new x or y position, depending on the orientation of the
* <code>JSplitPane</code>.
* <p>
* To resize the <code>Component</code>s to their preferred sizes invoke
* <code>resetToPreferredSizes</code>.
* <p>
* When the user is resizing the <code>Component</code>s the minimum
* size of the <code>Components</code> is used to determine the
* maximum/minimum position the <code>Component</code>s
* can be set to. If the minimum size of the two
* components is greater than the size of the split pane the divider
* will not allow you to resize it. To alter the minimum size of a
* <code>JComponent</code>, see {@link JComponent#setMinimumSize}.
* <p>
* When the user resizes the split pane the new space is distributed between
* the two components based on the <code>resizeWeight</code> property.
* A value of 0,
* the default, indicates the right/bottom component gets all the space,
* where as a value of 1 indicates the left/top component gets all the space.
* <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 #setDividerLocation
* @see #resetToPreferredSizes
*
* @author Scott Violet
*/
public class JSplitPane extends JComponent implements Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "SplitPaneUI";
/** {@collect.stats}
* Vertical split indicates the <code>Component</code>s are
* split along the y axis. For example the two
* <code>Component</code>s will be split one on top of the other.
*/
public final static int VERTICAL_SPLIT = 0;
/** {@collect.stats}
* Horizontal split indicates the <code>Component</code>s are
* split along the x axis. For example the two
* <code>Component</code>s will be split one to the left of the
* other.
*/
public final static int HORIZONTAL_SPLIT = 1;
/** {@collect.stats}
* Used to add a <code>Component</code> to the left of the other
* <code>Component</code>.
*/
public final static String LEFT = "left";
/** {@collect.stats}
* Used to add a <code>Component</code> to the right of the other
* <code>Component</code>.
*/
public final static String RIGHT = "right";
/** {@collect.stats}
* Used to add a <code>Component</code> above the other
* <code>Component</code>.
*/
public final static String TOP = "top";
/** {@collect.stats}
* Used to add a <code>Component</code> below the other
* <code>Component</code>.
*/
public final static String BOTTOM = "bottom";
/** {@collect.stats}
* Used to add a <code>Component</code> that will represent the divider.
*/
public final static String DIVIDER = "divider";
/** {@collect.stats}
* Bound property name for orientation (horizontal or vertical).
*/
public final static String ORIENTATION_PROPERTY = "orientation";
/** {@collect.stats}
* Bound property name for continuousLayout.
*/
public final static String CONTINUOUS_LAYOUT_PROPERTY = "continuousLayout";
/** {@collect.stats}
* Bound property name for border.
*/
public final static String DIVIDER_SIZE_PROPERTY = "dividerSize";
/** {@collect.stats}
* Bound property for oneTouchExpandable.
*/
public final static String ONE_TOUCH_EXPANDABLE_PROPERTY =
"oneTouchExpandable";
/** {@collect.stats}
* Bound property for lastLocation.
*/
public final static String LAST_DIVIDER_LOCATION_PROPERTY =
"lastDividerLocation";
/** {@collect.stats}
* Bound property for the dividerLocation.
* @since 1.3
*/
public final static String DIVIDER_LOCATION_PROPERTY = "dividerLocation";
/** {@collect.stats}
* Bound property for weight.
* @since 1.3
*/
public final static String RESIZE_WEIGHT_PROPERTY = "resizeWeight";
/** {@collect.stats}
* How the views are split.
*/
protected int orientation;
/** {@collect.stats}
* Whether or not the views are continuously redisplayed while
* resizing.
*/
protected boolean continuousLayout;
/** {@collect.stats}
* The left or top component.
*/
protected Component leftComponent;
/** {@collect.stats}
* The right or bottom component.
*/
protected Component rightComponent;
/** {@collect.stats}
* Size of the divider.
*/
protected int dividerSize;
private boolean dividerSizeSet = false;
/** {@collect.stats}
* Is a little widget provided to quickly expand/collapse the
* split pane?
*/
protected boolean oneTouchExpandable;
private boolean oneTouchExpandableSet;
/** {@collect.stats}
* Previous location of the split pane.
*/
protected int lastDividerLocation;
/** {@collect.stats}
* How to distribute extra space.
*/
private double resizeWeight;
/** {@collect.stats}
* Location of the divider, at least the value that was set, the UI may
* have a different value.
*/
private int dividerLocation;
/** {@collect.stats}
* Creates a new <code>JSplitPane</code> configured to arrange the child
* components side-by-side horizontally with no continuous
* layout, using two buttons for the components.
*/
public JSplitPane() {
this(JSplitPane.HORIZONTAL_SPLIT, false,
new JButton(UIManager.getString("SplitPane.leftButtonText")),
new JButton(UIManager.getString("SplitPane.rightButtonText")));
}
/** {@collect.stats}
* Creates a new <code>JSplitPane</code> configured with the
* specified orientation and no continuous layout.
*
* @param newOrientation <code>JSplitPane.HORIZONTAL_SPLIT</code> or
* <code>JSplitPane.VERTICAL_SPLIT</code>
* @exception IllegalArgumentException if <code>orientation</code>
* is not one of HORIZONTAL_SPLIT or VERTICAL_SPLIT.
*/
public JSplitPane(int newOrientation) {
this(newOrientation, false);
}
/** {@collect.stats}
* Creates a new <code>JSplitPane</code> with the specified
* orientation and redrawing style.
*
* @param newOrientation <code>JSplitPane.HORIZONTAL_SPLIT</code> or
* <code>JSplitPane.VERTICAL_SPLIT</code>
* @param newContinuousLayout a boolean, true for the components to
* redraw continuously as the divider changes position, false
* to wait until the divider position stops changing to redraw
* @exception IllegalArgumentException if <code>orientation</code>
* is not one of HORIZONTAL_SPLIT or VERTICAL_SPLIT
*/
public JSplitPane(int newOrientation,
boolean newContinuousLayout) {
this(newOrientation, newContinuousLayout, null, null);
}
/** {@collect.stats}
* Creates a new <code>JSplitPane</code> with the specified
* orientation and
* with the specified components that do not do continuous
* redrawing.
*
* @param newOrientation <code>JSplitPane.HORIZONTAL_SPLIT</code> or
* <code>JSplitPane.VERTICAL_SPLIT</code>
* @param newLeftComponent the <code>Component</code> that will
* appear on the left
* of a horizontally-split pane, or at the top of a
* vertically-split pane
* @param newRightComponent the <code>Component</code> that will
* appear on the right
* of a horizontally-split pane, or at the bottom of a
* vertically-split pane
* @exception IllegalArgumentException if <code>orientation</code>
* is not one of: HORIZONTAL_SPLIT or VERTICAL_SPLIT
*/
public JSplitPane(int newOrientation,
Component newLeftComponent,
Component newRightComponent){
this(newOrientation, false, newLeftComponent, newRightComponent);
}
/** {@collect.stats}
* Creates a new <code>JSplitPane</code> with the specified
* orientation and
* redrawing style, and with the specified components.
*
* @param newOrientation <code>JSplitPane.HORIZONTAL_SPLIT</code> or
* <code>JSplitPane.VERTICAL_SPLIT</code>
* @param newContinuousLayout a boolean, true for the components to
* redraw continuously as the divider changes position, false
* to wait until the divider position stops changing to redraw
* @param newLeftComponent the <code>Component</code> that will
* appear on the left
* of a horizontally-split pane, or at the top of a
* vertically-split pane
* @param newRightComponent the <code>Component</code> that will
* appear on the right
* of a horizontally-split pane, or at the bottom of a
* vertically-split pane
* @exception IllegalArgumentException if <code>orientation</code>
* is not one of HORIZONTAL_SPLIT or VERTICAL_SPLIT
*/
public JSplitPane(int newOrientation,
boolean newContinuousLayout,
Component newLeftComponent,
Component newRightComponent){
super();
dividerLocation = -1;
setLayout(null);
setUIProperty("opaque", Boolean.TRUE);
orientation = newOrientation;
if (orientation != HORIZONTAL_SPLIT && orientation != VERTICAL_SPLIT)
throw new IllegalArgumentException("cannot create JSplitPane, " +
"orientation must be one of " +
"JSplitPane.HORIZONTAL_SPLIT " +
"or JSplitPane.VERTICAL_SPLIT");
continuousLayout = newContinuousLayout;
if (newLeftComponent != null)
setLeftComponent(newLeftComponent);
if (newRightComponent != null)
setRightComponent(newRightComponent);
updateUI();
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the <code>SplitPaneUI</code> 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(SplitPaneUI ui) {
if ((SplitPaneUI)this.ui != ui) {
super.setUI(ui);
revalidate();
}
}
/** {@collect.stats}
* Returns the <code>SplitPaneUI</code> that is providing the
* current look and feel.
*
* @return the <code>SplitPaneUI</code> object that renders this component
* @beaninfo
* expert: true
* description: The L&F object that renders this component.
*/
public SplitPaneUI getUI() {
return (SplitPaneUI)ui;
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((SplitPaneUI)UIManager.getUI(this));
revalidate();
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "SplitPaneUI"
* @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}
* Sets the size of the divider.
*
* @param newSize an integer giving the size of the divider in pixels
* @beaninfo
* bound: true
* description: The size of the divider.
*/
public void setDividerSize(int newSize) {
int oldSize = dividerSize;
dividerSizeSet = true;
if (oldSize != newSize) {
dividerSize = newSize;
firePropertyChange(DIVIDER_SIZE_PROPERTY, oldSize, newSize);
}
}
/** {@collect.stats}
* Returns the size of the divider.
*
* @return an integer giving the size of the divider in pixels
*/
public int getDividerSize() {
return dividerSize;
}
/** {@collect.stats}
* Sets the component to the left (or above) the divider.
*
* @param comp the <code>Component</code> to display in that position
*/
public void setLeftComponent(Component comp) {
if (comp == null) {
if (leftComponent != null) {
remove(leftComponent);
leftComponent = null;
}
} else {
add(comp, JSplitPane.LEFT);
}
}
/** {@collect.stats}
* Returns the component to the left (or above) the divider.
*
* @return the <code>Component</code> displayed in that position
* @beaninfo
* preferred: true
* description: The component to the left (or above) the divider.
*/
public Component getLeftComponent() {
return leftComponent;
}
/** {@collect.stats}
* Sets the component above, or to the left of the divider.
*
* @param comp the <code>Component</code> to display in that position
* @beaninfo
* description: The component above, or to the left of the divider.
*/
public void setTopComponent(Component comp) {
setLeftComponent(comp);
}
/** {@collect.stats}
* Returns the component above, or to the left of the divider.
*
* @return the <code>Component</code> displayed in that position
*/
public Component getTopComponent() {
return leftComponent;
}
/** {@collect.stats}
* Sets the component to the right (or below) the divider.
*
* @param comp the <code>Component</code> to display in that position
* @beaninfo
* preferred: true
* description: The component to the right (or below) the divider.
*/
public void setRightComponent(Component comp) {
if (comp == null) {
if (rightComponent != null) {
remove(rightComponent);
rightComponent = null;
}
} else {
add(comp, JSplitPane.RIGHT);
}
}
/** {@collect.stats}
* Returns the component to the right (or below) the divider.
*
* @return the <code>Component</code> displayed in that position
*/
public Component getRightComponent() {
return rightComponent;
}
/** {@collect.stats}
* Sets the component below, or to the right of the divider.
*
* @param comp the <code>Component</code> to display in that position
* @beaninfo
* description: The component below, or to the right of the divider.
*/
public void setBottomComponent(Component comp) {
setRightComponent(comp);
}
/** {@collect.stats}
* Returns the component below, or to the right of the divider.
*
* @return the <code>Component</code> displayed in that position
*/
public Component getBottomComponent() {
return rightComponent;
}
/** {@collect.stats}
* Sets the value of the <code>oneTouchExpandable</code> property,
* which must be <code>true</code> for the
* <code>JSplitPane</code> to provide a UI widget
* on the divider to quickly expand/collapse the divider.
* The default value of this property is <code>false</code>.
* Some look and feels might not support one-touch expanding;
* they will ignore this property.
*
* @param newValue <code>true</code> to specify that the split pane should provide a
* collapse/expand widget
* @beaninfo
* bound: true
* description: UI widget on the divider to quickly
* expand/collapse the divider.
*
* @see #isOneTouchExpandable
*/
public void setOneTouchExpandable(boolean newValue) {
boolean oldValue = oneTouchExpandable;
oneTouchExpandable = newValue;
oneTouchExpandableSet = true;
firePropertyChange(ONE_TOUCH_EXPANDABLE_PROPERTY, oldValue, newValue);
repaint();
}
/** {@collect.stats}
* Gets the <code>oneTouchExpandable</code> property.
*
* @return the value of the <code>oneTouchExpandable</code> property
* @see #setOneTouchExpandable
*/
public boolean isOneTouchExpandable() {
return oneTouchExpandable;
}
/** {@collect.stats}
* Sets the last location the divider was at to
* <code>newLastLocation</code>.
*
* @param newLastLocation an integer specifying the last divider location
* in pixels, from the left (or upper) edge of the pane to the
* left (or upper) edge of the divider
* @beaninfo
* bound: true
* description: The last location the divider was at.
*/
public void setLastDividerLocation(int newLastLocation) {
int oldLocation = lastDividerLocation;
lastDividerLocation = newLastLocation;
firePropertyChange(LAST_DIVIDER_LOCATION_PROPERTY, oldLocation,
newLastLocation);
}
/** {@collect.stats}
* Returns the last location the divider was at.
*
* @return an integer specifying the last divider location as a count
* of pixels from the left (or upper) edge of the pane to the
* left (or upper) edge of the divider
*/
public int getLastDividerLocation() {
return lastDividerLocation;
}
/** {@collect.stats}
* Sets the orientation, or how the splitter is divided. The options
* are:<ul>
* <li>JSplitPane.VERTICAL_SPLIT (above/below orientation of components)
* <li>JSplitPane.HORIZONTAL_SPLIT (left/right orientation of components)
* </ul>
*
* @param orientation an integer specifying the orientation
* @exception IllegalArgumentException if orientation is not one of:
* HORIZONTAL_SPLIT or VERTICAL_SPLIT.
* @beaninfo
* bound: true
* description: The orientation, or how the splitter is divided.
* enum: HORIZONTAL_SPLIT JSplitPane.HORIZONTAL_SPLIT
* VERTICAL_SPLIT JSplitPane.VERTICAL_SPLIT
*/
public void setOrientation(int orientation) {
if ((orientation != VERTICAL_SPLIT) &&
(orientation != HORIZONTAL_SPLIT)) {
throw new IllegalArgumentException("JSplitPane: orientation must " +
"be one of " +
"JSplitPane.VERTICAL_SPLIT or " +
"JSplitPane.HORIZONTAL_SPLIT");
}
int oldOrientation = this.orientation;
this.orientation = orientation;
firePropertyChange(ORIENTATION_PROPERTY, oldOrientation, orientation);
}
/** {@collect.stats}
* Returns the orientation.
*
* @return an integer giving the orientation
* @see #setOrientation
*/
public int getOrientation() {
return orientation;
}
/** {@collect.stats}
* Sets the value of the <code>continuousLayout</code> property,
* which must be <code>true</code> for the child components
* to be continuously
* redisplayed and laid out during user intervention.
* The default value of this property is <code>false</code>.
* Some look and feels might not support continuous layout;
* they will ignore this property.
*
* @param newContinuousLayout <code>true</code> if the components
* should continuously be redrawn as the divider changes position
* @beaninfo
* bound: true
* description: Whether the child components are
* continuously redisplayed and laid out during
* user intervention.
* @see #isContinuousLayout
*/
public void setContinuousLayout(boolean newContinuousLayout) {
boolean oldCD = continuousLayout;
continuousLayout = newContinuousLayout;
firePropertyChange(CONTINUOUS_LAYOUT_PROPERTY, oldCD,
newContinuousLayout);
}
/** {@collect.stats}
* Gets the <code>continuousLayout</code> property.
*
* @return the value of the <code>continuousLayout</code> property
* @see #setContinuousLayout
*/
public boolean isContinuousLayout() {
return continuousLayout;
}
/** {@collect.stats}
* Specifies how to distribute extra space when the size of the split pane
* changes. A value of 0, the default,
* indicates the right/bottom component gets all the extra space (the
* left/top component acts fixed), where as a value of 1 specifies the
* left/top component gets all the extra space (the right/bottom component
* acts fixed). Specifically, the left/top component gets (weight * diff)
* extra space and the right/bottom component gets (1 - weight) * diff
* extra space.
*
* @param value as described above
* @exception IllegalArgumentException if <code>value</code> is < 0 or > 1
* @since 1.3
* @beaninfo
* bound: true
* description: Specifies how to distribute extra space when the split pane
* resizes.
*/
public void setResizeWeight(double value) {
if (value < 0 || value > 1) {
throw new IllegalArgumentException("JSplitPane weight must be between 0 and 1");
}
double oldWeight = resizeWeight;
resizeWeight = value;
firePropertyChange(RESIZE_WEIGHT_PROPERTY, oldWeight, value);
}
/** {@collect.stats}
* Returns the number that determines how extra space is distributed.
* @return how extra space is to be distributed on a resize of the
* split pane
* @since 1.3
*/
public double getResizeWeight() {
return resizeWeight;
}
/** {@collect.stats}
* Lays out the <code>JSplitPane</code> layout based on the preferred size
* of the children components. This will likely result in changing
* the divider location.
*/
public void resetToPreferredSizes() {
SplitPaneUI ui = getUI();
if (ui != null) {
ui.resetToPreferredSizes(this);
}
}
/** {@collect.stats}
* Sets the divider location as a percentage of the
* <code>JSplitPane</code>'s size.
* <p>
* This method is implemented in terms of
* <code>setDividerLocation(int)</code>.
* This method immediately changes the size of the split pane based on
* its current size. If the split pane is not correctly realized and on
* screen, this method will have no effect (new divider location will
* become (current size * proportionalLocation) which is 0).
*
* @param proportionalLocation a double-precision floating point value
* that specifies a percentage, from zero (top/left) to 1.0
* (bottom/right)
* @exception IllegalArgumentException if the specified location is < 0
* or > 1.0
* @beaninfo
* description: The location of the divider.
*/
public void setDividerLocation(double proportionalLocation) {
if (proportionalLocation < 0.0 ||
proportionalLocation > 1.0) {
throw new IllegalArgumentException("proportional location must " +
"be between 0.0 and 1.0.");
}
if (getOrientation() == VERTICAL_SPLIT) {
setDividerLocation((int)((double)(getHeight() - getDividerSize()) *
proportionalLocation));
} else {
setDividerLocation((int)((double)(getWidth() - getDividerSize()) *
proportionalLocation));
}
}
/** {@collect.stats}
* Sets the location of the divider. This is passed off to the
* look and feel implementation, and then listeners are notified. A value
* less than 0 implies the divider should be reset to a value that
* attempts to honor the preferred size of the left/top component.
* After notifying the listeners, the last divider location is updated,
* via <code>setLastDividerLocation</code>.
*
* @param location an int specifying a UI-specific value (typically a
* pixel count)
* @beaninfo
* bound: true
* description: The location of the divider.
*/
public void setDividerLocation(int location) {
int oldValue = dividerLocation;
dividerLocation = location;
// Notify UI.
SplitPaneUI ui = getUI();
if (ui != null) {
ui.setDividerLocation(this, location);
}
// Then listeners
firePropertyChange(DIVIDER_LOCATION_PROPERTY, oldValue, location);
// And update the last divider location.
setLastDividerLocation(oldValue);
}
/** {@collect.stats}
* Returns the last value passed to <code>setDividerLocation</code>.
* The value returned from this method may differ from the actual
* divider location (if <code>setDividerLocation</code> was passed a
* value bigger than the curent size).
*
* @return an integer specifying the location of the divider
*/
public int getDividerLocation() {
return dividerLocation;
}
/** {@collect.stats}
* Returns the minimum location of the divider from the look and feel
* implementation.
*
* @return an integer specifying a UI-specific value for the minimum
* location (typically a pixel count); or -1 if the UI is
* <code>null</code>
* @beaninfo
* description: The minimum location of the divider from the L&F.
*/
public int getMinimumDividerLocation() {
SplitPaneUI ui = getUI();
if (ui != null) {
return ui.getMinimumDividerLocation(this);
}
return -1;
}
/** {@collect.stats}
* Returns the maximum location of the divider from the look and feel
* implementation.
*
* @return an integer specifying a UI-specific value for the maximum
* location (typically a pixel count); or -1 if the UI is
* <code>null</code>
*/
public int getMaximumDividerLocation() {
SplitPaneUI ui = getUI();
if (ui != null) {
return ui.getMaximumDividerLocation(this);
}
return -1;
}
/** {@collect.stats}
* Removes the child component, <code>component</code> from the
* pane. Resets the <code>leftComponent</code> or
* <code>rightComponent</code> instance variable, as necessary.
*
* @param component the <code>Component</code> to remove
*/
public void remove(Component component) {
if (component == leftComponent) {
leftComponent = null;
} else if (component == rightComponent) {
rightComponent = null;
}
super.remove(component);
// Update the JSplitPane on the screen
revalidate();
repaint();
}
/** {@collect.stats}
* Removes the <code>Component</code> at the specified index.
* Updates the <code>leftComponent</code> and <code>rightComponent</code>
* instance variables as necessary, and then messages super.
*
* @param index an integer specifying the component to remove, where
* 1 specifies the left/top component and 2 specifies the
* bottom/right component
*/
public void remove(int index) {
Component comp = getComponent(index);
if (comp == leftComponent) {
leftComponent = null;
} else if (comp == rightComponent) {
rightComponent = null;
}
super.remove(index);
// Update the JSplitPane on the screen
revalidate();
repaint();
}
/** {@collect.stats}
* Removes all the child components from the split pane. Resets the
* <code>leftComonent</code> and <code>rightComponent</code>
* instance variables.
*/
public void removeAll() {
leftComponent = rightComponent = null;
super.removeAll();
// Update the JSplitPane on the screen
revalidate();
repaint();
}
/** {@collect.stats}
* Returns true, so that calls to <code>revalidate</code>
* on any descendant of this <code>JSplitPane</code>
* will cause a request to be queued that
* will validate the <code>JSplitPane</code> and all its descendants.
*
* @return true
* @see JComponent#revalidate
*
* @beaninfo
* hidden: true
*/
public boolean isValidateRoot() {
return true;
}
/** {@collect.stats}
* Adds the specified component to this split pane.
* If <code>constraints</code> identifies the left/top or
* right/bottom child component, and a component with that identifier
* was previously added, it will be removed and then <code>comp</code>
* will be added in its place. If <code>constraints</code> is not
* one of the known identifiers the layout manager may throw an
* <code>IllegalArgumentException</code>.
* <p>
* The possible constraints objects (Strings) are:
* <ul>
* <li>JSplitPane.TOP
* <li>JSplitPane.LEFT
* <li>JSplitPane.BOTTOM
* <li>JSplitPane.RIGHT
* </ul>
* If the <code>constraints</code> object is <code>null</code>,
* the component is added in the
* first available position (left/top if open, else right/bottom).
*
* @param comp the component to add
* @param constraints an <code>Object</code> specifying the
* layout constraints
* (position) for this component
* @param index an integer specifying the index in the container's
* list.
* @exception IllegalArgumentException if the <code>constraints</code>
* object does not match an existing component
* @see java.awt.Container#addImpl(Component, Object, int)
*/
protected void addImpl(Component comp, Object constraints, int index)
{
Component toRemove;
if (constraints != null && !(constraints instanceof String)) {
throw new IllegalArgumentException("cannot add to layout: " +
"constraint must be a string " +
"(or null)");
}
/* If the constraints are null and the left/right component is
invalid, add it at the left/right component. */
if (constraints == null) {
if (getLeftComponent() == null) {
constraints = JSplitPane.LEFT;
} else if (getRightComponent() == null) {
constraints = JSplitPane.RIGHT;
}
}
/* Find the Component that already exists and remove it. */
if (constraints != null && (constraints.equals(JSplitPane.LEFT) ||
constraints.equals(JSplitPane.TOP))) {
toRemove = getLeftComponent();
if (toRemove != null) {
remove(toRemove);
}
leftComponent = comp;
index = -1;
} else if (constraints != null &&
(constraints.equals(JSplitPane.RIGHT) ||
constraints.equals(JSplitPane.BOTTOM))) {
toRemove = getRightComponent();
if (toRemove != null) {
remove(toRemove);
}
rightComponent = comp;
index = -1;
} else if (constraints != null &&
constraints.equals(JSplitPane.DIVIDER)) {
index = -1;
}
/* LayoutManager should raise for else condition here. */
super.addImpl(comp, constraints, index);
// Update the JSplitPane on the screen
revalidate();
repaint();
}
/** {@collect.stats}
* Subclassed to message the UI with <code>finishedPaintingChildren</code>
* after super has been messaged, as well as painting the border.
*
* @param g the <code>Graphics</code> context within which to paint
*/
protected void paintChildren(Graphics g) {
super.paintChildren(g);
SplitPaneUI ui = getUI();
if (ui != null) {
Graphics tempG = g.create();
ui.finishedPaintingChildren(this, tempG);
tempG.dispose();
}
}
/** {@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);
}
}
}
void setUIProperty(String propertyName, Object value) {
if (propertyName == "dividerSize") {
if (!dividerSizeSet) {
setDividerSize(((Number)value).intValue());
dividerSizeSet = false;
}
} else if (propertyName == "oneTouchExpandable") {
if (!oneTouchExpandableSet) {
setOneTouchExpandable(((Boolean)value).booleanValue());
oneTouchExpandableSet = false;
}
} else {
super.setUIProperty(propertyName, value);
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JSplitPane</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>JSplitPane</code>.
*/
protected String paramString() {
String orientationString = (orientation == HORIZONTAL_SPLIT ?
"HORIZONTAL_SPLIT" : "VERTICAL_SPLIT");
String continuousLayoutString = (continuousLayout ?
"true" : "false");
String oneTouchExpandableString = (oneTouchExpandable ?
"true" : "false");
return super.paramString() +
",continuousLayout=" + continuousLayoutString +
",dividerSize=" + dividerSize +
",lastDividerLocation=" + lastDividerLocation +
",oneTouchExpandable=" + oneTouchExpandableString +
",orientation=" + orientationString;
}
///////////////////////////
// Accessibility support //
///////////////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JSplitPane.
* For split panes, the AccessibleContext takes the form of an
* AccessibleJSplitPane.
* A new AccessibleJSplitPane instance is created if necessary.
*
* @return an AccessibleJSplitPane that serves as the
* AccessibleContext of this JSplitPane
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this SplitPane.
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJSplitPane();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JSplitPane</code> class. It provides an implementation of the
* Java Accessibility API appropriate to split 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 AccessibleJSplitPane extends AccessibleJComponent
implements AccessibleValue {
/** {@collect.stats}
* Gets the state set of this object.
*
* @return an instance of AccessibleState containing the current state
* of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
// FIXME: [[[WDW - Should also add BUSY if this implements
// Adjustable at some point. If this happens, we probably
// should also add actions.]]]
if (getOrientation() == VERTICAL_SPLIT) {
states.add(AccessibleState.VERTICAL);
} else {
states.add(AccessibleState.HORIZONTAL);
}
return states;
}
/** {@collect.stats}
* Get the AccessibleValue associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleValue interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
/** {@collect.stats}
* Gets the accessible value of this object.
*
* @return a localized String describing the value of this object
*/
public Number getCurrentAccessibleValue() {
return new Integer(getDividerLocation());
}
/** {@collect.stats}
* Sets the value of this object as a Number.
*
* @return True if the value was set.
*/
public boolean setCurrentAccessibleValue(Number n) {
// TIGER - 4422535
if (n == null) {
return false;
}
setDividerLocation(n.intValue());
return true;
}
/** {@collect.stats}
* Gets the minimum accessible value of this object.
*
* @return The minimum value of this object.
*/
public Number getMinimumAccessibleValue() {
return new Integer(getUI().getMinimumDividerLocation(
JSplitPane.this));
}
/** {@collect.stats}
* Gets the maximum accessible value of this object.
*
* @return The maximum value of this object.
*/
public Number getMaximumAccessibleValue() {
return new Integer(getUI().getMaximumDividerLocation(
JSplitPane.this));
}
/** {@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.SPLIT_PANE;
}
} // inner class AccessibleJSplitPane
}
|
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.AWTKeyStroke;
import java.awt.event.KeyEvent;
/** {@collect.stats}
* A KeyStroke represents a key action on the keyboard, or equivalent input
* device. KeyStrokes can correspond to only a press or release of a particular
* key, just as KEY_PRESSED and KEY_RELEASED KeyEvents do; alternately, they
* can correspond to typing a specific Java character, just as KEY_TYPED
* KeyEvents do. In all cases, KeyStrokes can specify modifiers (alt, shift,
* control, meta, altGraph, or a combination thereof) which must be present during the
* action for an exact match.
* <p>
* KeyStrokes are used to define high-level (semantic) action events. Instead
* of trapping every keystroke and throwing away the ones you are not
* interested in, those keystrokes you care about automatically initiate
* actions on the Components with which they are registered.
* <p>
* KeyStrokes are immutable, and are intended to be unique. Client code cannot
* create a KeyStroke; a variant of <code>getKeyStroke</code> must be used
* instead. These factory methods allow the KeyStroke implementation to cache
* and share instances efficiently.
* <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.text.Keymap
* @see #getKeyStroke
*
* @author Arnaud Weber
* @author David Mendenhall
*/
public class KeyStroke extends AWTKeyStroke {
/** {@collect.stats}
* Serial Version ID.
*/
private static final long serialVersionUID = -9060180771037902530L;
private KeyStroke() {
}
private KeyStroke(char keyChar, int keyCode, int modifiers,
boolean onKeyRelease) {
super(keyChar, keyCode, modifiers, onKeyRelease);
}
/** {@collect.stats}
* Returns a shared instance of a <code>KeyStroke</code>
* that represents a <code>KEY_TYPED</code> event for the
* specified character.
*
* @param keyChar the character value for a keyboard key
* @return a KeyStroke object for that key
*/
public static KeyStroke getKeyStroke(char keyChar) {
synchronized (AWTKeyStroke.class) {
registerSubclass(KeyStroke.class);
return (KeyStroke)getAWTKeyStroke(keyChar);
}
}
/** {@collect.stats}
* Returns an instance of a KeyStroke, specifying whether the key is
* considered to be activated when it is pressed or released. Unlike all
* other factory methods in this class, the instances returned by this
* method are not necessarily cached or shared.
*
* @param keyChar the character value for a keyboard key
* @param onKeyRelease <code>true</code> if this KeyStroke corresponds to a
* key release; <code>false</code> otherwise.
* @return a KeyStroke object for that key
* @deprecated use getKeyStroke(char)
*/
@Deprecated
public static KeyStroke getKeyStroke(char keyChar, boolean onKeyRelease) {
return new KeyStroke(keyChar, KeyEvent.VK_UNDEFINED, 0, onKeyRelease);
}
/** {@collect.stats}
* Returns a shared instance of a {@code KeyStroke}
* that represents a {@code KEY_TYPED} event for the
* specified Character object and a
* set of modifiers. Note that the first parameter is of type Character
* rather than char. This is to avoid inadvertent clashes with calls to
* <code>getKeyStroke(int keyCode, int modifiers)</code>.
*
* The modifiers consist of any combination of following:<ul>
* <li>java.awt.event.InputEvent.SHIFT_DOWN_MASK
* <li>java.awt.event.InputEvent.CTRL_DOWN_MASK
* <li>java.awt.event.InputEvent.META_DOWN_MASK
* <li>java.awt.event.InputEvent.ALT_DOWN_MASK
* <li>java.awt.event.InputEvent.ALT_GRAPH_DOWN_MASK
* </ul>
* The old modifiers listed below also can be used, but they are
* mapped to _DOWN_ modifiers. <ul>
* <li>java.awt.event.InputEvent.SHIFT_MASK
* <li>java.awt.event.InputEvent.CTRL_MASK
* <li>java.awt.event.InputEvent.META_MASK
* <li>java.awt.event.InputEvent.ALT_MASK
* <li>java.awt.event.InputEvent.ALT_GRAPH_MASK
* </ul>
* also can be used, but they are mapped to _DOWN_ modifiers.
*
* Since these numbers are all different powers of two, any combination of
* them is an integer in which each bit represents a different modifier
* key. Use 0 to specify no modifiers.
*
* @param keyChar the Character object for a keyboard character
* @param modifiers a bitwise-ored combination of any modifiers
* @return an KeyStroke object for that key
* @throws IllegalArgumentException if keyChar is null
*
* @see java.awt.event.InputEvent
* @since 1.3
*/
public static KeyStroke getKeyStroke(Character keyChar, int modifiers) {
synchronized (AWTKeyStroke.class) {
registerSubclass(KeyStroke.class);
return (KeyStroke)getAWTKeyStroke(keyChar, modifiers);
}
}
/** {@collect.stats}
* Returns a shared instance of a KeyStroke, given a numeric key code and a
* set of modifiers, specifying whether the key is activated when it is
* pressed or released.
* <p>
* The "virtual key" constants defined in java.awt.event.KeyEvent can be
* used to specify the key code. For example:<ul>
* <li>java.awt.event.KeyEvent.VK_ENTER
* <li>java.awt.event.KeyEvent.VK_TAB
* <li>java.awt.event.KeyEvent.VK_SPACE
* </ul>
* The modifiers consist of any combination of:<ul>
* <li>java.awt.event.InputEvent.SHIFT_DOWN_MASK
* <li>java.awt.event.InputEvent.CTRL_DOWN_MASK
* <li>java.awt.event.InputEvent.META_DOWN_MASK
* <li>java.awt.event.InputEvent.ALT_DOWN_MASK
* <li>java.awt.event.InputEvent.ALT_GRAPH_DOWN_MASK
* </ul>
* The old modifiers <ul>
* <li>java.awt.event.InputEvent.SHIFT_MASK
* <li>java.awt.event.InputEvent.CTRL_MASK
* <li>java.awt.event.InputEvent.META_MASK
* <li>java.awt.event.InputEvent.ALT_MASK
* <li>java.awt.event.InputEvent.ALT_GRAPH_MASK
* </ul>
* also can be used, but they are mapped to _DOWN_ modifiers.
*
* Since these numbers are all different powers of two, any combination of
* them is an integer in which each bit represents a different modifier
* key. Use 0 to specify no modifiers.
*
* @param keyCode an int specifying the numeric code for a keyboard key
* @param modifiers a bitwise-ored combination of any modifiers
* @param onKeyRelease <code>true</code> if the KeyStroke should represent
* a key release; <code>false</code> otherwise.
* @return a KeyStroke object for that key
*
* @see java.awt.event.KeyEvent
* @see java.awt.event.InputEvent
*/
public static KeyStroke getKeyStroke(int keyCode, int modifiers,
boolean onKeyRelease) {
synchronized (AWTKeyStroke.class) {
registerSubclass(KeyStroke.class);
return (KeyStroke)getAWTKeyStroke(keyCode, modifiers,
onKeyRelease);
}
}
/** {@collect.stats}
* Returns a shared instance of a KeyStroke, given a numeric key code and a
* set of modifiers. The returned KeyStroke will correspond to a key press.
* <p>
* The "virtual key" constants defined in java.awt.event.KeyEvent can be
* used to specify the key code. For example:<ul>
* <li>java.awt.event.KeyEvent.VK_ENTER
* <li>java.awt.event.KeyEvent.VK_TAB
* <li>java.awt.event.KeyEvent.VK_SPACE
* </ul>
* The modifiers consist of any combination of:<ul>
* <li>java.awt.event.InputEvent.SHIFT_DOWN_MASK
* <li>java.awt.event.InputEvent.CTRL_DOWN_MASK
* <li>java.awt.event.InputEvent.META_DOWN_MASK
* <li>java.awt.event.InputEvent.ALT_DOWN_MASK
* <li>java.awt.event.InputEvent.ALT_GRAPH_DOWN_MASK
* </ul>
* The old modifiers <ul>
* <li>java.awt.event.InputEvent.SHIFT_MASK
* <li>java.awt.event.InputEvent.CTRL_MASK
* <li>java.awt.event.InputEvent.META_MASK
* <li>java.awt.event.InputEvent.ALT_MASK
* <li>java.awt.event.InputEvent.ALT_GRAPH_MASK
* </ul>
* also can be used, but they are mapped to _DOWN_ modifiers.
*
* Since these numbers are all different powers of two, any combination of
* them is an integer in which each bit represents a different modifier
* key. Use 0 to specify no modifiers.
*
* @param keyCode an int specifying the numeric code for a keyboard key
* @param modifiers a bitwise-ored combination of any modifiers
* @return a KeyStroke object for that key
*
* @see java.awt.event.KeyEvent
* @see java.awt.event.InputEvent
*/
public static KeyStroke getKeyStroke(int keyCode, int modifiers) {
synchronized (AWTKeyStroke.class) {
registerSubclass(KeyStroke.class);
return (KeyStroke)getAWTKeyStroke(keyCode, modifiers);
}
}
/** {@collect.stats}
* Returns a KeyStroke which represents the stroke which generated a given
* KeyEvent.
* <p>
* This method obtains the keyChar from a KeyTyped event, and the keyCode
* from a KeyPressed or KeyReleased event. The KeyEvent modifiers are
* obtained for all three types of KeyEvent.
*
* @param anEvent the KeyEvent from which to obtain the KeyStroke
* @throws NullPointerException if <code>anEvent</code> is null
* @return the KeyStroke that precipitated the event
*/
public static KeyStroke getKeyStrokeForEvent(KeyEvent anEvent) {
synchronized (AWTKeyStroke.class) {
registerSubclass(KeyStroke.class);
return (KeyStroke)getAWTKeyStrokeForEvent(anEvent);
}
}
/** {@collect.stats}
* Parses a string and returns a <code>KeyStroke</code>.
* The string must have the following syntax:
* <pre>
* <modifiers>* (<typedID> | <pressedReleasedID>)
*
* modifiers := shift | control | ctrl | meta | alt | altGraph
* typedID := typed <typedKey>
* typedKey := string of length 1 giving Unicode character.
* pressedReleasedID := (pressed | released) key
* key := KeyEvent key code name, i.e. the name following "VK_".
* </pre>
* If typed, pressed or released is not specified, pressed is assumed. Here
* are some examples:
* <pre>
* "INSERT" => getKeyStroke(KeyEvent.VK_INSERT, 0);
* "control DELETE" => getKeyStroke(KeyEvent.VK_DELETE, InputEvent.CTRL_MASK);
* "alt shift X" => getKeyStroke(KeyEvent.VK_X, InputEvent.ALT_MASK | InputEvent.SHIFT_MASK);
* "alt shift released X" => getKeyStroke(KeyEvent.VK_X, InputEvent.ALT_MASK | InputEvent.SHIFT_MASK, true);
* "typed a" => getKeyStroke('a');
* </pre>
*
* In order to maintain backward-compatibility, specifying a null String,
* or a String which is formatted incorrectly, returns null.
*
* @param s a String formatted as described above
* @return a KeyStroke object for that String, or null if the specified
* String is null, or is formatted incorrectly
*
* @see java.awt.event.KeyEvent
*/
public static KeyStroke getKeyStroke(String s) {
if (s == null || s.length() == 0) {
return null;
}
synchronized (AWTKeyStroke.class) {
registerSubclass(KeyStroke.class);
try {
return (KeyStroke)getAWTKeyStroke(s);
} catch (IllegalArgumentException e) {
return null;
}
}
}
}
|
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.Font;
import java.awt.Image;
import java.awt.*;
import java.text.*;
import java.awt.geom.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.plaf.LabelUI;
import javax.accessibility.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.plaf.basic.*;
import java.util.*;
/** {@collect.stats}
* A display area for a short text string or an image,
* or both.
* A label does not react to input events.
* As a result, it cannot get the keyboard focus.
* A label can, however, display a keyboard alternative
* as a convenience for a nearby component
* that has a keyboard alternative but can't display it.
* <p>
* A <code>JLabel</code> object can display
* either text, an image, or both.
* You can specify where in the label's display area
* the label's contents are aligned
* by setting the vertical and horizontal alignment.
* By default, labels are vertically centered
* in their display area.
* Text-only labels are leading edge aligned, by default;
* image-only labels are horizontally centered, by default.
* <p>
* You can also specify the position of the text
* relative to the image.
* By default, text is on the trailing edge of the image,
* with the text and image vertically aligned.
* <p>
* A label's leading and trailing edge are determined from the value of its
* {@link java.awt.ComponentOrientation} property. At present, the default
* ComponentOrientation setting maps the leading edge to left and the trailing
* edge to right.
*
* <p>
* Finally, you can use the <code>setIconTextGap</code> method
* to specify how many pixels
* should appear between the text and the image.
* The default is 4 pixels.
* <p>
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/label.html">How to Use Labels</a>
* in <em>The Java Tutorial</em>
* for further documentation.
* <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 that displays a short string and an icon.
*
* @author Hans Muller
*/
public class JLabel extends JComponent implements SwingConstants, Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "LabelUI";
private int mnemonic = '\0';
private int mnemonicIndex = -1;
private String text = ""; // "" rather than null, for BeanBox
private Icon defaultIcon = null;
private Icon disabledIcon = null;
private boolean disabledIconSet = false;
private int verticalAlignment = CENTER;
private int horizontalAlignment = LEADING;
private int verticalTextPosition = CENTER;
private int horizontalTextPosition = TRAILING;
private int iconTextGap = 4;
protected Component labelFor = null;
/** {@collect.stats}
* Client property key used to determine what label is labeling the
* component. This is generally not used by labels, but is instead
* used by components such as text areas that are being labeled by
* labels. When the labelFor property of a label is set, it will
* automatically set the LABELED_BY_PROPERTY of the component being
* labelled.
*
* @see #setLabelFor
*/
static final String LABELED_BY_PROPERTY = "labeledBy";
/** {@collect.stats}
* Creates a <code>JLabel</code> instance with the specified
* text, image, and horizontal alignment.
* The label is centered vertically in its display area.
* The text is on the trailing edge of the image.
*
* @param text The text to be displayed by the label.
* @param icon The image to be displayed by the label.
* @param horizontalAlignment One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> or
* <code>TRAILING</code>.
*/
public JLabel(String text, Icon icon, int horizontalAlignment) {
setText(text);
setIcon(icon);
setHorizontalAlignment(horizontalAlignment);
updateUI();
setAlignmentX(LEFT_ALIGNMENT);
}
/** {@collect.stats}
* Creates a <code>JLabel</code> instance with the specified
* text and horizontal alignment.
* The label is centered vertically in its display area.
*
* @param text The text to be displayed by the label.
* @param horizontalAlignment One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> or
* <code>TRAILING</code>.
*/
public JLabel(String text, int horizontalAlignment) {
this(text, null, horizontalAlignment);
}
/** {@collect.stats}
* Creates a <code>JLabel</code> instance with the specified text.
* The label is aligned against the leading edge of its display area,
* and centered vertically.
*
* @param text The text to be displayed by the label.
*/
public JLabel(String text) {
this(text, null, LEADING);
}
/** {@collect.stats}
* Creates a <code>JLabel</code> instance with the specified
* image and horizontal alignment.
* The label is centered vertically in its display area.
*
* @param image The image to be displayed by the label.
* @param horizontalAlignment One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> or
* <code>TRAILING</code>.
*/
public JLabel(Icon image, int horizontalAlignment) {
this(null, image, horizontalAlignment);
}
/** {@collect.stats}
* Creates a <code>JLabel</code> instance with the specified image.
* The label is centered vertically and horizontally
* in its display area.
*
* @param image The image to be displayed by the label.
*/
public JLabel(Icon image) {
this(null, image, CENTER);
}
/** {@collect.stats}
* Creates a <code>JLabel</code> instance with
* no image and with an empty string for the title.
* The label is centered vertically
* in its display area.
* The label's contents, once set, will be displayed on the leading edge
* of the label's display area.
*/
public JLabel() {
this("", null, LEADING);
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return LabelUI object
*/
public LabelUI getUI() {
return (LabelUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the LabelUI 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(LabelUI ui) {
super.setUI(ui);
// disabled icon is generated by LF so it should be unset here
if (!disabledIconSet && disabledIcon != null) {
setDisabledIcon(null);
}
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((LabelUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns a string that specifies the name of the l&f class
* that renders this component.
*
* @return String "LabelUI"
*
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns the text string that the label displays.
*
* @return a String
* @see #setText
*/
public String getText() {
return text;
}
/** {@collect.stats}
* Defines the single line of text this component will display. If
* the value of text is null or empty string, nothing is displayed.
* <p>
* The default value of this property is null.
* <p>
* This is a JavaBeans bound property.
*
* @see #setVerticalTextPosition
* @see #setHorizontalTextPosition
* @see #setIcon
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: Defines the single line of text this component will display.
*/
public void setText(String text) {
String oldAccessibleName = null;
if (accessibleContext != null) {
oldAccessibleName = accessibleContext.getAccessibleName();
}
String oldValue = this.text;
this.text = text;
firePropertyChange("text", oldValue, text);
setDisplayedMnemonicIndex(
SwingUtilities.findDisplayedMnemonicIndex(
text, getDisplayedMnemonic()));
if ((accessibleContext != null)
&& (accessibleContext.getAccessibleName() != oldAccessibleName)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldAccessibleName,
accessibleContext.getAccessibleName());
}
if (text == null || oldValue == null || !text.equals(oldValue)) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the graphic image (glyph, icon) that the label displays.
*
* @return an Icon
* @see #setIcon
*/
public Icon getIcon() {
return defaultIcon;
}
/** {@collect.stats}
* Defines the icon this component will display. If
* the value of icon is null, nothing is displayed.
* <p>
* The default value of this property is null.
* <p>
* This is a JavaBeans bound property.
*
* @see #setVerticalTextPosition
* @see #setHorizontalTextPosition
* @see #getIcon
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: The icon this component will display.
*/
public void setIcon(Icon icon) {
Icon oldValue = defaultIcon;
defaultIcon = icon;
/* If the default icon has really changed and we had
* generated the disabled icon for this component
* (in other words, setDisabledIcon() was never called), then
* clear the disabledIcon field.
*/
if ((defaultIcon != oldValue) && !disabledIconSet) {
disabledIcon = null;
}
firePropertyChange("icon", oldValue, defaultIcon);
if ((accessibleContext != null) && (oldValue != defaultIcon)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, defaultIcon);
}
/* If the default icon has changed and the new one is
* a different size, then revalidate. Repaint if the
* default icon has changed.
*/
if (defaultIcon != oldValue) {
if ((defaultIcon == null) ||
(oldValue == null) ||
(defaultIcon.getIconWidth() != oldValue.getIconWidth()) ||
(defaultIcon.getIconHeight() != oldValue.getIconHeight())) {
revalidate();
}
repaint();
}
}
/** {@collect.stats}
* Returns the icon used by the label when it's disabled.
* If no disabled icon has been set this will forward the call to
* the look and feel to construct an appropriate disabled Icon.
* <p>
* Some look and feels might not render the disabled Icon, in which
* case they will ignore this.
*
* @return the <code>disabledIcon</code> property
* @see #setDisabledIcon
* @see javax.swing.LookAndFeel#getDisabledIcon
* @see ImageIcon
*/
public Icon getDisabledIcon() {
if (!disabledIconSet && disabledIcon == null && defaultIcon != null) {
disabledIcon = UIManager.getLookAndFeel().getDisabledIcon(this, defaultIcon);
if (disabledIcon != null) {
firePropertyChange("disabledIcon", null, disabledIcon);
}
}
return disabledIcon;
}
/** {@collect.stats}
* Set the icon to be displayed if this JLabel is "disabled"
* (JLabel.setEnabled(false)).
* <p>
* The default value of this property is null.
*
* @param disabledIcon the Icon to display when the component is disabled
* @see #getDisabledIcon
* @see #setEnabled
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The icon to display if the label is disabled.
*/
public void setDisabledIcon(Icon disabledIcon) {
Icon oldValue = this.disabledIcon;
this.disabledIcon = disabledIcon;
disabledIconSet = (disabledIcon != null);
firePropertyChange("disabledIcon", oldValue, disabledIcon);
if (disabledIcon != oldValue) {
if (disabledIcon == null || oldValue == null ||
disabledIcon.getIconWidth() != oldValue.getIconWidth() ||
disabledIcon.getIconHeight() != oldValue.getIconHeight()) {
revalidate();
}
if (!isEnabled()) {
repaint();
}
}
}
/** {@collect.stats}
* Specify a keycode that indicates a mnemonic key.
* This property is used when the label is part of a larger component.
* If the labelFor property of the label is not null, the label will
* call the requestFocus method of the component specified by the
* labelFor property when the mnemonic is activated.
*
* @see #getLabelFor
* @see #setLabelFor
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The mnemonic keycode.
*/
public void setDisplayedMnemonic(int key) {
int oldKey = mnemonic;
mnemonic = key;
firePropertyChange("displayedMnemonic", oldKey, mnemonic);
setDisplayedMnemonicIndex(
SwingUtilities.findDisplayedMnemonicIndex(getText(), mnemonic));
if (key != oldKey) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Specifies the displayedMnemonic as a char value.
*
* @param aChar a char specifying the mnemonic to display
* @see #setDisplayedMnemonic(int)
*/
public void setDisplayedMnemonic(char aChar) {
int vk = (int) aChar;
if(vk >= 'a' && vk <='z')
vk -= ('a' - 'A');
setDisplayedMnemonic(vk);
}
/** {@collect.stats}
* Return the keycode that indicates a mnemonic key.
* This property is used when the label is part of a larger component.
* If the labelFor property of the label is not null, the label will
* call the requestFocus method of the component specified by the
* labelFor property when the mnemonic is activated.
*
* @return int value for the mnemonic key
*
* @see #getLabelFor
* @see #setLabelFor
*/
public int getDisplayedMnemonic() {
return mnemonic;
}
/** {@collect.stats}
* Provides a hint to the look and feel as to which character in the
* text should be decorated to represent the mnemonic. Not all look and
* feels may support this. A value of -1 indicates either there is no
* mnemonic, the mnemonic character is not contained in the string, or
* the developer does not wish the mnemonic to be displayed.
* <p>
* The value of this is updated as the properties relating to the
* mnemonic change (such as the mnemonic itself, the text...).
* You should only ever have to call this if
* you do not wish the default character to be underlined. For example, if
* the text was 'Save As', with a mnemonic of 'a', and you wanted the 'A'
* to be decorated, as 'Save <u>A</u>s', you would have to invoke
* <code>setDisplayedMnemonicIndex(5)</code> after invoking
* <code>setDisplayedMnemonic(KeyEvent.VK_A)</code>.
*
* @since 1.4
* @param index Index into the String to underline
* @exception IllegalArgumentException will be thrown if <code>index</code
* is >= length of the text, or < -1
*
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: the index into the String to draw the keyboard character
* mnemonic at
*/
public void setDisplayedMnemonicIndex(int index)
throws IllegalArgumentException {
int oldValue = mnemonicIndex;
if (index == -1) {
mnemonicIndex = -1;
} else {
String text = getText();
int textLength = (text == null) ? 0 : text.length();
if (index < -1 || index >= textLength) { // index out of range
throw new IllegalArgumentException("index == " + index);
}
}
mnemonicIndex = index;
firePropertyChange("displayedMnemonicIndex", oldValue, index);
if (index != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the character, as an index, that the look and feel should
* provide decoration for as representing the mnemonic character.
*
* @since 1.4
* @return index representing mnemonic character
* @see #setDisplayedMnemonicIndex
*/
public int getDisplayedMnemonicIndex() {
return mnemonicIndex;
}
/** {@collect.stats}
* Verify that key is a legal value for the horizontalAlignment properties.
*
* @param key the property value to check
* @param message the IllegalArgumentException detail message
* @exception IllegalArgumentException if key isn't LEFT, CENTER, RIGHT,
* LEADING or TRAILING.
* @see #setHorizontalTextPosition
* @see #setHorizontalAlignment
*/
protected int checkHorizontalKey(int key, String message) {
if ((key == LEFT) ||
(key == CENTER) ||
(key == RIGHT) ||
(key == LEADING) ||
(key == TRAILING)) {
return key;
}
else {
throw new IllegalArgumentException(message);
}
}
/** {@collect.stats}
* Verify that key is a legal value for the
* verticalAlignment or verticalTextPosition properties.
*
* @param key the property value to check
* @param message the IllegalArgumentException detail message
* @exception IllegalArgumentException if key isn't TOP, CENTER, or BOTTOM.
* @see #setVerticalAlignment
* @see #setVerticalTextPosition
*/
protected int checkVerticalKey(int key, String message) {
if ((key == TOP) || (key == CENTER) || (key == BOTTOM)) {
return key;
}
else {
throw new IllegalArgumentException(message);
}
}
/** {@collect.stats}
* Returns the amount of space between the text and the icon
* displayed in this label.
*
* @return an int equal to the number of pixels between the text
* and the icon.
* @see #setIconTextGap
*/
public int getIconTextGap() {
return iconTextGap;
}
/** {@collect.stats}
* If both the icon and text properties are set, this property
* defines the space between them.
* <p>
* The default value of this property is 4 pixels.
* <p>
* This is a JavaBeans bound property.
*
* @see #getIconTextGap
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: If both the icon and text properties are set, this
* property defines the space between them.
*/
public void setIconTextGap(int iconTextGap) {
int oldValue = this.iconTextGap;
this.iconTextGap = iconTextGap;
firePropertyChange("iconTextGap", oldValue, iconTextGap);
if (iconTextGap != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the alignment of the label's contents along the Y axis.
*
* @return The value of the verticalAlignment property, one of the
* following constants defined in <code>SwingConstants</code>:
* <code>TOP</code>,
* <code>CENTER</code>, or
* <code>BOTTOM</code>.
*
* @see SwingConstants
* @see #setVerticalAlignment
*/
public int getVerticalAlignment() {
return verticalAlignment;
}
/** {@collect.stats}
* Sets the alignment of the label's contents along the Y axis.
* <p>
* The default value of this property is CENTER.
*
* @param alignment One of the following constants
* defined in <code>SwingConstants</code>:
* <code>TOP</code>,
* <code>CENTER</code> (the default), or
* <code>BOTTOM</code>.
*
* @see SwingConstants
* @see #getVerticalAlignment
* @beaninfo
* bound: true
* enum: TOP SwingConstants.TOP
* CENTER SwingConstants.CENTER
* BOTTOM SwingConstants.BOTTOM
* attribute: visualUpdate true
* description: The alignment of the label's contents along the Y axis.
*/
public void setVerticalAlignment(int alignment) {
if (alignment == verticalAlignment) return;
int oldValue = verticalAlignment;
verticalAlignment = checkVerticalKey(alignment, "verticalAlignment");
firePropertyChange("verticalAlignment", oldValue, verticalAlignment);
repaint();
}
/** {@collect.stats}
* Returns the alignment of the label's contents along the X axis.
*
* @return The value of the horizontalAlignment property, one of the
* following constants defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> or
* <code>TRAILING</code>.
*
* @see #setHorizontalAlignment
* @see SwingConstants
*/
public int getHorizontalAlignment() {
return horizontalAlignment;
}
/** {@collect.stats}
* Sets the alignment of the label's contents along the X axis.
* <p>
* This is a JavaBeans bound property.
*
* @param alignment One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code> (the default for image-only labels),
* <code>RIGHT</code>,
* <code>LEADING</code> (the default for text-only labels) or
* <code>TRAILING</code>.
*
* @see SwingConstants
* @see #getHorizontalAlignment
* @beaninfo
* bound: true
* enum: LEFT SwingConstants.LEFT
* CENTER SwingConstants.CENTER
* RIGHT SwingConstants.RIGHT
* LEADING SwingConstants.LEADING
* TRAILING SwingConstants.TRAILING
* attribute: visualUpdate true
* description: The alignment of the label's content along the X axis.
*/
public void setHorizontalAlignment(int alignment) {
if (alignment == horizontalAlignment) return;
int oldValue = horizontalAlignment;
horizontalAlignment = checkHorizontalKey(alignment,
"horizontalAlignment");
firePropertyChange("horizontalAlignment",
oldValue, horizontalAlignment);
repaint();
}
/** {@collect.stats}
* Returns the vertical position of the label's text,
* relative to its image.
*
* @return One of the following constants
* defined in <code>SwingConstants</code>:
* <code>TOP</code>,
* <code>CENTER</code>, or
* <code>BOTTOM</code>.
*
* @see #setVerticalTextPosition
* @see SwingConstants
*/
public int getVerticalTextPosition() {
return verticalTextPosition;
}
/** {@collect.stats}
* Sets the vertical position of the label's text,
* relative to its image.
* <p>
* The default value of this property is CENTER.
* <p>
* This is a JavaBeans bound property.
*
* @param textPosition One of the following constants
* defined in <code>SwingConstants</code>:
* <code>TOP</code>,
* <code>CENTER</code> (the default), or
* <code>BOTTOM</code>.
*
* @see SwingConstants
* @see #getVerticalTextPosition
* @beaninfo
* bound: true
* enum: TOP SwingConstants.TOP
* CENTER SwingConstants.CENTER
* BOTTOM SwingConstants.BOTTOM
* expert: true
* attribute: visualUpdate true
* description: The vertical position of the text relative to it's image.
*/
public void setVerticalTextPosition(int textPosition) {
if (textPosition == verticalTextPosition) return;
int old = verticalTextPosition;
verticalTextPosition = checkVerticalKey(textPosition,
"verticalTextPosition");
firePropertyChange("verticalTextPosition", old, verticalTextPosition);
revalidate();
repaint();
}
/** {@collect.stats}
* Returns the horizontal position of the label's text,
* relative to its image.
*
* @return One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> or
* <code>TRAILING</code>.
*
* @see SwingConstants
*/
public int getHorizontalTextPosition() {
return horizontalTextPosition;
}
/** {@collect.stats}
* Sets the horizontal position of the label's text,
* relative to its image.
*
* @param textPosition One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code>, or
* <code>TRAILING</code> (the default).
* @exception IllegalArgumentException
*
* @see SwingConstants
* @beaninfo
* expert: true
* bound: true
* enum: LEFT SwingConstants.LEFT
* CENTER SwingConstants.CENTER
* RIGHT SwingConstants.RIGHT
* LEADING SwingConstants.LEADING
* TRAILING SwingConstants.TRAILING
* attribute: visualUpdate true
* description: The horizontal position of the label's text,
* relative to its image.
*/
public void setHorizontalTextPosition(int textPosition) {
int old = horizontalTextPosition;
this.horizontalTextPosition = checkHorizontalKey(textPosition,
"horizontalTextPosition");
firePropertyChange("horizontalTextPosition",
old, horizontalTextPosition);
revalidate();
repaint();
}
/** {@collect.stats}
* This is overridden to return false if the current Icon's Image is
* not equal to the passed in Image <code>img</code>.
*
* @see java.awt.image.ImageObserver
* @see java.awt.Component#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
public boolean imageUpdate(Image img, int infoflags,
int x, int y, int w, int h) {
// Don't use getDisabledIcon, will trigger creation of icon if icon
// not set.
if (!isShowing() ||
!SwingUtilities.doesIconReferenceImage(getIcon(), img) &&
!SwingUtilities.doesIconReferenceImage(disabledIcon, img)) {
return false;
}
return super.imageUpdate(img, infoflags, x, y, w, h);
}
/** {@collect.stats}
* 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}
* Returns a string representation of this JLabel. 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 JLabel.
*/
protected String paramString() {
String textString = (text != null ?
text : "");
String defaultIconString = ((defaultIcon != null)
&& (defaultIcon != this) ?
defaultIcon.toString() : "");
String disabledIconString = ((disabledIcon != null)
&& (disabledIcon != this) ?
disabledIcon.toString() : "");
String labelForString = (labelFor != null ?
labelFor.toString() : "");
String verticalAlignmentString;
if (verticalAlignment == TOP) {
verticalAlignmentString = "TOP";
} else if (verticalAlignment == CENTER) {
verticalAlignmentString = "CENTER";
} else if (verticalAlignment == BOTTOM) {
verticalAlignmentString = "BOTTOM";
} else verticalAlignmentString = "";
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 verticalTextPositionString;
if (verticalTextPosition == TOP) {
verticalTextPositionString = "TOP";
} else if (verticalTextPosition == CENTER) {
verticalTextPositionString = "CENTER";
} else if (verticalTextPosition == BOTTOM) {
verticalTextPositionString = "BOTTOM";
} else verticalTextPositionString = "";
String horizontalTextPositionString;
if (horizontalTextPosition == LEFT) {
horizontalTextPositionString = "LEFT";
} else if (horizontalTextPosition == CENTER) {
horizontalTextPositionString = "CENTER";
} else if (horizontalTextPosition == RIGHT) {
horizontalTextPositionString = "RIGHT";
} else if (horizontalTextPosition == LEADING) {
horizontalTextPositionString = "LEADING";
} else if (horizontalTextPosition == TRAILING) {
horizontalTextPositionString = "TRAILING";
} else horizontalTextPositionString = "";
return super.paramString() +
",defaultIcon=" + defaultIconString +
",disabledIcon=" + disabledIconString +
",horizontalAlignment=" + horizontalAlignmentString +
",horizontalTextPosition=" + horizontalTextPositionString +
",iconTextGap=" + iconTextGap +
",labelFor=" + labelForString +
",text=" + textString +
",verticalAlignment=" + verticalAlignmentString +
",verticalTextPosition=" + verticalTextPositionString;
}
/** {@collect.stats}
* --- Accessibility Support ---
*/
/** {@collect.stats}
* Get the component this is labelling.
*
* @return the Component this is labelling. Can be null if this
* does not label a Component. If the displayedMnemonic
* property is set and the labelFor property is also set, the label
* will call the requestFocus method of the component specified by the
* labelFor property when the mnemonic is activated.
*
* @see #getDisplayedMnemonic
* @see #setDisplayedMnemonic
*/
public Component getLabelFor() {
return labelFor;
}
/** {@collect.stats}
* Set the component this is labelling. Can be null if this does not
* label a Component. If the displayedMnemonic property is set
* and the labelFor property is also set, the label will
* call the requestFocus method of the component specified by the
* labelFor property when the mnemonic is activated.
*
* @param c the Component this label is for, or null if the label is
* not the label for a component
*
* @see #getDisplayedMnemonic
* @see #setDisplayedMnemonic
*
* @beaninfo
* bound: true
* description: The component this is labelling.
*/
public void setLabelFor(Component c) {
Component oldC = labelFor;
labelFor = c;
firePropertyChange("labelFor", oldC, c);
if (oldC instanceof JComponent) {
((JComponent)oldC).putClientProperty(LABELED_BY_PROPERTY, null);
}
if (c instanceof JComponent) {
((JComponent)c).putClientProperty(LABELED_BY_PROPERTY, this);
}
}
/** {@collect.stats}
* Get the AccessibleContext of this object
*
* @return the AccessibleContext of this object
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this Label.
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJLabel();
}
return accessibleContext;
}
/** {@collect.stats}
* The class used to obtain the accessible role for this object.
* <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 AccessibleJLabel extends AccessibleJComponent
implements AccessibleText, AccessibleExtendedComponent {
/** {@collect.stats}
* Get the accessible name of this object.
*
* @return the localized name of the object -- can be null if this
* object does not have a name
* @see AccessibleContext#setAccessibleName
*/
public String getAccessibleName() {
String name = accessibleName;
if (name == null) {
name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
if (name == null) {
name = JLabel.this.getText();
}
if (name == null) {
name = super.getAccessibleName();
}
return name;
}
/** {@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.LABEL;
}
/** {@collect.stats}
* Get the AccessibleIcons associated with this object if one
* or more exist. Otherwise return null.
* @since 1.3
*/
public AccessibleIcon [] getAccessibleIcon() {
Icon icon = getIcon();
if (icon instanceof Accessible) {
AccessibleContext ac =
((Accessible)icon).getAccessibleContext();
if (ac != null && ac instanceof AccessibleIcon) {
return new AccessibleIcon[] { (AccessibleIcon)ac };
}
}
return null;
}
/** {@collect.stats}
* Get the AccessibleRelationSet associated with this object if one
* exists. Otherwise return null.
* @see AccessibleRelation
* @since 1.3
*/
public AccessibleRelationSet getAccessibleRelationSet() {
// Check where the AccessibleContext's relation
// set already contains a LABEL_FOR relation.
AccessibleRelationSet relationSet
= super.getAccessibleRelationSet();
if (!relationSet.contains(AccessibleRelation.LABEL_FOR)) {
Component c = JLabel.this.getLabelFor();
if (c != null) {
AccessibleRelation relation
= new AccessibleRelation(AccessibleRelation.LABEL_FOR);
relation.setTarget(c);
relationSet.add(relation);
}
}
return relationSet;
}
/* AccessibleText ---------- */
public AccessibleText getAccessibleText() {
View view = (View)JLabel.this.getClientProperty("html");
if (view != null) {
return this;
} else {
return null;
}
}
/** {@collect.stats}
* Given a point in local coordinates, return the zero-based index
* of the character under that Point. If the point is invalid,
* this method returns -1.
*
* @param p the Point in local coordinates
* @return the zero-based index of the character under Point p; if
* Point is invalid returns -1.
* @since 1.3
*/
public int getIndexAtPoint(Point p) {
View view = (View) JLabel.this.getClientProperty("html");
if (view != null) {
Rectangle r = getTextRectangle();
if (r == null) {
return -1;
}
Rectangle2D.Float shape =
new Rectangle2D.Float(r.x, r.y, r.width, r.height);
Position.Bias bias[] = new Position.Bias[1];
return view.viewToModel(p.x, p.y, shape, bias);
} else {
return -1;
}
}
/** {@collect.stats}
* Determine the bounding box of the character at the given
* index into the string. The bounds are returned in local
* coordinates. If the index is invalid an empty rectangle is
* returned.
*
* @param i the index into the String
* @return the screen coordinates of the character's the bounding box,
* if index is invalid returns an empty rectangle.
* @since 1.3
*/
public Rectangle getCharacterBounds(int i) {
View view = (View) JLabel.this.getClientProperty("html");
if (view != null) {
Rectangle r = getTextRectangle();
if (r == null) {
return null;
}
Rectangle2D.Float shape =
new Rectangle2D.Float(r.x, r.y, r.width, r.height);
try {
Shape charShape =
view.modelToView(i, shape, Position.Bias.Forward);
return charShape.getBounds();
} catch (BadLocationException e) {
return null;
}
} else {
return null;
}
}
/** {@collect.stats}
* Return the number of characters (valid indicies)
*
* @return the number of characters
* @since 1.3
*/
public int getCharCount() {
View view = (View) JLabel.this.getClientProperty("html");
if (view != null) {
Document d = view.getDocument();
if (d instanceof StyledDocument) {
StyledDocument doc = (StyledDocument)d;
return doc.getLength();
}
}
return accessibleContext.getAccessibleName().length();
}
/** {@collect.stats}
* Return the zero-based offset of the caret.
*
* Note: That to the right of the caret will have the same index
* value as the offset (the caret is between two characters).
* @return the zero-based offset of the caret.
* @since 1.3
*/
public int getCaretPosition() {
// There is no caret.
return -1;
}
/** {@collect.stats}
* Returns the String at a given index.
*
* @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
* or AccessibleText.SENTENCE to retrieve
* @param index an index within the text >= 0
* @return the letter, word, or sentence,
* null for an invalid index or part
* @since 1.3
*/
public String getAtIndex(int part, int index) {
if (index < 0 || index >= getCharCount()) {
return null;
}
switch (part) {
case AccessibleText.CHARACTER:
try {
return getText(index, 1);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.WORD:
try {
String s = getText(0, getCharCount());
BreakIterator words = BreakIterator.getWordInstance(getLocale());
words.setText(s);
int end = words.following(index);
return s.substring(words.previous(), end);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.SENTENCE:
try {
String s = getText(0, getCharCount());
BreakIterator sentence =
BreakIterator.getSentenceInstance(getLocale());
sentence.setText(s);
int end = sentence.following(index);
return s.substring(sentence.previous(), end);
} catch (BadLocationException e) {
return null;
}
default:
return null;
}
}
/** {@collect.stats}
* Returns the String after a given index.
*
* @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
* or AccessibleText.SENTENCE to retrieve
* @param index an index within the text >= 0
* @return the letter, word, or sentence, null for an invalid
* index or part
* @since 1.3
*/
public String getAfterIndex(int part, int index) {
if (index < 0 || index >= getCharCount()) {
return null;
}
switch (part) {
case AccessibleText.CHARACTER:
if (index+1 >= getCharCount()) {
return null;
}
try {
return getText(index+1, 1);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.WORD:
try {
String s = getText(0, getCharCount());
BreakIterator words = BreakIterator.getWordInstance(getLocale());
words.setText(s);
int start = words.following(index);
if (start == BreakIterator.DONE || start >= s.length()) {
return null;
}
int end = words.following(start);
if (end == BreakIterator.DONE || end >= s.length()) {
return null;
}
return s.substring(start, end);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.SENTENCE:
try {
String s = getText(0, getCharCount());
BreakIterator sentence =
BreakIterator.getSentenceInstance(getLocale());
sentence.setText(s);
int start = sentence.following(index);
if (start == BreakIterator.DONE || start > s.length()) {
return null;
}
int end = sentence.following(start);
if (end == BreakIterator.DONE || end > s.length()) {
return null;
}
return s.substring(start, end);
} catch (BadLocationException e) {
return null;
}
default:
return null;
}
}
/** {@collect.stats}
* Returns the String before a given index.
*
* @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
* or AccessibleText.SENTENCE to retrieve
* @param index an index within the text >= 0
* @return the letter, word, or sentence, null for an invalid index
* or part
* @since 1.3
*/
public String getBeforeIndex(int part, int index) {
if (index < 0 || index > getCharCount()-1) {
return null;
}
switch (part) {
case AccessibleText.CHARACTER:
if (index == 0) {
return null;
}
try {
return getText(index-1, 1);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.WORD:
try {
String s = getText(0, getCharCount());
BreakIterator words = BreakIterator.getWordInstance(getLocale());
words.setText(s);
int end = words.following(index);
end = words.previous();
int start = words.previous();
if (start == BreakIterator.DONE) {
return null;
}
return s.substring(start, end);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.SENTENCE:
try {
String s = getText(0, getCharCount());
BreakIterator sentence =
BreakIterator.getSentenceInstance(getLocale());
sentence.setText(s);
int end = sentence.following(index);
end = sentence.previous();
int start = sentence.previous();
if (start == BreakIterator.DONE) {
return null;
}
return s.substring(start, end);
} catch (BadLocationException e) {
return null;
}
default:
return null;
}
}
/** {@collect.stats}
* Return the AttributeSet for a given character at a given index
*
* @param i the zero-based index into the text
* @return the AttributeSet of the character
* @since 1.3
*/
public AttributeSet getCharacterAttribute(int i) {
View view = (View) JLabel.this.getClientProperty("html");
if (view != null) {
Document d = view.getDocument();
if (d instanceof StyledDocument) {
StyledDocument doc = (StyledDocument)d;
Element elem = doc.getCharacterElement(i);
if (elem != null) {
return elem.getAttributes();
}
}
}
return null;
}
/** {@collect.stats}
* Returns the start offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
*
* @return the index into the text of the start of the selection
* @since 1.3
*/
public int getSelectionStart() {
// Text cannot be selected.
return -1;
}
/** {@collect.stats}
* Returns the end offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
*
* @return the index into teh text of the end of the selection
* @since 1.3
*/
public int getSelectionEnd() {
// Text cannot be selected.
return -1;
}
/** {@collect.stats}
* Returns the portion of the text that is selected.
*
* @return the String portion of the text that is selected
* @since 1.3
*/
public String getSelectedText() {
// Text cannot be selected.
return null;
}
/*
* Returns the text substring starting at the specified
* offset with the specified length.
*/
private String getText(int offset, int length)
throws BadLocationException {
View view = (View) JLabel.this.getClientProperty("html");
if (view != null) {
Document d = view.getDocument();
if (d instanceof StyledDocument) {
StyledDocument doc = (StyledDocument)d;
return doc.getText(offset, length);
}
}
return null;
}
/*
* Returns the bounding rectangle for the component text.
*/
private Rectangle getTextRectangle() {
String text = JLabel.this.getText();
Icon icon = (JLabel.this.isEnabled()) ? JLabel.this.getIcon() : JLabel.this.getDisabledIcon();
if ((icon == null) && (text == null)) {
return null;
}
Rectangle paintIconR = new Rectangle();
Rectangle paintTextR = new Rectangle();
Rectangle paintViewR = new Rectangle();
Insets paintViewInsets = new Insets(0, 0, 0, 0);
paintViewInsets = JLabel.this.getInsets(paintViewInsets);
paintViewR.x = paintViewInsets.left;
paintViewR.y = paintViewInsets.top;
paintViewR.width = JLabel.this.getWidth() - (paintViewInsets.left + paintViewInsets.right);
paintViewR.height = JLabel.this.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
String clippedText = SwingUtilities.layoutCompoundLabel(
(JComponent)JLabel.this,
getFontMetrics(getFont()),
text,
icon,
JLabel.this.getVerticalAlignment(),
JLabel.this.getHorizontalAlignment(),
JLabel.this.getVerticalTextPosition(),
JLabel.this.getHorizontalTextPosition(),
paintViewR,
paintIconR,
paintTextR,
JLabel.this.getIconTextGap());
return paintTextR;
}
// ----- AccessibleExtendedComponent
/** {@collect.stats}
* Returns the AccessibleExtendedComponent
*
* @return the AccessibleExtendedComponent
*/
AccessibleExtendedComponent getAccessibleExtendedComponent() {
return this;
}
/** {@collect.stats}
* Returns the tool tip text
*
* @return the tool tip text, if supported, of the object;
* otherwise, null
* @since 1.4
*/
public String getToolTipText() {
return JLabel.this.getToolTipText();
}
/** {@collect.stats}
* Returns the titled border text
*
* @return the titled border text, if supported, of the object;
* otherwise, null
* @since 1.4
*/
public String getTitledBorderText() {
return super.getTitledBorderText();
}
/** {@collect.stats}
* Returns key bindings associated with this object
*
* @return the key bindings, if supported, of the object;
* otherwise, null
* @see AccessibleKeyBinding
* @since 1.4
*/
public AccessibleKeyBinding getAccessibleKeyBinding() {
int mnemonic = JLabel.this.getDisplayedMnemonic();
if (mnemonic == 0) {
return null;
}
return new LabelKeyBinding(mnemonic);
}
class LabelKeyBinding implements AccessibleKeyBinding {
int mnemonic;
LabelKeyBinding(int mnemonic) {
this.mnemonic = mnemonic;
}
/** {@collect.stats}
* Returns the number of key bindings for this object
*
* @return the zero-based number of key bindings for this object
*/
public int getAccessibleKeyBindingCount() {
return 1;
}
/** {@collect.stats}
* Returns a key binding for this object. The value returned is an
* java.lang.Object which must be cast to appropriate type depending
* on the underlying implementation of the key. For example, if the
* Object returned is a javax.swing.KeyStroke, the user of this
* method should do the following:
* <nf><code>
* Component c = <get the component that has the key bindings>
* AccessibleContext ac = c.getAccessibleContext();
* AccessibleKeyBinding akb = ac.getAccessibleKeyBinding();
* for (int i = 0; i < akb.getAccessibleKeyBindingCount(); i++) {
* Object o = akb.getAccessibleKeyBinding(i);
* if (o instanceof javax.swing.KeyStroke) {
* javax.swing.KeyStroke keyStroke = (javax.swing.KeyStroke)o;
* <do something with the key binding>
* }
* }
* </code></nf>
*
* @param i zero-based index of the key bindings
* @return a javax.lang.Object which specifies the key binding
* @exception IllegalArgumentException if the index is
* out of bounds
* @see #getAccessibleKeyBindingCount
*/
public java.lang.Object getAccessibleKeyBinding(int i) {
if (i != 0) {
throw new IllegalArgumentException();
}
return KeyStroke.getKeyStroke(mnemonic, 0);
}
}
} // AccessibleJComponent
}
|
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.awt.event.*;
import java.awt.Component;
import java.awt.Container;
import java.awt.Window;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.io.Serializable;
/** {@collect.stats}
* @author Dave Moore
*/
class AncestorNotifier implements ComponentListener, PropertyChangeListener, Serializable
{
Component firstInvisibleAncestor;
EventListenerList listenerList = new EventListenerList();
JComponent root;
AncestorNotifier(JComponent root) {
this.root = root;
addListeners(root, true);
}
void addAncestorListener(AncestorListener l) {
listenerList.add(AncestorListener.class, l);
}
void removeAncestorListener(AncestorListener l) {
listenerList.remove(AncestorListener.class, l);
}
AncestorListener[] getAncestorListeners() {
return (AncestorListener[])listenerList.getListeners(AncestorListener.class);
}
/** {@collect.stats}
* 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.
* @see EventListenerList
*/
protected void fireAncestorAdded(JComponent source, int id, Container ancestor, Container ancestorParent) {
// 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]==AncestorListener.class) {
// Lazily create the event:
AncestorEvent ancestorEvent =
new AncestorEvent(source, id, ancestor, ancestorParent);
((AncestorListener)listeners[i+1]).ancestorAdded(ancestorEvent);
}
}
}
/** {@collect.stats}
* 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.
* @see EventListenerList
*/
protected void fireAncestorRemoved(JComponent source, int id, Container ancestor, Container ancestorParent) {
// 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]==AncestorListener.class) {
// Lazily create the event:
AncestorEvent ancestorEvent =
new AncestorEvent(source, id, ancestor, ancestorParent);
((AncestorListener)listeners[i+1]).ancestorRemoved(ancestorEvent);
}
}
}
/** {@collect.stats}
* 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.
* @see EventListenerList
*/
protected void fireAncestorMoved(JComponent source, int id, Container ancestor, Container ancestorParent) {
// 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]==AncestorListener.class) {
// Lazily create the event:
AncestorEvent ancestorEvent =
new AncestorEvent(source, id, ancestor, ancestorParent);
((AncestorListener)listeners[i+1]).ancestorMoved(ancestorEvent);
}
}
}
void removeAllListeners() {
removeListeners(root);
}
void addListeners(Component ancestor, boolean addToFirst) {
Component a;
firstInvisibleAncestor = null;
for (a = ancestor;
firstInvisibleAncestor == null;
a = a.getParent()) {
if (addToFirst || a != ancestor) {
a.addComponentListener(this);
if (a instanceof JComponent) {
JComponent jAncestor = (JComponent)a;
jAncestor.addPropertyChangeListener(this);
}
}
if (!a.isVisible() || a.getParent() == null || a instanceof Window) {
firstInvisibleAncestor = a;
}
}
if (firstInvisibleAncestor instanceof Window &&
firstInvisibleAncestor.isVisible()) {
firstInvisibleAncestor = null;
}
}
void removeListeners(Component ancestor) {
Component a;
for (a = ancestor; a != null; a = a.getParent()) {
a.removeComponentListener(this);
if (a instanceof JComponent) {
JComponent jAncestor = (JComponent)a;
jAncestor.removePropertyChangeListener(this);
}
if (a == firstInvisibleAncestor || a instanceof Window) {
break;
}
}
}
public void componentResized(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {
Component source = e.getComponent();
fireAncestorMoved(root, AncestorEvent.ANCESTOR_MOVED,
(Container)source, source.getParent());
}
public void componentShown(ComponentEvent e) {
Component ancestor = e.getComponent();
if (ancestor == firstInvisibleAncestor) {
addListeners(ancestor, false);
if (firstInvisibleAncestor == null) {
fireAncestorAdded(root, AncestorEvent.ANCESTOR_ADDED,
(Container)ancestor, ancestor.getParent());
}
}
}
public void componentHidden(ComponentEvent e) {
Component ancestor = e.getComponent();
boolean needsNotify = firstInvisibleAncestor == null;
if ( !(ancestor instanceof Window) ) {
removeListeners(ancestor.getParent());
}
firstInvisibleAncestor = ancestor;
if (needsNotify) {
fireAncestorRemoved(root, AncestorEvent.ANCESTOR_REMOVED,
(Container)ancestor, ancestor.getParent());
}
}
public void propertyChange(PropertyChangeEvent evt) {
String s = evt.getPropertyName();
if (s!=null && (s.equals("parent") || s.equals("ancestor"))) {
JComponent component = (JComponent)evt.getSource();
if (evt.getNewValue() != null) {
if (component == firstInvisibleAncestor) {
addListeners(component, false);
if (firstInvisibleAncestor == null) {
fireAncestorAdded(root, AncestorEvent.ANCESTOR_ADDED,
component, component.getParent());
}
}
} else {
boolean needsNotify = firstInvisibleAncestor == null;
Container oldParent = (Container)evt.getOldValue();
removeListeners(oldParent);
firstInvisibleAncestor = component;
if (needsNotify) {
fireAncestorRemoved(root, AncestorEvent.ANCESTOR_REMOVED,
component, oldParent);
}
}
}
}
}
|
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;
/** {@collect.stats}
* An interface used to tag heavy weight components that we want processed
* by Swing's RepaintManager.
*
* @author Scott Violet
*/
interface SwingHeavyWeight {
}
|
Java
|
/*
* Copyright (c) 1999, 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.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Set;
/** {@collect.stats}
* <code>InputMap</code> provides a binding between an input event
* (currently only <code>KeyStroke</code>s are used)
* and an <code>Object</code>. <code>InputMap</code>s
* are usually used with an <code>ActionMap</code>,
* to determine an <code>Action</code> to perform
* when a key is pressed.
* An <code>InputMap</code> can have a parent
* that is searched for bindings not defined in the <code>InputMap</code>.
* <p>As with <code>ActionMap</code> if you create a cycle, eg:
* <pre>
* InputMap am = new InputMap();
* InputMap bm = new InputMap():
* am.setParent(bm);
* bm.setParent(am);
* </pre>
* some of the methods will cause a StackOverflowError to be thrown.
*
* @author Scott Violet
* @since 1.3
*/
public class InputMap implements Serializable {
/** {@collect.stats} Handles the mapping between KeyStroke and Action name. */
private transient ArrayTable arrayTable;
/** {@collect.stats} Parent that handles any bindings we don't contain. */
private InputMap parent;
/** {@collect.stats}
* Creates an <code>InputMap</code> with no parent and no mappings.
*/
public InputMap() {
}
/** {@collect.stats}
* Sets this <code>InputMap</code>'s parent.
*
* @param map the <code>InputMap</code> that is the parent of this one
*/
public void setParent(InputMap map) {
this.parent = map;
}
/** {@collect.stats}
* Gets this <code>InputMap</code>'s parent.
*
* @return map the <code>InputMap</code> that is the parent of this one,
* or null if this <code>InputMap</code> has no parent
*/
public InputMap getParent() {
return parent;
}
/** {@collect.stats}
* Adds a binding for <code>keyStroke</code> to <code>actionMapKey</code>.
* If <code>actionMapKey</code> is null, this removes the current binding
* for <code>keyStroke</code>.
*/
public void put(KeyStroke keyStroke, Object actionMapKey) {
if (keyStroke == null) {
return;
}
if (actionMapKey == null) {
remove(keyStroke);
}
else {
if (arrayTable == null) {
arrayTable = new ArrayTable();
}
arrayTable.put(keyStroke, actionMapKey);
}
}
/** {@collect.stats}
* Returns the binding for <code>keyStroke</code>, messaging the
* parent <code>InputMap</code> if the binding is not locally defined.
*/
public Object get(KeyStroke keyStroke) {
if (arrayTable == null) {
InputMap parent = getParent();
if (parent != null) {
return parent.get(keyStroke);
}
return null;
}
Object value = arrayTable.get(keyStroke);
if (value == null) {
InputMap parent = getParent();
if (parent != null) {
return parent.get(keyStroke);
}
}
return value;
}
/** {@collect.stats}
* Removes the binding for <code>key</code> from this
* <code>InputMap</code>.
*/
public void remove(KeyStroke key) {
if (arrayTable != null) {
arrayTable.remove(key);
}
}
/** {@collect.stats}
* Removes all the mappings from this <code>InputMap</code>.
*/
public void clear() {
if (arrayTable != null) {
arrayTable.clear();
}
}
/** {@collect.stats}
* Returns the <code>KeyStroke</code>s that are bound in this <code>InputMap</code>.
*/
public KeyStroke[] keys() {
if (arrayTable == null) {
return null;
}
KeyStroke[] keys = new KeyStroke[arrayTable.size()];
arrayTable.getKeys(keys);
return keys;
}
/** {@collect.stats}
* Returns the number of <code>KeyStroke</code> bindings.
*/
public int size() {
if (arrayTable == null) {
return 0;
}
return arrayTable.size();
}
/** {@collect.stats}
* Returns an array of the <code>KeyStroke</code>s defined in this
* <code>InputMap</code> and its parent. This differs from <code>keys()</code> in that
* this method includes the keys defined in the parent.
*/
public KeyStroke[] allKeys() {
int count = size();
InputMap parent = getParent();
if (count == 0) {
if (parent != null) {
return parent.allKeys();
}
return keys();
}
if (parent == null) {
return keys();
}
KeyStroke[] keys = keys();
KeyStroke[] pKeys = parent.allKeys();
if (pKeys == null) {
return keys;
}
if (keys == null) {
// Should only happen if size() != keys.length, which should only
// happen if mutated from multiple threads (or a bogus subclass).
return pKeys;
}
HashMap keyMap = new HashMap();
int counter;
for (counter = keys.length - 1; counter >= 0; counter--) {
keyMap.put(keys[counter], keys[counter]);
}
for (counter = pKeys.length - 1; counter >= 0; counter--) {
keyMap.put(pKeys[counter], pKeys[counter]);
}
KeyStroke[] allKeys = new KeyStroke[keyMap.size()];
return (KeyStroke[])keyMap.keySet().toArray(allKeys);
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
ArrayTable.writeArrayTable(s, arrayTable);
}
private void readObject(ObjectInputStream s) throws ClassNotFoundException,
IOException {
s.defaultReadObject();
for (int counter = s.readInt() - 1; counter >= 0; counter--) {
put((KeyStroke)s.readObject(), s.readObject());
}
}
}
|
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;
import java.awt.Graphics;
import java.awt.Component;
/** {@collect.stats}
* A small fixed size picture, typically used to decorate components.
*
* @see ImageIcon
*/
public interface Icon
{
/** {@collect.stats}
* Draw the icon at the specified location. Icon implementations
* may use the Component argument to get properties useful for
* painting, e.g. the foreground or background color.
*/
void paintIcon(Component c, Graphics g, int x, int y);
/** {@collect.stats}
* Returns the icon's width.
*
* @return an int specifying the fixed width of the icon.
*/
int getIconWidth();
/** {@collect.stats}
* Returns the icon's height.
*
* @return an int specifying the fixed height of the icon.
*/
int getIconHeight();
}
|
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.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;
import java.awt.Frame;
import java.awt.Point;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.Window;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Vector;
import javax.swing.plaf.OptionPaneUI;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameAdapter;
import javax.accessibility.*;
import static javax.swing.ClientPropertyKey.PopupFactory_FORCE_HEAVYWEIGHT_POPUP;
/** {@collect.stats}
* <code>JOptionPane</code> makes it easy to pop up a standard dialog box that
* prompts users for a value or informs them of something.
* For information about using <code>JOptionPane</code>, see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html">How to Make Dialogs</a>,
* a section in <em>The Java Tutorial</em>.
*
* <p>
*
* While the <code>JOptionPane</code>
* class may appear complex because of the large number of methods, almost
* all uses of this class are one-line calls to one of the static
* <code>showXxxDialog</code> methods shown below:
* <blockquote>
*
*
* <table border=1 summary="Common JOptionPane method names and their descriptions">
* <tr>
* <th>Method Name</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>showConfirmDialog</td>
* <td>Asks a confirming question, like yes/no/cancel.</td>
* </tr>
* <tr>
* <td>showInputDialog</td>
* <td>Prompt for some input.</td>
* </tr>
* <tr>
* <td>showMessageDialog</td>
* <td>Tell the user about something that has happened.</td>
* </tr>
* <tr>
* <td>showOptionDialog</td>
* <td>The Grand Unification of the above three.</td>
* </tr>
* </table>
*
* </blockquote>
* Each of these methods also comes in a <code>showInternalXXX</code>
* flavor, which uses an internal frame to hold the dialog box (see
* {@link JInternalFrame}).
* Multiple convenience methods have also been defined -- overloaded
* versions of the basic methods that use different parameter lists.
* <p>
* All dialogs are modal. Each <code>showXxxDialog</code> method blocks
* the caller until the user's interaction is complete.
* <p>
*
* <table cellspacing=6 cellpadding=4 border=0 align=right summary="layout">
* <tr>
* <td bgcolor=#FFe0d0 rowspan=2>icon</td>
* <td bgcolor=#FFe0d0>message</td>
* </tr>
* <tr>
* <td bgcolor=#FFe0d0>input value</td>
* </tr>
* <tr>
* <td bgcolor=#FFe0d0 colspan=2>option buttons</td>
* </tr>
* </table>
*
* The basic appearance of one of these dialog boxes is generally
* similar to the picture at the right, although the various
* look-and-feels are
* ultimately responsible for the final result. In particular, the
* look-and-feels will adjust the layout to accommodate the option pane's
* <code>ComponentOrientation</code> property.
* <br clear=all>
* <p>
* <b>Parameters:</b><br>
* The parameters to these methods follow consistent patterns:
* <blockquote>
* <dl compact>
* <dt>parentComponent<dd>
* Defines the <code>Component</code> that is to be the parent of this
* dialog box.
* It is used in two ways: the <code>Frame</code> that contains
* it is used as the <code>Frame</code>
* parent for the dialog box, and its screen coordinates are used in
* the placement of the dialog box. In general, the dialog box is placed
* just below the component. This parameter may be <code>null</code>,
* in which case a default <code>Frame</code> is used as the parent,
* and the dialog will be
* centered on the screen (depending on the L&F).
* <dt><a name=message>message</a><dd>
* A descriptive message to be placed in the dialog box.
* In the most common usage, message is just a <code>String</code> or
* <code>String</code> constant.
* However, the type of this parameter is actually <code>Object</code>. Its
* interpretation depends on its type:
* <dl compact>
* <dt>Object[]<dd>An array of objects is interpreted as a series of
* messages (one per object) arranged in a vertical stack.
* The interpretation is recursive -- each object in the
* array is interpreted according to its type.
* <dt>Component<dd>The <code>Component</code> is displayed in the dialog.
* <dt>Icon<dd>The <code>Icon</code> is wrapped in a <code>JLabel</code>
* and displayed in the dialog.
* <dt>others<dd>The object is converted to a <code>String</code> by calling
* its <code>toString</code> method. The result is wrapped in a
* <code>JLabel</code> and displayed.
* </dl>
* <dt>messageType<dd>Defines the style of the message. The Look and Feel
* manager may lay out the dialog differently depending on this value, and
* will often provide a default icon. The possible values are:
* <ul>
* <li><code>ERROR_MESSAGE</code>
* <li><code>INFORMATION_MESSAGE</code>
* <li><code>WARNING_MESSAGE</code>
* <li><code>QUESTION_MESSAGE</code>
* <li><code>PLAIN_MESSAGE</code>
* </ul>
* <dt>optionType<dd>Defines the set of option buttons that appear at
* the bottom of the dialog box:
* <ul>
* <li><code>DEFAULT_OPTION</code>
* <li><code>YES_NO_OPTION</code>
* <li><code>YES_NO_CANCEL_OPTION</code>
* <li><code>OK_CANCEL_OPTION</code>
* </ul>
* You aren't limited to this set of option buttons. You can provide any
* buttons you want using the options parameter.
* <dt>options<dd>A more detailed description of the set of option buttons
* that will appear at the bottom of the dialog box.
* The usual value for the options parameter is an array of
* <code>String</code>s. But
* the parameter type is an array of <code>Objects</code>.
* A button is created for each object depending on its type:
* <dl compact>
* <dt>Component<dd>The component is added to the button row directly.
* <dt>Icon<dd>A <code>JButton</code> is created with this as its label.
* <dt>other<dd>The <code>Object</code> is converted to a string using its
* <code>toString</code> method and the result is used to
* label a <code>JButton</code>.
* </dl>
* <dt>icon<dd>A decorative icon to be placed in the dialog box. A default
* value for this is determined by the <code>messageType</code> parameter.
* <dt>title<dd>The title for the dialog box.
* <dt>initialValue<dd>The default selection (input value).
* </dl>
* </blockquote>
* <p>
* When the selection is changed, <code>setValue</code> is invoked,
* which generates a <code>PropertyChangeEvent</code>.
* <p>
* If a <code>JOptionPane</code> has configured to all input
* <code>setWantsInput</code>
* the bound property <code>JOptionPane.INPUT_VALUE_PROPERTY</code>
* can also be listened
* to, to determine when the user has input or selected a value.
* <p>
* When one of the <code>showXxxDialog</code> methods returns an integer,
* the possible values are:
* <ul>
* <li><code>YES_OPTION</code>
* <li><code>NO_OPTION</code>
* <li><code>CANCEL_OPTION</code>
* <li><code>OK_OPTION</code>
* <li><code>CLOSED_OPTION</code>
* </ul>
* <b>Examples:</b>
* <dl>
* <dt>Show an error dialog that displays the message, 'alert':
* <dd><code>
* JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
* </code><p>
* <dt>Show an internal information dialog with the message, 'information':
* <dd><code>
* JOptionPane.showInternalMessageDialog(frame, "information",<br>
* <ul><ul>"information", JOptionPane.INFORMATION_MESSAGE);</ul></ul>
* </code><p>
* <dt>Show an information panel with the options yes/no and message 'choose one':
* <dd><code>JOptionPane.showConfirmDialog(null,
* <ul><ul>"choose one", "choose one", JOptionPane.YES_NO_OPTION);</ul></ul>
* </code><p>
* <dt>Show an internal information dialog with the options yes/no/cancel and
* message 'please choose one' and title information:
* <dd><code>JOptionPane.showInternalConfirmDialog(frame,
* <ul><ul>"please choose one", "information",</ul></ul>
* <ul><ul>JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);</ul></ul>
* </code><p>
* <dt>Show a warning dialog with the options OK, CANCEL, title 'Warning', and
* message 'Click OK to continue':
* <dd><code>
* Object[] options = { "OK", "CANCEL" };<br>
* JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",
* <ul><ul>JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,</ul></ul>
* <ul><ul>null, options, options[0]);</ul></ul>
* </code><p>
* <dt>Show a dialog asking the user to type in a String:
* <dd><code>
* String inputValue = JOptionPane.showInputDialog("Please input a value");
* </code><p>
* <dt>Show a dialog asking the user to select a String:
* <dd><code>
* Object[] possibleValues = { "First", "Second", "Third" };<br>
* Object selectedValue = JOptionPane.showInputDialog(null,
* <ul><ul>"Choose one", "Input",</ul></ul>
* <ul><ul>JOptionPane.INFORMATION_MESSAGE, null,</ul></ul>
* <ul><ul>possibleValues, possibleValues[0]);</ul></ul>
* </code><p>
* </dl>
* <b>Direct Use:</b><br>
* To create and use an <code>JOptionPane</code> directly, the
* standard pattern is roughly as follows:
* <pre>
* JOptionPane pane = new JOptionPane(<i>arguments</i>);
* pane.set<i>.Xxxx(...); // Configure</i>
* JDialog dialog = pane.createDialog(<i>parentComponent, title</i>);
* dialog.show();
* Object selectedValue = pane.getValue();
* if(selectedValue == null)
* return CLOSED_OPTION;
* <i>//If there is <b>not</b> an array of option buttons:</i>
* if(options == null) {
* if(selectedValue instanceof Integer)
* return ((Integer)selectedValue).intValue();
* return CLOSED_OPTION;
* }
* <i>//If there is an array of option buttons:</i>
* for(int counter = 0, maxCounter = options.length;
* counter < maxCounter; counter++) {
* if(options[counter].equals(selectedValue))
* return counter;
* }
* return CLOSED_OPTION;
* </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}.
*
* @see JInternalFrame
*
* @beaninfo
* attribute: isContainer true
* description: A component which implements standard dialog box controls.
*
* @author James Gosling
* @author Scott Violet
*/
public class JOptionPane extends JComponent implements Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "OptionPaneUI";
/** {@collect.stats}
* Indicates that the user has not yet selected a value.
*/
public static final Object UNINITIALIZED_VALUE = "uninitializedValue";
//
// Option types
//
/** {@collect.stats}
* Type meaning Look and Feel should not supply any options -- only
* use the options from the <code>JOptionPane</code>.
*/
public static final int DEFAULT_OPTION = -1;
/** {@collect.stats} Type used for <code>showConfirmDialog</code>. */
public static final int YES_NO_OPTION = 0;
/** {@collect.stats} Type used for <code>showConfirmDialog</code>. */
public static final int YES_NO_CANCEL_OPTION = 1;
/** {@collect.stats} Type used for <code>showConfirmDialog</code>. */
public static final int OK_CANCEL_OPTION = 2;
//
// Return values.
//
/** {@collect.stats} Return value from class method if YES is chosen. */
public static final int YES_OPTION = 0;
/** {@collect.stats} Return value from class method if NO is chosen. */
public static final int NO_OPTION = 1;
/** {@collect.stats} Return value from class method if CANCEL is chosen. */
public static final int CANCEL_OPTION = 2;
/** {@collect.stats} Return value form class method if OK is chosen. */
public static final int OK_OPTION = 0;
/** {@collect.stats} Return value from class method if user closes window without selecting
* anything, more than likely this should be treated as either a
* <code>CANCEL_OPTION</code> or <code>NO_OPTION</code>. */
public static final int CLOSED_OPTION = -1;
//
// Message types. Used by the UI to determine what icon to display,
// and possibly what behavior to give based on the type.
//
/** {@collect.stats} Used for error messages. */
public static final int ERROR_MESSAGE = 0;
/** {@collect.stats} Used for information messages. */
public static final int INFORMATION_MESSAGE = 1;
/** {@collect.stats} Used for warning messages. */
public static final int WARNING_MESSAGE = 2;
/** {@collect.stats} Used for questions. */
public static final int QUESTION_MESSAGE = 3;
/** {@collect.stats} No icon is used. */
public static final int PLAIN_MESSAGE = -1;
/** {@collect.stats} Bound property name for <code>icon</code>. */
public static final String ICON_PROPERTY = "icon";
/** {@collect.stats} Bound property name for <code>message</code>. */
public static final String MESSAGE_PROPERTY = "message";
/** {@collect.stats} Bound property name for <code>value</code>. */
public static final String VALUE_PROPERTY = "value";
/** {@collect.stats} Bound property name for <code>option</code>. */
public static final String OPTIONS_PROPERTY = "options";
/** {@collect.stats} Bound property name for <code>initialValue</code>. */
public static final String INITIAL_VALUE_PROPERTY = "initialValue";
/** {@collect.stats} Bound property name for <code>type</code>. */
public static final String MESSAGE_TYPE_PROPERTY = "messageType";
/** {@collect.stats} Bound property name for <code>optionType</code>. */
public static final String OPTION_TYPE_PROPERTY = "optionType";
/** {@collect.stats} Bound property name for <code>selectionValues</code>. */
public static final String SELECTION_VALUES_PROPERTY = "selectionValues";
/** {@collect.stats} Bound property name for <code>initialSelectionValue</code>. */
public static final String INITIAL_SELECTION_VALUE_PROPERTY = "initialSelectionValue";
/** {@collect.stats} Bound property name for <code>inputValue</code>. */
public static final String INPUT_VALUE_PROPERTY = "inputValue";
/** {@collect.stats} Bound property name for <code>wantsInput</code>. */
public static final String WANTS_INPUT_PROPERTY = "wantsInput";
/** {@collect.stats} Icon used in pane. */
transient protected Icon icon;
/** {@collect.stats} Message to display. */
transient protected Object message;
/** {@collect.stats} Options to display to the user. */
transient protected Object[] options;
/** {@collect.stats} Value that should be initially selected in <code>options</code>. */
transient protected Object initialValue;
/** {@collect.stats} Message type. */
protected int messageType;
/** {@collect.stats}
* Option type, one of <code>DEFAULT_OPTION</code>,
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code> or
* <code>OK_CANCEL_OPTION</code>.
*/
protected int optionType;
/** {@collect.stats} Currently selected value, will be a valid option, or
* <code>UNINITIALIZED_VALUE</code> or <code>null</code>. */
transient protected Object value;
/** {@collect.stats} Array of values the user can choose from. Look and feel will
* provide the UI component to choose this from. */
protected transient Object[] selectionValues;
/** {@collect.stats} Value the user has input. */
protected transient Object inputValue;
/** {@collect.stats} Initial value to select in <code>selectionValues</code>. */
protected transient Object initialSelectionValue;
/** {@collect.stats} If true, a UI widget will be provided to the user to get input. */
protected boolean wantsInput;
/** {@collect.stats}
* Shows a question-message dialog requesting input from the user. The
* dialog uses the default frame, which usually means it is centered on
* the screen.
*
* @param message the <code>Object</code> to display
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static String showInputDialog(Object message)
throws HeadlessException {
return showInputDialog(null, message);
}
/** {@collect.stats}
* Shows a question-message dialog requesting input from the user, with
* the input value initialized to <code>initialSelectionValue</code>. The
* dialog uses the default frame, which usually means it is centered on
* the screen.
*
* @param message the <code>Object</code> to display
* @param initialSelectionValue the value used to initialize the input
* field
* @since 1.4
*/
public static String showInputDialog(Object message, Object initialSelectionValue) {
return showInputDialog(null, message, initialSelectionValue);
}
/** {@collect.stats}
* Shows a question-message dialog requesting input from the user
* parented to <code>parentComponent</code>.
* The dialog is displayed on top of the <code>Component</code>'s
* frame, and is usually positioned below the <code>Component</code>.
*
* @param parentComponent the parent <code>Component</code> for the
* dialog
* @param message the <code>Object</code> to display
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static String showInputDialog(Component parentComponent,
Object message) throws HeadlessException {
return showInputDialog(parentComponent, message, UIManager.getString(
"OptionPane.inputDialogTitle", parentComponent), QUESTION_MESSAGE);
}
/** {@collect.stats}
* Shows a question-message dialog requesting input from the user and
* parented to <code>parentComponent</code>. The input value will be
* initialized to <code>initialSelectionValue</code>.
* The dialog is displayed on top of the <code>Component</code>'s
* frame, and is usually positioned below the <code>Component</code>.
*
* @param parentComponent the parent <code>Component</code> for the
* dialog
* @param message the <code>Object</code> to display
* @param initialSelectionValue the value used to initialize the input
* field
* @since 1.4
*/
public static String showInputDialog(Component parentComponent, Object message,
Object initialSelectionValue) {
return (String)showInputDialog(parentComponent, message,
UIManager.getString("OptionPane.inputDialogTitle",
parentComponent), QUESTION_MESSAGE, null, null,
initialSelectionValue);
}
/** {@collect.stats}
* Shows a dialog requesting input from the user parented to
* <code>parentComponent</code> with the dialog having the title
* <code>title</code> and message type <code>messageType</code>.
*
* @param parentComponent the parent <code>Component</code> for the
* dialog
* @param message the <code>Object</code> to display
* @param title the <code>String</code> to display in the dialog
* title bar
* @param messageType the type of message that is to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static String showInputDialog(Component parentComponent,
Object message, String title, int messageType)
throws HeadlessException {
return (String)showInputDialog(parentComponent, message, title,
messageType, null, null, null);
}
/** {@collect.stats}
* Prompts the user for input in a blocking dialog where the
* initial selection, possible selections, and all other options can
* be specified. The user will able to choose from
* <code>selectionValues</code>, where <code>null</code> implies the
* user can input
* whatever they wish, usually by means of a <code>JTextField</code>.
* <code>initialSelectionValue</code> is the initial value to prompt
* the user with. It is up to the UI to decide how best to represent
* the <code>selectionValues</code>, but usually a
* <code>JComboBox</code>, <code>JList</code>, or
* <code>JTextField</code> will be used.
*
* @param parentComponent the parent <code>Component</code> for the
* dialog
* @param message the <code>Object</code> to display
* @param title the <code>String</code> to display in the
* dialog title bar
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param icon the <code>Icon</code> image to display
* @param selectionValues an array of <code>Object</code>s that
* gives the possible selections
* @param initialSelectionValue the value used to initialize the input
* field
* @return user's input, or <code>null</code> meaning the user
* canceled the input
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static Object showInputDialog(Component parentComponent,
Object message, String title, int messageType, Icon icon,
Object[] selectionValues, Object initialSelectionValue)
throws HeadlessException {
JOptionPane pane = new JOptionPane(message, messageType,
OK_CANCEL_OPTION, icon,
null, null);
pane.setWantsInput(true);
pane.setSelectionValues(selectionValues);
pane.setInitialSelectionValue(initialSelectionValue);
pane.setComponentOrientation(((parentComponent == null) ?
getRootFrame() : parentComponent).getComponentOrientation());
int style = styleFromMessageType(messageType);
JDialog dialog = pane.createDialog(parentComponent, title, style);
pane.selectInitialValue();
dialog.show();
dialog.dispose();
Object value = pane.getInputValue();
if (value == UNINITIALIZED_VALUE) {
return null;
}
return value;
}
/** {@collect.stats}
* Brings up an information-message dialog titled "Message".
*
* @param parentComponent determines the <code>Frame</code> in
* which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static void showMessageDialog(Component parentComponent,
Object message) throws HeadlessException {
showMessageDialog(parentComponent, message, UIManager.getString(
"OptionPane.messageDialogTitle", parentComponent),
INFORMATION_MESSAGE);
}
/** {@collect.stats}
* Brings up a dialog that displays a message using a default
* icon determined by the <code>messageType</code> parameter.
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static void showMessageDialog(Component parentComponent,
Object message, String title, int messageType)
throws HeadlessException {
showMessageDialog(parentComponent, message, title, messageType, null);
}
/** {@collect.stats}
* Brings up a dialog displaying a message, specifying all parameters.
*
* @param parentComponent determines the <code>Frame</code> in which the
* dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a
* default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param icon an icon to display in the dialog that helps the user
* identify the kind of message that is being displayed
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static void showMessageDialog(Component parentComponent,
Object message, String title, int messageType, Icon icon)
throws HeadlessException {
showOptionDialog(parentComponent, message, title, DEFAULT_OPTION,
messageType, icon, null, null);
}
/** {@collect.stats}
* Brings up a dialog with the options <i>Yes</i>,
* <i>No</i> and <i>Cancel</i>; with the
* title, <b>Select an Option</b>.
*
* @param parentComponent determines the <code>Frame</code> in which the
* dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a
* default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @return an integer indicating the option selected by the user
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static int showConfirmDialog(Component parentComponent,
Object message) throws HeadlessException {
return showConfirmDialog(parentComponent, message,
UIManager.getString("OptionPane.titleText"),
YES_NO_CANCEL_OPTION);
}
/** {@collect.stats}
* Brings up a dialog where the number of choices is determined
* by the <code>optionType</code> parameter.
*
* @param parentComponent determines the <code>Frame</code> in which the
* dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a
* default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param optionType an int designating the options available on the dialog:
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* or <code>OK_CANCEL_OPTION</code>
* @return an int indicating the option selected by the user
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType)
throws HeadlessException {
return showConfirmDialog(parentComponent, message, title, optionType,
QUESTION_MESSAGE);
}
/** {@collect.stats}
* Brings up a dialog where the number of choices is determined
* by the <code>optionType</code> parameter, where the
* <code>messageType</code>
* parameter determines the icon to display.
* The <code>messageType</code> parameter is primarily used to supply
* a default icon from the Look and Feel.
*
* @param parentComponent determines the <code>Frame</code> in
* which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a
* default <code>Frame</code> is used.
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param optionType an integer designating the options available
* on the dialog: <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* or <code>OK_CANCEL_OPTION</code>
* @param messageType an integer designating the kind of message this is;
* primarily used to determine the icon from the pluggable
* Look and Feel: <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @return an integer indicating the option selected by the user
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType, int messageType)
throws HeadlessException {
return showConfirmDialog(parentComponent, message, title, optionType,
messageType, null);
}
/** {@collect.stats}
* Brings up a dialog with a specified icon, where the number of
* choices is determined by the <code>optionType</code> parameter.
* The <code>messageType</code> parameter is primarily used to supply
* a default icon from the look and feel.
*
* @param parentComponent determines the <code>Frame</code> in which the
* dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a
* default <code>Frame</code> is used
* @param message the Object to display
* @param title the title string for the dialog
* @param optionType an int designating the options available on the dialog:
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* or <code>OK_CANCEL_OPTION</code>
* @param messageType an int designating the kind of message this is,
* primarily used to determine the icon from the pluggable
* Look and Feel: <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param icon the icon to display in the dialog
* @return an int indicating the option selected by the user
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType,
int messageType, Icon icon) throws HeadlessException {
return showOptionDialog(parentComponent, message, title, optionType,
messageType, icon, null, null);
}
/** {@collect.stats}
* Brings up a dialog with a specified icon, where the initial
* choice is determined by the <code>initialValue</code> parameter and
* the number of choices is determined by the <code>optionType</code>
* parameter.
* <p>
* If <code>optionType</code> is <code>YES_NO_OPTION</code>,
* or <code>YES_NO_CANCEL_OPTION</code>
* and the <code>options</code> parameter is <code>null</code>,
* then the options are
* supplied by the look and feel.
* <p>
* The <code>messageType</code> parameter is primarily used to supply
* a default icon from the look and feel.
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if
* <code>null</code>, or if the
* <code>parentComponent</code> has no
* <code>Frame</code>, a
* default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param optionType an integer designating the options available on the
* dialog: <code>DEFAULT_OPTION</code>,
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* or <code>OK_CANCEL_OPTION</code>
* @param messageType an integer designating the kind of message this is,
* primarily used to determine the icon from the
* pluggable Look and Feel: <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param icon the icon to display in the dialog
* @param options an array of objects indicating the possible choices
* the user can make; if the objects are components, they
* are rendered properly; non-<code>String</code>
* objects are
* rendered using their <code>toString</code> methods;
* if this parameter is <code>null</code>,
* the options are determined by the Look and Feel
* @param initialValue the object that represents the default selection
* for the dialog; only meaningful if <code>options</code>
* is used; can be <code>null</code>
* @return an integer indicating the option chosen by the user,
* or <code>CLOSED_OPTION</code> if the user closed
* the dialog
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static int showOptionDialog(Component parentComponent,
Object message, String title, int optionType, int messageType,
Icon icon, Object[] options, Object initialValue)
throws HeadlessException {
JOptionPane pane = new JOptionPane(message, messageType,
optionType, icon,
options, initialValue);
pane.setInitialValue(initialValue);
pane.setComponentOrientation(((parentComponent == null) ?
getRootFrame() : parentComponent).getComponentOrientation());
int style = styleFromMessageType(messageType);
JDialog dialog = pane.createDialog(parentComponent, title, style);
pane.selectInitialValue();
dialog.show();
dialog.dispose();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return CLOSED_OPTION;
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue).intValue();
return CLOSED_OPTION;
}
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return CLOSED_OPTION;
}
/** {@collect.stats}
* Creates and returns a new <code>JDialog</code> wrapping
* <code>this</code> centered on the <code>parentComponent</code>
* in the <code>parentComponent</code>'s frame.
* <code>title</code> is the title of the returned dialog.
* The returned <code>JDialog</code> will not be resizable by the
* user, however programs can invoke <code>setResizable</code> on
* the <code>JDialog</code> instance to change this property.
* The returned <code>JDialog</code> will be set up such that
* once it is closed, or the user clicks on one of the buttons,
* the optionpane's value property will be set accordingly and
* the dialog will be closed. Each time the dialog is made visible,
* it will reset the option pane's value property to
* <code>JOptionPane.UNINITIALIZED_VALUE</code> to ensure the
* user's subsequent action closes the dialog properly.
*
* @param parentComponent determines the frame in which the dialog
* is displayed; if the <code>parentComponent</code> has
* no <code>Frame</code>, a default <code>Frame</code> is used
* @param title the title string for the dialog
* @return a new <code>JDialog</code> containing this instance
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public JDialog createDialog(Component parentComponent, String title)
throws HeadlessException {
int style = styleFromMessageType(getMessageType());
return createDialog(parentComponent, title, style);
}
/** {@collect.stats}
* Creates and returns a new parentless <code>JDialog</code>
* with the specified title.
* The returned <code>JDialog</code> will not be resizable by the
* user, however programs can invoke <code>setResizable</code> on
* the <code>JDialog</code> instance to change this property.
* The returned <code>JDialog</code> will be set up such that
* once it is closed, or the user clicks on one of the buttons,
* the optionpane's value property will be set accordingly and
* the dialog will be closed. Each time the dialog is made visible,
* it will reset the option pane's value property to
* <code>JOptionPane.UNINITIALIZED_VALUE</code> to ensure the
* user's subsequent action closes the dialog properly.
*
* @param title the title string for the dialog
* @return a new <code>JDialog</code> containing this instance
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @since 1.6
*/
public JDialog createDialog(String title) throws HeadlessException {
int style = styleFromMessageType(getMessageType());
JDialog dialog = new JDialog((Dialog) null, title, true);
initDialog(dialog, style, null);
return dialog;
}
private JDialog createDialog(Component parentComponent, String title,
int style)
throws HeadlessException {
final JDialog dialog;
Window window = JOptionPane.getWindowForComponent(parentComponent);
if (window instanceof Frame) {
dialog = new JDialog((Frame)window, title, true);
} else {
dialog = new JDialog((Dialog)window, title, true);
}
if (window instanceof SwingUtilities.SharedOwnerFrame) {
WindowListener ownerShutdownListener =
(WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
dialog.addWindowListener(ownerShutdownListener);
}
initDialog(dialog, style, parentComponent);
return dialog;
}
private void initDialog(final JDialog dialog, int style, Component parentComponent) {
dialog.setComponentOrientation(this.getComponentOrientation());
Container contentPane = dialog.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(this, BorderLayout.CENTER);
dialog.setResizable(false);
if (JDialog.isDefaultLookAndFeelDecorated()) {
boolean supportsWindowDecorations =
UIManager.getLookAndFeel().getSupportsWindowDecorations();
if (supportsWindowDecorations) {
dialog.setUndecorated(true);
getRootPane().setWindowDecorationStyle(style);
}
}
dialog.pack();
dialog.setLocationRelativeTo(parentComponent);
WindowAdapter adapter = new WindowAdapter() {
private boolean gotFocus = false;
public void windowClosing(WindowEvent we) {
setValue(null);
}
public void windowGainedFocus(WindowEvent we) {
// Once window gets focus, set initial focus
if (!gotFocus) {
selectInitialValue();
gotFocus = true;
}
}
};
dialog.addWindowListener(adapter);
dialog.addWindowFocusListener(adapter);
dialog.addComponentListener(new ComponentAdapter() {
public void componentShown(ComponentEvent ce) {
// reset value to ensure closing works properly
setValue(JOptionPane.UNINITIALIZED_VALUE);
}
});
addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
// Let the defaultCloseOperation handle the closing
// if the user closed the window without selecting a button
// (newValue = null in that case). Otherwise, close the dialog.
if (dialog.isVisible() && event.getSource() == JOptionPane.this &&
(event.getPropertyName().equals(VALUE_PROPERTY) ||
event.getPropertyName().equals(INPUT_VALUE_PROPERTY)) &&
event.getNewValue() != null &&
event.getNewValue() != JOptionPane.UNINITIALIZED_VALUE) {
dialog.setVisible(false);
}
}
});
}
/** {@collect.stats}
* Brings up an internal confirmation dialog panel. The dialog
* is a information-message dialog titled "Message".
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the object to display
*/
public static void showInternalMessageDialog(Component parentComponent,
Object message) {
showInternalMessageDialog(parentComponent, message, UIManager.
getString("OptionPane.messageDialogTitle",
parentComponent), INFORMATION_MESSAGE);
}
/** {@collect.stats}
* Brings up an internal dialog panel that displays a message
* using a default icon determined by the <code>messageType</code>
* parameter.
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
*/
public static void showInternalMessageDialog(Component parentComponent,
Object message, String title,
int messageType) {
showInternalMessageDialog(parentComponent, message, title, messageType,null);
}
/** {@collect.stats}
* Brings up an internal dialog panel displaying a message,
* specifying all parameters.
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param icon an icon to display in the dialog that helps the user
* identify the kind of message that is being displayed
*/
public static void showInternalMessageDialog(Component parentComponent,
Object message,
String title, int messageType,
Icon icon){
showInternalOptionDialog(parentComponent, message, title, DEFAULT_OPTION,
messageType, icon, null, null);
}
/** {@collect.stats}
* Brings up an internal dialog panel with the options <i>Yes</i>, <i>No</i>
* and <i>Cancel</i>; with the title, <b>Select an Option</b>.
*
* @param parentComponent determines the <code>Frame</code> in
* which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @return an integer indicating the option selected by the user
*/
public static int showInternalConfirmDialog(Component parentComponent,
Object message) {
return showInternalConfirmDialog(parentComponent, message,
UIManager.getString("OptionPane.titleText"),
YES_NO_CANCEL_OPTION);
}
/** {@collect.stats}
* Brings up a internal dialog panel where the number of choices
* is determined by the <code>optionType</code> parameter.
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the object to display in the dialog; a
* <code>Component</code> object is rendered as a
* <code>Component</code>; a <code>String</code>
* object is rendered as a string; other objects
* are converted to a <code>String</code> using the
* <code>toString</code> method
* @param title the title string for the dialog
* @param optionType an integer designating the options
* available on the dialog: <code>YES_NO_OPTION</code>,
* or <code>YES_NO_CANCEL_OPTION</code>
* @return an integer indicating the option selected by the user
*/
public static int showInternalConfirmDialog(Component parentComponent,
Object message, String title,
int optionType) {
return showInternalConfirmDialog(parentComponent, message, title, optionType,
QUESTION_MESSAGE);
}
/** {@collect.stats}
* Brings up an internal dialog panel where the number of choices
* is determined by the <code>optionType</code> parameter, where
* the <code>messageType</code> parameter determines the icon to display.
* The <code>messageType</code> parameter is primarily used to supply
* a default icon from the Look and Feel.
*
* @param parentComponent determines the <code>Frame</code> in
* which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the object to display in the dialog; a
* <code>Component</code> object is rendered as a
* <code>Component</code>; a <code>String</code>
* object is rendered as a string; other objects are
* converted to a <code>String</code> using the
* <code>toString</code> method
* @param title the title string for the dialog
* @param optionType an integer designating the options
* available on the dialog:
* <code>YES_NO_OPTION</code>, or <code>YES_NO_CANCEL_OPTION</code>
* @param messageType an integer designating the kind of message this is,
* primarily used to determine the icon from the
* pluggable Look and Feel: <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>, <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @return an integer indicating the option selected by the user
*/
public static int showInternalConfirmDialog(Component parentComponent,
Object message,
String title, int optionType,
int messageType) {
return showInternalConfirmDialog(parentComponent, message, title, optionType,
messageType, null);
}
/** {@collect.stats}
* Brings up an internal dialog panel with a specified icon, where
* the number of choices is determined by the <code>optionType</code>
* parameter.
* The <code>messageType</code> parameter is primarily used to supply
* a default icon from the look and feel.
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if <code>null</code>,
* or if the parentComponent has no Frame, a
* default <code>Frame</code> is used
* @param message the object to display in the dialog; a
* <code>Component</code> object is rendered as a
* <code>Component</code>; a <code>String</code>
* object is rendered as a string; other objects are
* converted to a <code>String</code> using the
* <code>toString</code> method
* @param title the title string for the dialog
* @param optionType an integer designating the options available
* on the dialog:
* <code>YES_NO_OPTION</code>, or
* <code>YES_NO_CANCEL_OPTION</code>.
* @param messageType an integer designating the kind of message this is,
* primarily used to determine the icon from the pluggable
* Look and Feel: <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>, <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param icon the icon to display in the dialog
* @return an integer indicating the option selected by the user
*/
public static int showInternalConfirmDialog(Component parentComponent,
Object message,
String title, int optionType,
int messageType, Icon icon) {
return showInternalOptionDialog(parentComponent, message, title, optionType,
messageType, icon, null, null);
}
/** {@collect.stats}
* Brings up an internal dialog panel with a specified icon, where
* the initial choice is determined by the <code>initialValue</code>
* parameter and the number of choices is determined by the
* <code>optionType</code> parameter.
* <p>
* If <code>optionType</code> is <code>YES_NO_OPTION</code>, or
* <code>YES_NO_CANCEL_OPTION</code>
* and the <code>options</code> parameter is <code>null</code>,
* then the options are supplied by the Look and Feel.
* <p>
* The <code>messageType</code> parameter is primarily used to supply
* a default icon from the look and feel.
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the object to display in the dialog; a
* <code>Component</code> object is rendered as a
* <code>Component</code>; a <code>String</code>
* object is rendered as a string. Other objects are
* converted to a <code>String</code> using the
* <code>toString</code> method
* @param title the title string for the dialog
* @param optionType an integer designating the options available
* on the dialog: <code>YES_NO_OPTION</code>,
* or <code>YES_NO_CANCEL_OPTION</code>
* @param messageType an integer designating the kind of message this is;
* primarily used to determine the icon from the
* pluggable Look and Feel: <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>, <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param icon the icon to display in the dialog
* @param options an array of objects indicating the possible choices
* the user can make; if the objects are components, they
* are rendered properly; non-<code>String</code>
* objects are rendered using their <code>toString</code>
* methods; if this parameter is <code>null</code>,
* the options are determined by the Look and Feel
* @param initialValue the object that represents the default selection
* for the dialog; only meaningful if <code>options</code>
* is used; can be <code>null</code>
* @return an integer indicating the option chosen by the user,
* or <code>CLOSED_OPTION</code> if the user closed the Dialog
*/
public static int showInternalOptionDialog(Component parentComponent,
Object message,
String title, int optionType,
int messageType, Icon icon,
Object[] options, Object initialValue) {
JOptionPane pane = new JOptionPane(message, messageType,
optionType, icon, options, initialValue);
pane.putClientProperty(PopupFactory_FORCE_HEAVYWEIGHT_POPUP,
Boolean.TRUE);
Component fo = KeyboardFocusManager.getCurrentKeyboardFocusManager().
getFocusOwner();
pane.setInitialValue(initialValue);
JInternalFrame dialog =
pane.createInternalFrame(parentComponent, title);
pane.selectInitialValue();
dialog.setVisible(true);
/* Since all input will be blocked until this dialog is dismissed,
* make sure its parent containers are visible first (this component
* is tested below). This is necessary for JApplets, because
* because an applet normally isn't made visible until after its
* start() method returns -- if this method is called from start(),
* the applet will appear to hang while an invisible modal frame
* waits for input.
*/
if (dialog.isVisible() && !dialog.isShowing()) {
Container parent = dialog.getParent();
while (parent != null) {
if (parent.isVisible() == false) {
parent.setVisible(true);
}
parent = parent.getParent();
}
}
// Use reflection to get Container.startLWModal.
try {
Object obj;
obj = AccessController.doPrivileged(new ModalPrivilegedAction(
Container.class, "startLWModal"));
if (obj != null) {
((Method)obj).invoke(dialog, (Object[])null);
}
} catch (IllegalAccessException ex) {
} catch (IllegalArgumentException ex) {
} catch (InvocationTargetException ex) {
}
if (parentComponent instanceof JInternalFrame) {
try {
((JInternalFrame)parentComponent).setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
Object selectedValue = pane.getValue();
if (fo != null && fo.isShowing()) {
fo.requestFocus();
}
if (selectedValue == null) {
return CLOSED_OPTION;
}
if (options == null) {
if (selectedValue instanceof Integer) {
return ((Integer)selectedValue).intValue();
}
return CLOSED_OPTION;
}
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if (options[counter].equals(selectedValue)) {
return counter;
}
}
return CLOSED_OPTION;
}
/** {@collect.stats}
* Shows an internal question-message dialog requesting input from
* the user parented to <code>parentComponent</code>. The dialog
* is displayed in the <code>Component</code>'s frame,
* and is usually positioned below the <code>Component</code>.
*
* @param parentComponent the parent <code>Component</code>
* for the dialog
* @param message the <code>Object</code> to display
*/
public static String showInternalInputDialog(Component parentComponent,
Object message) {
return showInternalInputDialog(parentComponent, message, UIManager.
getString("OptionPane.inputDialogTitle", parentComponent),
QUESTION_MESSAGE);
}
/** {@collect.stats}
* Shows an internal dialog requesting input from the user parented
* to <code>parentComponent</code> with the dialog having the title
* <code>title</code> and message type <code>messageType</code>.
*
* @param parentComponent the parent <code>Component</code> for the dialog
* @param message the <code>Object</code> to display
* @param title the <code>String</code> to display in the
* dialog title bar
* @param messageType the type of message that is to be displayed:
* ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE,
* QUESTION_MESSAGE, or PLAIN_MESSAGE
*/
public static String showInternalInputDialog(Component parentComponent,
Object message, String title, int messageType) {
return (String)showInternalInputDialog(parentComponent, message, title,
messageType, null, null, null);
}
/** {@collect.stats}
* Prompts the user for input in a blocking internal dialog where
* the initial selection, possible selections, and all other
* options can be specified. The user will able to choose from
* <code>selectionValues</code>, where <code>null</code>
* implies the user can input
* whatever they wish, usually by means of a <code>JTextField</code>.
* <code>initialSelectionValue</code> is the initial value to prompt
* the user with. It is up to the UI to decide how best to represent
* the <code>selectionValues</code>, but usually a
* <code>JComboBox</code>, <code>JList</code>, or
* <code>JTextField</code> will be used.
*
* @param parentComponent the parent <code>Component</code> for the dialog
* @param message the <code>Object</code> to display
* @param title the <code>String</code> to display in the dialog
* title bar
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>, <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>, or <code>PLAIN_MESSAGE</code>
* @param icon the <code>Icon</code> image to display
* @param selectionValues an array of <code>Objects</code> that
* gives the possible selections
* @param initialSelectionValue the value used to initialize the input
* field
* @return user's input, or <code>null</code> meaning the user
* canceled the input
*/
public static Object showInternalInputDialog(Component parentComponent,
Object message, String title, int messageType, Icon icon,
Object[] selectionValues, Object initialSelectionValue) {
JOptionPane pane = new JOptionPane(message, messageType,
OK_CANCEL_OPTION, icon, null, null);
pane.putClientProperty(PopupFactory_FORCE_HEAVYWEIGHT_POPUP,
Boolean.TRUE);
Component fo = KeyboardFocusManager.getCurrentKeyboardFocusManager().
getFocusOwner();
pane.setWantsInput(true);
pane.setSelectionValues(selectionValues);
pane.setInitialSelectionValue(initialSelectionValue);
JInternalFrame dialog =
pane.createInternalFrame(parentComponent, title);
pane.selectInitialValue();
dialog.setVisible(true);
/* Since all input will be blocked until this dialog is dismissed,
* make sure its parent containers are visible first (this component
* is tested below). This is necessary for JApplets, because
* because an applet normally isn't made visible until after its
* start() method returns -- if this method is called from start(),
* the applet will appear to hang while an invisible modal frame
* waits for input.
*/
if (dialog.isVisible() && !dialog.isShowing()) {
Container parent = dialog.getParent();
while (parent != null) {
if (parent.isVisible() == false) {
parent.setVisible(true);
}
parent = parent.getParent();
}
}
// Use reflection to get Container.startLWModal.
try {
Object obj;
obj = AccessController.doPrivileged(new ModalPrivilegedAction(
Container.class, "startLWModal"));
if (obj != null) {
((Method)obj).invoke(dialog, (Object[])null);
}
} catch (IllegalAccessException ex) {
} catch (IllegalArgumentException ex) {
} catch (InvocationTargetException ex) {
}
if (parentComponent instanceof JInternalFrame) {
try {
((JInternalFrame)parentComponent).setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
if (fo != null && fo.isShowing()) {
fo.requestFocus();
}
Object value = pane.getInputValue();
if (value == UNINITIALIZED_VALUE) {
return null;
}
return value;
}
/** {@collect.stats}
* Creates and returns an instance of <code>JInternalFrame</code>.
* The internal frame is created with the specified title,
* and wrapping the <code>JOptionPane</code>.
* The returned <code>JInternalFrame</code> is
* added to the <code>JDesktopPane</code> ancestor of
* <code>parentComponent</code>, or components
* parent if one its ancestors isn't a <code>JDesktopPane</code>,
* or if <code>parentComponent</code>
* doesn't have a parent then a <code>RuntimeException</code> is thrown.
*
* @param parentComponent the parent <code>Component</code> for
* the internal frame
* @param title the <code>String</code> to display in the
* frame's title bar
* @return a <code>JInternalFrame</code> containing a
* <code>JOptionPane</code>
* @exception RuntimeException if <code>parentComponent</code> does
* not have a valid parent
*/
public JInternalFrame createInternalFrame(Component parentComponent,
String title) {
Container parent =
JOptionPane.getDesktopPaneForComponent(parentComponent);
if (parent == null && (parentComponent == null ||
(parent = parentComponent.getParent()) == null)) {
throw new RuntimeException("JOptionPane: parentComponent does " +
"not have a valid parent");
}
// Option dialogs should be closable only
final JInternalFrame iFrame = new JInternalFrame(title, false, true,
false, false);
iFrame.putClientProperty("JInternalFrame.frameType", "optionDialog");
iFrame.putClientProperty("JInternalFrame.messageType",
new Integer(getMessageType()));
iFrame.addInternalFrameListener(new InternalFrameAdapter() {
public void internalFrameClosing(InternalFrameEvent e) {
if (getValue() == UNINITIALIZED_VALUE) {
setValue(null);
}
}
});
addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
// Let the defaultCloseOperation handle the closing
// if the user closed the iframe without selecting a button
// (newValue = null in that case). Otherwise, close the dialog.
if (iFrame.isVisible() &&
event.getSource() == JOptionPane.this &&
event.getPropertyName().equals(VALUE_PROPERTY)) {
// Use reflection to get Container.stopLWModal().
try {
Object obj;
obj = AccessController.doPrivileged(
new ModalPrivilegedAction(
Container.class, "stopLWModal"));
if (obj != null) {
((Method)obj).invoke(iFrame, (Object[])null);
}
} catch (IllegalAccessException ex) {
} catch (IllegalArgumentException ex) {
} catch (InvocationTargetException ex) {
}
try {
iFrame.setClosed(true);
}
catch (java.beans.PropertyVetoException e) {
}
iFrame.setVisible(false);
}
}
});
iFrame.getContentPane().add(this, BorderLayout.CENTER);
if (parent instanceof JDesktopPane) {
parent.add(iFrame, JLayeredPane.MODAL_LAYER);
} else {
parent.add(iFrame, BorderLayout.CENTER);
}
Dimension iFrameSize = iFrame.getPreferredSize();
Dimension rootSize = parent.getSize();
Dimension parentSize = parentComponent.getSize();
iFrame.setBounds((rootSize.width - iFrameSize.width) / 2,
(rootSize.height - iFrameSize.height) / 2,
iFrameSize.width, iFrameSize.height);
// We want dialog centered relative to its parent component
Point iFrameCoord =
SwingUtilities.convertPoint(parentComponent, 0, 0, parent);
int x = (parentSize.width - iFrameSize.width) / 2 + iFrameCoord.x;
int y = (parentSize.height - iFrameSize.height) / 2 + iFrameCoord.y;
// If possible, dialog should be fully visible
int ovrx = x + iFrameSize.width - rootSize.width;
int ovry = y + iFrameSize.height - rootSize.height;
x = Math.max((ovrx > 0? x - ovrx: x), 0);
y = Math.max((ovry > 0? y - ovry: y), 0);
iFrame.setBounds(x, y, iFrameSize.width, iFrameSize.height);
parent.validate();
try {
iFrame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {}
return iFrame;
}
/** {@collect.stats}
* Returns the specified component's <code>Frame</code>.
*
* @param parentComponent the <code>Component</code> to check for a
* <code>Frame</code>
* @return the <code>Frame</code> that contains the component,
* or <code>getRootFrame</code>
* if the component is <code>null</code>,
* or does not have a valid <code>Frame</code> parent
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see #getRootFrame
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static Frame getFrameForComponent(Component parentComponent)
throws HeadlessException {
if (parentComponent == null)
return getRootFrame();
if (parentComponent instanceof Frame)
return (Frame)parentComponent;
return JOptionPane.getFrameForComponent(parentComponent.getParent());
}
/** {@collect.stats}
* Returns the specified component's toplevel <code>Frame</code> or
* <code>Dialog</code>.
*
* @param parentComponent the <code>Component</code> to check for a
* <code>Frame</code> or <code>Dialog</code>
* @return the <code>Frame</code> or <code>Dialog</code> that
* contains the component, or the default
* frame if the component is <code>null</code>,
* or does not have a valid
* <code>Frame</code> or <code>Dialog</code> parent
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
static Window getWindowForComponent(Component parentComponent)
throws HeadlessException {
if (parentComponent == null)
return getRootFrame();
if (parentComponent instanceof Frame || parentComponent instanceof Dialog)
return (Window)parentComponent;
return JOptionPane.getWindowForComponent(parentComponent.getParent());
}
/** {@collect.stats}
* Returns the specified component's desktop pane.
*
* @param parentComponent the <code>Component</code> to check for a
* desktop
* @return the <code>JDesktopPane</code> that contains the component,
* or <code>null</code> if the component is <code>null</code>
* or does not have an ancestor that is a
* <code>JInternalFrame</code>
*/
public static JDesktopPane getDesktopPaneForComponent(Component parentComponent) {
if(parentComponent == null)
return null;
if(parentComponent instanceof JDesktopPane)
return (JDesktopPane)parentComponent;
return getDesktopPaneForComponent(parentComponent.getParent());
}
private static final Object sharedFrameKey = JOptionPane.class;
/** {@collect.stats}
* Sets the frame to use for class methods in which a frame is
* not provided.
* <p>
* <strong>Note:</strong>
* It is recommended that rather than using this method you supply a valid parent.
*
* @param newRootFrame the default <code>Frame</code> to use
*/
public static void setRootFrame(Frame newRootFrame) {
if (newRootFrame != null) {
SwingUtilities.appContextPut(sharedFrameKey, newRootFrame);
} else {
SwingUtilities.appContextRemove(sharedFrameKey);
}
}
/** {@collect.stats}
* Returns the <code>Frame</code> to use for the class methods in
* which a frame is not provided.
*
* @return the default <code>Frame</code> to use
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see #setRootFrame
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static Frame getRootFrame() throws HeadlessException {
Frame sharedFrame =
(Frame)SwingUtilities.appContextGet(sharedFrameKey);
if (sharedFrame == null) {
sharedFrame = SwingUtilities.getSharedOwnerFrame();
SwingUtilities.appContextPut(sharedFrameKey, sharedFrame);
}
return sharedFrame;
}
/** {@collect.stats}
* Creates a <code>JOptionPane</code> with a test message.
*/
public JOptionPane() {
this("JOptionPane message");
}
/** {@collect.stats}
* Creates a instance of <code>JOptionPane</code> to display a
* message using the
* plain-message message type and the default options delivered by
* the UI.
*
* @param message the <code>Object</code> to display
*/
public JOptionPane(Object message) {
this(message, PLAIN_MESSAGE);
}
/** {@collect.stats}
* Creates an instance of <code>JOptionPane</code> to display a message
* with the specified message type and the default options,
*
* @param message the <code>Object</code> to display
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
*/
public JOptionPane(Object message, int messageType) {
this(message, messageType, DEFAULT_OPTION);
}
/** {@collect.stats}
* Creates an instance of <code>JOptionPane</code> to display a message
* with the specified message type and options.
*
* @param message the <code>Object</code> to display
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param optionType the options to display in the pane:
* <code>DEFAULT_OPTION</code>, <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* <code>OK_CANCEL_OPTION</code>
*/
public JOptionPane(Object message, int messageType, int optionType) {
this(message, messageType, optionType, null);
}
/** {@collect.stats}
* Creates an instance of <code>JOptionPane</code> to display a message
* with the specified message type, options, and icon.
*
* @param message the <code>Object</code> to display
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param optionType the options to display in the pane:
* <code>DEFAULT_OPTION</code>, <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* <code>OK_CANCEL_OPTION</code>
* @param icon the <code>Icon</code> image to display
*/
public JOptionPane(Object message, int messageType, int optionType,
Icon icon) {
this(message, messageType, optionType, icon, null);
}
/** {@collect.stats}
* Creates an instance of <code>JOptionPane</code> to display a message
* with the specified message type, icon, and options.
* None of the options is initially selected.
* <p>
* The options objects should contain either instances of
* <code>Component</code>s, (which are added directly) or
* <code>Strings</code> (which are wrapped in a <code>JButton</code>).
* If you provide <code>Component</code>s, you must ensure that when the
* <code>Component</code> is clicked it messages <code>setValue</code>
* in the created <code>JOptionPane</code>.
*
* @param message the <code>Object</code> to display
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param optionType the options to display in the pane:
* <code>DEFAULT_OPTION</code>,
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* <code>OK_CANCEL_OPTION</code>
* @param icon the <code>Icon</code> image to display
* @param options the choices the user can select
*/
public JOptionPane(Object message, int messageType, int optionType,
Icon icon, Object[] options) {
this(message, messageType, optionType, icon, options, null);
}
/** {@collect.stats}
* Creates an instance of <code>JOptionPane</code> to display a message
* with the specified message type, icon, and options, with the
* initially-selected option specified.
*
* @param message the <code>Object</code> to display
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param optionType the options to display in the pane:
* <code>DEFAULT_OPTION</code>,
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* <code>OK_CANCEL_OPTION</code>
* @param icon the Icon image to display
* @param options the choices the user can select
* @param initialValue the choice that is initially selected; if
* <code>null</code>, then nothing will be initially selected;
* only meaningful if <code>options</code> is used
*/
public JOptionPane(Object message, int messageType, int optionType,
Icon icon, Object[] options, Object initialValue) {
this.message = message;
this.options = options;
this.initialValue = initialValue;
this.icon = icon;
setMessageType(messageType);
setOptionType(optionType);
value = UNINITIALIZED_VALUE;
inputValue = UNINITIALIZED_VALUE;
updateUI();
}
/** {@collect.stats}
* Sets the UI object which implements the L&F for this component.
*
* @param ui the <code>OptionPaneUI</code> L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* description: The UI object that implements the optionpane's LookAndFeel
*/
public void setUI(OptionPaneUI ui) {
if ((OptionPaneUI)this.ui != ui) {
super.setUI(ui);
invalidate();
}
}
/** {@collect.stats}
* Returns the UI object which implements the L&F for this component.
*
* @return the <code>OptionPaneUI</code> object
*/
public OptionPaneUI getUI() {
return (OptionPaneUI)ui;
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((OptionPaneUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the UI class that implements the
* L&F for this component.
*
* @return the string "OptionPaneUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Sets the option pane's message-object.
* @param newMessage the <code>Object</code> to display
* @see #getMessage
*
* @beaninfo
* preferred: true
* bound: true
* description: The optionpane's message object.
*/
public void setMessage(Object newMessage) {
Object oldMessage = message;
message = newMessage;
firePropertyChange(MESSAGE_PROPERTY, oldMessage, message);
}
/** {@collect.stats}
* Returns the message-object this pane displays.
* @see #setMessage
*
* @return the <code>Object</code> that is displayed
*/
public Object getMessage() {
return message;
}
/** {@collect.stats}
* Sets the icon to display. If non-<code>null</code>, the look and feel
* does not provide an icon.
* @param newIcon the <code>Icon</code> to display
*
* @see #getIcon
* @beaninfo
* preferred: true
* bound: true
* description: The option pane's type icon.
*/
public void setIcon(Icon newIcon) {
Object oldIcon = icon;
icon = newIcon;
firePropertyChange(ICON_PROPERTY, oldIcon, icon);
}
/** {@collect.stats}
* Returns the icon this pane displays.
* @return the <code>Icon</code> that is displayed
*
* @see #setIcon
*/
public Icon getIcon() {
return icon;
}
/** {@collect.stats}
* Sets the value the user has chosen.
* @param newValue the chosen value
*
* @see #getValue
* @beaninfo
* preferred: true
* bound: true
* description: The option pane's value object.
*/
public void setValue(Object newValue) {
Object oldValue = value;
value = newValue;
firePropertyChange(VALUE_PROPERTY, oldValue, value);
}
/** {@collect.stats}
* Returns the value the user has selected. <code>UNINITIALIZED_VALUE</code>
* implies the user has not yet made a choice, <code>null</code> means the
* user closed the window with out choosing anything. Otherwise
* the returned value will be one of the options defined in this
* object.
*
* @return the <code>Object</code> chosen by the user,
* <code>UNINITIALIZED_VALUE</code>
* if the user has not yet made a choice, or <code>null</code> if
* the user closed the window without making a choice
*
* @see #setValue
*/
public Object getValue() {
return value;
}
/** {@collect.stats}
* Sets the options this pane displays. If an element in
* <code>newOptions</code> is a <code>Component</code>
* it is added directly to the pane,
* otherwise a button is created for the element.
*
* @param newOptions an array of <code>Objects</code> that create the
* buttons the user can click on, or arbitrary
* <code>Components</code> to add to the pane
*
* @see #getOptions
* @beaninfo
* bound: true
* description: The option pane's options objects.
*/
public void setOptions(Object[] newOptions) {
Object[] oldOptions = options;
options = newOptions;
firePropertyChange(OPTIONS_PROPERTY, oldOptions, options);
}
/** {@collect.stats}
* Returns the choices the user can make.
* @return the array of <code>Objects</code> that give the user's choices
*
* @see #setOptions
*/
public Object[] getOptions() {
if(options != null) {
int optionCount = options.length;
Object[] retOptions = new Object[optionCount];
System.arraycopy(options, 0, retOptions, 0, optionCount);
return retOptions;
}
return options;
}
/** {@collect.stats}
* Sets the initial value that is to be enabled -- the
* <code>Component</code>
* that has the focus when the pane is initially displayed.
*
* @param newInitialValue the <code>Object</code> that gets the initial
* keyboard focus
*
* @see #getInitialValue
* @beaninfo
* preferred: true
* bound: true
* description: The option pane's initial value object.
*/
public void setInitialValue(Object newInitialValue) {
Object oldIV = initialValue;
initialValue = newInitialValue;
firePropertyChange(INITIAL_VALUE_PROPERTY, oldIV, initialValue);
}
/** {@collect.stats}
* Returns the initial value.
*
* @return the <code>Object</code> that gets the initial keyboard focus
*
* @see #setInitialValue
*/
public Object getInitialValue() {
return initialValue;
}
/** {@collect.stats}
* Sets the option pane's message type.
* The message type is used by the Look and Feel to determine the
* icon to display (if not supplied) as well as potentially how to
* lay out the <code>parentComponent</code>.
* @param newType an integer specifying the kind of message to display:
* <code>ERROR_MESSAGE</code>, <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>, or <code>PLAIN_MESSAGE</code>
* @exception RuntimeException if <code>newType</code> is not one of the
* legal values listed above
* @see #getMessageType
* @beaninfo
* preferred: true
* bound: true
* description: The option pane's message type.
*/
public void setMessageType(int newType) {
if(newType != ERROR_MESSAGE && newType != INFORMATION_MESSAGE &&
newType != WARNING_MESSAGE && newType != QUESTION_MESSAGE &&
newType != PLAIN_MESSAGE)
throw new RuntimeException("JOptionPane: type must be one of JOptionPane.ERROR_MESSAGE, JOptionPane.INFORMATION_MESSAGE, JOptionPane.WARNING_MESSAGE, JOptionPane.QUESTION_MESSAGE or JOptionPane.PLAIN_MESSAGE");
int oldType = messageType;
messageType = newType;
firePropertyChange(MESSAGE_TYPE_PROPERTY, oldType, messageType);
}
/** {@collect.stats}
* Returns the message type.
*
* @return an integer specifying the message type
*
* @see #setMessageType
*/
public int getMessageType() {
return messageType;
}
/** {@collect.stats}
* Sets the options to display.
* The option type is used by the Look and Feel to
* determine what buttons to show (unless options are supplied).
* @param newType an integer specifying the options the L&F is to display:
* <code>DEFAULT_OPTION</code>,
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* or <code>OK_CANCEL_OPTION</code>
* @exception RuntimeException if <code>newType</code> is not one of
* the legal values listed above
*
* @see #getOptionType
* @see #setOptions
* @beaninfo
* preferred: true
* bound: true
* description: The option pane's option type.
*/
public void setOptionType(int newType) {
if(newType != DEFAULT_OPTION && newType != YES_NO_OPTION &&
newType != YES_NO_CANCEL_OPTION && newType != OK_CANCEL_OPTION)
throw new RuntimeException("JOptionPane: option type must be one of JOptionPane.DEFAULT_OPTION, JOptionPane.YES_NO_OPTION, JOptionPane.YES_NO_CANCEL_OPTION or JOptionPane.OK_CANCEL_OPTION");
int oldType = optionType;
optionType = newType;
firePropertyChange(OPTION_TYPE_PROPERTY, oldType, optionType);
}
/** {@collect.stats}
* Returns the type of options that are displayed.
*
* @return an integer specifying the user-selectable options
*
* @see #setOptionType
*/
public int getOptionType() {
return optionType;
}
/** {@collect.stats}
* Sets the input selection values for a pane that provides the user
* with a list of items to choose from. (The UI provides a widget
* for choosing one of the values.) A <code>null</code> value
* implies the user can input whatever they wish, usually by means
* of a <code>JTextField</code>.
* <p>
* Sets <code>wantsInput</code> to true. Use
* <code>setInitialSelectionValue</code> to specify the initially-chosen
* value. After the pane as been enabled, <code>inputValue</code> is
* set to the value the user has selected.
* @param newValues an array of <code>Objects</code> the user to be
* displayed
* (usually in a list or combo-box) from which
* the user can make a selection
* @see #setWantsInput
* @see #setInitialSelectionValue
* @see #getSelectionValues
* @beaninfo
* bound: true
* description: The option pane's selection values.
*/
public void setSelectionValues(Object[] newValues) {
Object[] oldValues = selectionValues;
selectionValues = newValues;
firePropertyChange(SELECTION_VALUES_PROPERTY, oldValues, newValues);
if(selectionValues != null)
setWantsInput(true);
}
/** {@collect.stats}
* Returns the input selection values.
*
* @return the array of <code>Objects</code> the user can select
* @see #setSelectionValues
*/
public Object[] getSelectionValues() {
return selectionValues;
}
/** {@collect.stats}
* Sets the input value that is initially displayed as selected to the user.
* Only used if <code>wantsInput</code> is true.
* @param newValue the initially selected value
* @see #setSelectionValues
* @see #getInitialSelectionValue
* @beaninfo
* bound: true
* description: The option pane's initial selection value object.
*/
public void setInitialSelectionValue(Object newValue) {
Object oldValue = initialSelectionValue;
initialSelectionValue = newValue;
firePropertyChange(INITIAL_SELECTION_VALUE_PROPERTY, oldValue,
newValue);
}
/** {@collect.stats}
* Returns the input value that is displayed as initially selected to the user.
*
* @return the initially selected value
* @see #setInitialSelectionValue
* @see #setSelectionValues
*/
public Object getInitialSelectionValue() {
return initialSelectionValue;
}
/** {@collect.stats}
* Sets the input value that was selected or input by the user.
* Only used if <code>wantsInput</code> is true. Note that this method
* is invoked internally by the option pane (in response to user action)
* and should generally not be called by client programs. To set the
* input value initially displayed as selected to the user, use
* <code>setInitialSelectionValue</code>.
*
* @param newValue the <code>Object</code> used to set the
* value that the user specified (usually in a text field)
* @see #setSelectionValues
* @see #setInitialSelectionValue
* @see #setWantsInput
* @see #getInputValue
* @beaninfo
* preferred: true
* bound: true
* description: The option pane's input value object.
*/
public void setInputValue(Object newValue) {
Object oldValue = inputValue;
inputValue = newValue;
firePropertyChange(INPUT_VALUE_PROPERTY, oldValue, newValue);
}
/** {@collect.stats}
* Returns the value the user has input, if <code>wantsInput</code>
* is true.
*
* @return the <code>Object</code> the user specified,
* if it was one of the objects, or a
* <code>String</code> if it was a value typed into a
* field
* @see #setSelectionValues
* @see #setWantsInput
* @see #setInputValue
*/
public Object getInputValue() {
return inputValue;
}
/** {@collect.stats}
* Returns the maximum number of characters to place on a line in a
* message. Default is to return <code>Integer.MAX_VALUE</code>.
* The value can be
* changed by overriding this method in a subclass.
*
* @return an integer giving the maximum number of characters on a line
*/
public int getMaxCharactersPerLineCount() {
return Integer.MAX_VALUE;
}
/** {@collect.stats}
* Sets the <code>wantsInput</code> property.
* If <code>newValue</code> is true, an input component
* (such as a text field or combo box) whose parent is
* <code>parentComponent</code> is provided to
* allow the user to input a value. If <code>getSelectionValues</code>
* returns a non-<code>null</code> array, the input value is one of the
* objects in that array. Otherwise the input value is whatever
* the user inputs.
* <p>
* This is a bound property.
*
* @see #setSelectionValues
* @see #setInputValue
* @beaninfo
* preferred: true
* bound: true
* description: Flag which allows the user to input a value.
*/
public void setWantsInput(boolean newValue) {
boolean oldValue = wantsInput;
wantsInput = newValue;
firePropertyChange(WANTS_INPUT_PROPERTY, oldValue, newValue);
}
/** {@collect.stats}
* Returns the value of the <code>wantsInput</code> property.
*
* @return true if an input component will be provided
* @see #setWantsInput
*/
public boolean getWantsInput() {
return wantsInput;
}
/** {@collect.stats}
* Requests that the initial value be selected, which will set
* focus to the initial value. This method
* should be invoked after the window containing the option pane
* is made visible.
*/
public void selectInitialValue() {
OptionPaneUI ui = getUI();
if (ui != null) {
ui.selectInitialValue(this);
}
}
private static int styleFromMessageType(int messageType) {
switch (messageType) {
case ERROR_MESSAGE:
return JRootPane.ERROR_DIALOG;
case QUESTION_MESSAGE:
return JRootPane.QUESTION_DIALOG;
case WARNING_MESSAGE:
return JRootPane.WARNING_DIALOG;
case INFORMATION_MESSAGE:
return JRootPane.INFORMATION_DIALOG;
case PLAIN_MESSAGE:
default:
return JRootPane.PLAIN_DIALOG;
}
}
// Serialization support.
private void writeObject(ObjectOutputStream s) throws IOException {
Vector values = new Vector();
s.defaultWriteObject();
// Save the icon, if its Serializable.
if(icon != null && icon instanceof Serializable) {
values.addElement("icon");
values.addElement(icon);
}
// Save the message, if its Serializable.
if(message != null && message instanceof Serializable) {
values.addElement("message");
values.addElement(message);
}
// Save the treeModel, if its Serializable.
if(options != null) {
Vector serOptions = new Vector();
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++)
if(options[counter] instanceof Serializable)
serOptions.addElement(options[counter]);
if(serOptions.size() > 0) {
int optionCount = serOptions.size();
Object[] arrayOptions = new Object[optionCount];
serOptions.copyInto(arrayOptions);
values.addElement("options");
values.addElement(arrayOptions);
}
}
// Save the initialValue, if its Serializable.
if(initialValue != null && initialValue instanceof Serializable) {
values.addElement("initialValue");
values.addElement(initialValue);
}
// Save the value, if its Serializable.
if(value != null && value instanceof Serializable) {
values.addElement("value");
values.addElement(value);
}
// Save the selectionValues, if its Serializable.
if(selectionValues != null) {
boolean serialize = true;
for(int counter = 0, maxCounter = selectionValues.length;
counter < maxCounter; counter++) {
if(selectionValues[counter] != null &&
!(selectionValues[counter] instanceof Serializable)) {
serialize = false;
break;
}
}
if(serialize) {
values.addElement("selectionValues");
values.addElement(selectionValues);
}
}
// Save the inputValue, if its Serializable.
if(inputValue != null && inputValue instanceof Serializable) {
values.addElement("inputValue");
values.addElement(inputValue);
}
// Save the initialSelectionValue, if its Serializable.
if(initialSelectionValue != null &&
initialSelectionValue instanceof Serializable) {
values.addElement("initialSelectionValue");
values.addElement(initialSelectionValue);
}
s.writeObject(values);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
Vector values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("icon")) {
icon = (Icon)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("message")) {
message = values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("options")) {
options = (Object[])values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("initialValue")) {
initialValue = values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("value")) {
value = values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("selectionValues")) {
selectionValues = (Object[])values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("inputValue")) {
inputValue = values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("initialSelectionValue")) {
initialSelectionValue = values.elementAt(++indexCounter);
indexCounter++;
}
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>JOptionPane</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>JOptionPane</code>
*/
protected String paramString() {
String iconString = (icon != null ?
icon.toString() : "");
String initialValueString = (initialValue != null ?
initialValue.toString() : "");
String messageString = (message != null ?
message.toString() : "");
String messageTypeString;
if (messageType == ERROR_MESSAGE) {
messageTypeString = "ERROR_MESSAGE";
} else if (messageType == INFORMATION_MESSAGE) {
messageTypeString = "INFORMATION_MESSAGE";
} else if (messageType == WARNING_MESSAGE) {
messageTypeString = "WARNING_MESSAGE";
} else if (messageType == QUESTION_MESSAGE) {
messageTypeString = "QUESTION_MESSAGE";
} else if (messageType == PLAIN_MESSAGE) {
messageTypeString = "PLAIN_MESSAGE";
} else messageTypeString = "";
String optionTypeString;
if (optionType == DEFAULT_OPTION) {
optionTypeString = "DEFAULT_OPTION";
} else if (optionType == YES_NO_OPTION) {
optionTypeString = "YES_NO_OPTION";
} else if (optionType == YES_NO_CANCEL_OPTION) {
optionTypeString = "YES_NO_CANCEL_OPTION";
} else if (optionType == OK_CANCEL_OPTION) {
optionTypeString = "OK_CANCEL_OPTION";
} else optionTypeString = "";
String wantsInputString = (wantsInput ?
"true" : "false");
return super.paramString() +
",icon=" + iconString +
",initialValue=" + initialValueString +
",message=" + messageString +
",messageType=" + messageTypeString +
",optionType=" + optionTypeString +
",wantsInput=" + wantsInputString;
}
/** {@collect.stats}
* Retrieves a method from the provided class and makes it accessible.
*/
private static class ModalPrivilegedAction implements PrivilegedAction {
private Class clazz;
private String methodName;
public ModalPrivilegedAction(Class clazz, String methodName) {
this.clazz = clazz;
this.methodName = methodName;
}
public Object run() {
Method method = null;
try {
method = clazz.getDeclaredMethod(methodName, (Class[])null);
} catch (NoSuchMethodException ex) {
}
if (method != null) {
method.setAccessible(true);
}
return method;
}
}
///////////////////
// Accessibility support
///////////////////
/** {@collect.stats}
* Returns the <code>AccessibleContext</code> associated with this JOptionPane.
* For option panes, the <code>AccessibleContext</code> takes the form of an
* <code>AccessibleJOptionPane</code>.
* A new <code>AccessibleJOptionPane</code> instance is created if necessary.
*
* @return an AccessibleJOptionPane that serves as the
* AccessibleContext of this AccessibleJOptionPane
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this option pane
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJOptionPane();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JOptionPane</code> class. It provides an implementation of the
* Java Accessibility API appropriate to option 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 AccessibleJOptionPane extends AccessibleJComponent {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
switch (messageType) {
case ERROR_MESSAGE:
case INFORMATION_MESSAGE:
case WARNING_MESSAGE:
return AccessibleRole.ALERT;
default:
return AccessibleRole.OPTION_PANE;
}
}
} // inner class AccessibleJOptionPane
}
|
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.ActionEvent;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
/** {@collect.stats}
* A text component that can be marked up with attributes that are
* represented graphically.
* You can find how-to information and examples of using text 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 models paragraphs
* that are composed of runs of character level attributes. Each
* paragraph may have a logical style attached to it which contains
* the default attributes to use if not overridden by attributes set
* on the paragraph or character run. Components and images may
* be embedded in the flow of text.
* <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 true
* description: A text component that can be marked up with attributes that are graphically represented.
*
* @author Timothy Prinzing
* @see javax.swing.text.StyledEditorKit
*/
public class JTextPane extends JEditorPane {
/** {@collect.stats}
* Creates a new <code>JTextPane</code>. A new instance of
* <code>StyledEditorKit</code> is
* created and set, and the document model set to <code>null</code>.
*/
public JTextPane() {
super();
EditorKit editorKit = createDefaultEditorKit();
String contentType = editorKit.getContentType();
if (contentType != null
&& getEditorKitClassNameForContentType(contentType) ==
defaultEditorKitMap.get(contentType)) {
setEditorKitForContentType(contentType, editorKit);
}
setEditorKit(editorKit);
}
/** {@collect.stats}
* Creates a new <code>JTextPane</code>, with a specified document model.
* A new instance of <code>javax.swing.text.StyledEditorKit</code>
* is created and set.
*
* @param doc the document model
*/
public JTextPane(StyledDocument doc) {
this();
setStyledDocument(doc);
}
/** {@collect.stats}
* Returns the class ID for the UI.
*
* @return the string "TextPaneUI"
*
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Associates the editor with a text document. This
* must be a <code>StyledDocument</code>.
*
* @param doc the document to display/edit
* @exception IllegalArgumentException if <code>doc</code> can't
* be narrowed to a <code>StyledDocument</code> which is the
* required type of model for this text component
*/
public void setDocument(Document doc) {
if (doc instanceof StyledDocument) {
super.setDocument(doc);
} else {
throw new IllegalArgumentException("Model must be StyledDocument");
}
}
/** {@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.
*
* @param doc the document to display/edit
*/
public void setStyledDocument(StyledDocument doc) {
super.setDocument(doc);
}
/** {@collect.stats}
* Fetches the model associated with the editor.
*
* @return the model
*/
public StyledDocument getStyledDocument() {
return (StyledDocument) getDocument();
}
/** {@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 this amounts to a removal of the
* current selection. The replacement text will have the
* attributes currently defined for input at the point of
* insertion. If the document 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
*/
public void replaceSelection(String content) {
replaceSelection(content, true);
}
private void replaceSelection(String content, boolean checkEditable) {
if (checkEditable && !isEditable()) {
UIManager.getLookAndFeel().provideErrorFeedback(JTextPane.this);
return;
}
Document doc = getStyledDocument();
if (doc != null) {
try {
Caret caret = getCaret();
int p0 = Math.min(caret.getDot(), caret.getMark());
int p1 = Math.max(caret.getDot(), caret.getMark());
AttributeSet attr = getInputAttributes().copyAttributes();
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).replace(p0, p1 - p0, content,attr);
}
else {
if (p0 != p1) {
doc.remove(p0, p1 - p0);
}
if (content != null && content.length() > 0) {
doc.insertString(p0, content, attr);
}
}
} catch (BadLocationException e) {
UIManager.getLookAndFeel().provideErrorFeedback(JTextPane.this);
}
}
}
/** {@collect.stats}
* Inserts a component into the document as a replacement
* for the currently selected content. If there is no
* selection the component is effectively inserted at the
* current position of the caret. This is represented in
* the associated document as an attribute of one character
* of content.
* <p>
* The component given is the actual component used by the
* JTextPane. Since components cannot be a child of more than
* one container, this method should not be used in situations
* where the model is shared by text components.
* <p>
* The component is placed relative to the text baseline
* according to the value returned by
* <code>Component.getAlignmentY</code>. For Swing components
* this value can be conveniently set using the method
* <code>JComponent.setAlignmentY</code>. For example, setting
* a value of <code>0.75</code> will cause 75 percent of the
* component to be above the baseline, and 25 percent of the
* component to be below the baseline.
* <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 c the component to insert
*/
public void insertComponent(Component c) {
MutableAttributeSet inputAttributes = getInputAttributes();
inputAttributes.removeAttributes(inputAttributes);
StyleConstants.setComponent(inputAttributes, c);
replaceSelection(" ", false);
inputAttributes.removeAttributes(inputAttributes);
}
/** {@collect.stats}
* Inserts an icon into the document as a replacement
* for the currently selected content. If there is no
* selection the icon is effectively inserted at the
* current position of the caret. This is represented in
* the associated document as an attribute of one character
* of content.
* <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 g the icon to insert
* @see Icon
*/
public void insertIcon(Icon g) {
MutableAttributeSet inputAttributes = getInputAttributes();
inputAttributes.removeAttributes(inputAttributes);
StyleConstants.setIcon(inputAttributes, g);
replaceSelection(" ", false);
inputAttributes.removeAttributes(inputAttributes);
}
/** {@collect.stats}
* Adds a new style into the logical style hierarchy. Style attributes
* resolve from bottom up so an attribute specified in a child
* will override an attribute specified in the parent.
*
* @param nm the name of the style (must be unique within the
* collection of named styles). The name may be <code>null</code>
* if the style is unnamed, but the caller is responsible
* for managing the reference returned as an unnamed style can't
* be fetched by name. An unnamed style may be useful for things
* like character attribute overrides such as found in a style
* run.
* @param parent the parent style. This may be <code>null</code>
* if unspecified
* attributes need not be resolved in some other style.
* @return the new <code>Style</code>
*/
public Style addStyle(String nm, Style parent) {
StyledDocument doc = getStyledDocument();
return doc.addStyle(nm, parent);
}
/** {@collect.stats}
* Removes a named non-<code>null</code> style previously added to
* the document.
*
* @param nm the name of the style to remove
*/
public void removeStyle(String nm) {
StyledDocument doc = getStyledDocument();
doc.removeStyle(nm);
}
/** {@collect.stats}
* Fetches a named non-<code>null</code> style previously added.
*
* @param nm the name of the style
* @return the <code>Style</code>
*/
public Style getStyle(String nm) {
StyledDocument doc = getStyledDocument();
return doc.getStyle(nm);
}
/** {@collect.stats}
* Sets the logical style to use for the paragraph at the
* current caret position. If attributes aren't explicitly set
* for character and paragraph attributes they will resolve
* through the logical style assigned to the paragraph, which
* in term may resolve through some hierarchy completely
* independent of the element hierarchy in the document.
* <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 s the logical style to assign to the paragraph,
* or <code>null</code> for no style
*/
public void setLogicalStyle(Style s) {
StyledDocument doc = getStyledDocument();
doc.setLogicalStyle(getCaretPosition(), s);
}
/** {@collect.stats}
* Fetches the logical style assigned to the paragraph represented
* by the current position of the caret, or <code>null</code>.
*
* @return the <code>Style</code>
*/
public Style getLogicalStyle() {
StyledDocument doc = getStyledDocument();
return doc.getLogicalStyle(getCaretPosition());
}
/** {@collect.stats}
* Fetches the character attributes in effect at the
* current location of the caret, or <code>null</code>.
*
* @return the attributes, or <code>null</code>
*/
public AttributeSet getCharacterAttributes() {
StyledDocument doc = getStyledDocument();
Element run = doc.getCharacterElement(getCaretPosition());
if (run != null) {
return run.getAttributes();
}
return null;
}
/** {@collect.stats}
* Applies the given attributes to character
* content. If there is a selection, the attributes
* are applied to the selection range. If there
* is no selection, the attributes are applied to
* the input attribute set which defines the attributes
* for any new text that gets inserted.
* <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 attr the attributes
* @param replace if true, then replace the existing attributes first
*/
public void setCharacterAttributes(AttributeSet attr, boolean replace) {
int p0 = getSelectionStart();
int p1 = getSelectionEnd();
if (p0 != p1) {
StyledDocument doc = getStyledDocument();
doc.setCharacterAttributes(p0, p1 - p0, attr, replace);
} else {
MutableAttributeSet inputAttributes = getInputAttributes();
if (replace) {
inputAttributes.removeAttributes(inputAttributes);
}
inputAttributes.addAttributes(attr);
}
}
/** {@collect.stats}
* Fetches the current paragraph attributes in effect
* at the location of the caret, or <code>null</code> if none.
*
* @return the attributes
*/
public AttributeSet getParagraphAttributes() {
StyledDocument doc = getStyledDocument();
Element paragraph = doc.getParagraphElement(getCaretPosition());
if (paragraph != null) {
return paragraph.getAttributes();
}
return null;
}
/** {@collect.stats}
* Applies the given attributes to paragraphs. If
* there is a selection, the attributes are applied
* to the paragraphs that intersect the selection.
* If there is no selection, the attributes are applied
* to the paragraph at the current caret position.
* <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 attr the non-<code>null</code> attributes
* @param replace if true, replace the existing attributes first
*/
public void setParagraphAttributes(AttributeSet attr, boolean replace) {
int p0 = getSelectionStart();
int p1 = getSelectionEnd();
StyledDocument doc = getStyledDocument();
doc.setParagraphAttributes(p0, p1 - p0, attr, replace);
}
/** {@collect.stats}
* Gets the input attributes for the pane.
*
* @return the attributes
*/
public MutableAttributeSet getInputAttributes() {
return getStyledEditorKit().getInputAttributes();
}
/** {@collect.stats}
* Gets the editor kit.
*
* @return the editor kit
*/
protected final StyledEditorKit getStyledEditorKit() {
return (StyledEditorKit) getEditorKit();
}
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "TextPaneUI";
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*
* @param s the output stream
*/
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);
}
}
}
// --- JEditorPane ------------------------------------
/** {@collect.stats}
* Creates the <code>EditorKit</code> to use by default. This
* is implemented to return <code>javax.swing.text.StyledEditorKit</code>.
*
* @return the editor kit
*/
protected EditorKit createDefaultEditorKit() {
return new StyledEditorKit();
}
/** {@collect.stats}
* Sets the currently installed kit for handling
* content. This is the bound property that
* establishes the content type of the editor.
*
* @param kit the desired editor behavior
* @exception IllegalArgumentException if kit is not a
* <code>StyledEditorKit</code>
*/
public final void setEditorKit(EditorKit kit) {
if (kit instanceof StyledEditorKit) {
super.setEditorKit(kit);
} else {
throw new IllegalArgumentException("Must be StyledEditorKit");
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JTextPane</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>JTextPane</code>
*/
protected String paramString() {
return super.paramString();
}
}
|
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.util.EventListener;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.plaf.*;
import javax.accessibility.*;
/** {@collect.stats}
* An implementation of a radio button menu item.
* A <code>JRadioButtonMenuItem</code> is
* a menu item that is part of a group of menu items in which only one
* item in the group can be selected. The selected item displays its
* selected state. Selecting it causes any other selected item to
* switch to the unselected state.
* To control the selected state of a group of radio button menu items,
* use a <code>ButtonGroup</code> object.
* <p>
* Menu items 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 menu item has many benefits beyond directly
* configuring a menu item. 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>
* For further documentation and examples 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 false
* description: A component within a group of menu items which can be selected.
*
* @author Georges Saab
* @author David Karlton
* @see ButtonGroup
*/
public class JRadioButtonMenuItem extends JMenuItem implements Accessible {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "RadioButtonMenuItemUI";
/** {@collect.stats}
* Creates a <code>JRadioButtonMenuItem</code> with no set text or icon.
*/
public JRadioButtonMenuItem() {
this(null, null, false);
}
/** {@collect.stats}
* Creates a <code>JRadioButtonMenuItem</code> with an icon.
*
* @param icon the <code>Icon</code> to display on the
* <code>JRadioButtonMenuItem</code>
*/
public JRadioButtonMenuItem(Icon icon) {
this(null, icon, false);
}
/** {@collect.stats}
* Creates a <code>JRadioButtonMenuItem</code> with text.
*
* @param text the text of the <code>JRadioButtonMenuItem</code>
*/
public JRadioButtonMenuItem(String text) {
this(text, null, false);
}
/** {@collect.stats}
* Creates a radio button menu item whose properties are taken from the
* <code>Action</code> supplied.
*
* @param a the <code>Action</code> on which to base the radio
* button menu item
*
* @since 1.3
*/
public JRadioButtonMenuItem(Action a) {
this();
setAction(a);
}
/** {@collect.stats}
* Creates a radio button menu item with the specified text
* and <code>Icon</code>.
*
* @param text the text of the <code>JRadioButtonMenuItem</code>
* @param icon the icon to display on the <code>JRadioButtonMenuItem</code>
*/
public JRadioButtonMenuItem(String text, Icon icon) {
this(text, icon, false);
}
/** {@collect.stats}
* Creates a radio button menu item with the specified text
* and selection state.
*
* @param text the text of the <code>CheckBoxMenuItem</code>
* @param selected the selected state of the <code>CheckBoxMenuItem</code>
*/
public JRadioButtonMenuItem(String text, boolean selected) {
this(text);
setSelected(selected);
}
/** {@collect.stats}
* Creates a radio button menu item with the specified image
* and selection state, but no text.
*
* @param icon the image that the button should display
* @param selected if true, the button is initially selected;
* otherwise, the button is initially unselected
*/
public JRadioButtonMenuItem(Icon icon, boolean selected) {
this(null, icon, selected);
}
/** {@collect.stats}
* Creates a radio button menu item that has the specified
* text, image, and selection state. All other constructors
* defer to this one.
*
* @param text the string displayed on the radio button
* @param icon the image that the button should display
*/
public JRadioButtonMenuItem(String text, Icon icon, boolean selected) {
super(text, icon);
setModel(new JToggleButton.ToggleButtonModel());
setSelected(selected);
setFocusable(false);
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "RadioButtonMenuItemUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@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>JRadioButtonMenuItem</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>JRadioButtonMenuItem</code>
*/
protected String paramString() {
return super.paramString();
}
/** {@collect.stats}
* Overriden to return true, JRadioButtonMenuItem supports
* the selected state.
*/
boolean shouldUpdateSelectedStateFromAction() {
return true;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JRadioButtonMenuItem.
* For JRadioButtonMenuItems, the AccessibleContext takes the form of an
* AccessibleJRadioButtonMenuItem.
* A new AccessibleJRadioButtonMenuItem instance is created if necessary.
*
* @return an AccessibleJRadioButtonMenuItem that serves as the
* AccessibleContext of this JRadioButtonMenuItem
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJRadioButtonMenuItem();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JRadioButtonMenuItem</code> class. It provides an
* implementation of the Java Accessibility API appropriate to
* <code>JRadioButtonMenuItem</code> 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 AccessibleJRadioButtonMenuItem extends AccessibleJMenuItem {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.RADIO_BUTTON;
}
} // inner class AccessibleJRadioButtonMenuItem
}
|
Java
|
/*
* Copyright (c) 1997, 2010, 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.Font;
import java.awt.Color;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;
import java.awt.KeyEventPostProcessor;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.security.AccessController;
import javax.swing.plaf.ComponentUI;
import javax.swing.border.Border;
import javax.swing.event.SwingPropertyChangeSupport;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.Locale;
import sun.awt.SunToolkit;
import sun.awt.OSInfo;
import sun.security.action.GetPropertyAction;
import sun.swing.SwingUtilities2;
import java.lang.reflect.Method;
/** {@collect.stats}
* {@code UIManager} manages the current look and feel, the set of
* available look and feels, {@code PropertyChangeListeners} that
* are notified when the look and feel changes, look and feel defaults, and
* convenience methods for obtaining various default values.
*
* <h3>Specifying the look and feel</h3>
*
* The look and feel can be specified in two distinct ways: by
* specifying the fully qualified name of the class for the look and
* feel, or by creating an instance of {@code LookAndFeel} and passing
* it to {@code setLookAndFeel}. The following example illustrates
* setting the look and feel to the system look and feel:
* <pre>
* UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
* </pre>
* The following example illustrates setting the look and feel based on
* class name:
* <pre>
* UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
* </pre>
* Once the look and feel has been changed it is imperative to invoke
* {@code updateUI} on all {@code JComponents}. The method {@link
* SwingUtilities#updateComponentTreeUI} makes it easy to apply {@code
* updateUI} to a containment hierarchy. Refer to it for
* details. The exact behavior of not invoking {@code
* updateUI} after changing the look and feel is
* unspecified. It is very possible to receive unexpected exceptions,
* painting problems, or worse.
*
* <h3>Default look and feel</h3>
*
* The class used for the default look and feel is chosen in the following
* manner:
* <ol>
* <li>If the system property <code>swing.defaultlaf</code> is
* {@code non-null}, use its value as the default look and feel class
* name.
* <li>If the {@link java.util.Properties} file <code>swing.properties</code>
* exists and contains the key <code>swing.defaultlaf</code>,
* use its value as the default look and feel class name. The location
* that is checked for <code>swing.properties</code> may vary depending
* upon the implementation of the Java platform. In Sun's implementation
* the location is <code>${java.home}/lib/swing.properties</code>.
* Refer to the release notes of the implementation being used for
* further details.
* <li>Otherwise use the cross platform look and feel.
* </ol>
*
* <h3>Defaults</h3>
*
* {@code UIManager} manages three sets of {@code UIDefaults}. In order, they
* are:
* <ol>
* <li>Developer defaults. With few exceptions Swing does not
* alter the developer defaults; these are intended to be modified
* and used by the developer.
* <li>Look and feel defaults. The look and feel defaults are
* supplied by the look and feel at the time it is installed as the
* current look and feel ({@code setLookAndFeel()} is invoked). The
* look and feel defaults can be obtained using the {@code
* getLookAndFeelDefaults()} method.
* <li>Sytem defaults. The system defaults are provided by Swing.
* </ol>
* Invoking any of the various {@code get} methods
* results in checking each of the defaults, in order, returning
* the first {@code non-null} value. For example, invoking
* {@code UIManager.getString("Table.foreground")} results in first
* checking developer defaults. If the developer defaults contain
* a value for {@code "Table.foreground"} it is returned, otherwise
* the look and feel defaults are checked, followed by the system defaults.
* <p>
* It's important to note that {@code getDefaults} returns a custom
* instance of {@code UIDefaults} with this resolution logic built into it.
* For example, {@code UIManager.getDefaults().getString("Table.foreground")}
* is equivalent to {@code UIManager.getString("Table.foreground")}. Both
* resolve using the algorithm just described. In many places the
* documentation uses the word defaults to refer to the custom instance
* of {@code UIDefaults} with the resolution logic as previously described.
* <p>
* When the look and feel is changed, {@code UIManager} alters only the
* look and feel defaults; the developer and system defaults are not
* altered by the {@code UIManager} in any way.
* <p>
* The set of defaults a particular look and feel supports is defined
* and documented by that look and feel. In addition, each look and
* feel, or {@code ComponentUI} provided by a look and feel, may
* access the defaults at different times in their life cycle. Some
* look and feels may agressively look up defaults, so that changing a
* default may not have an effect after installing the look and feel.
* Other look and feels may lazily access defaults so that a change to
* the defaults may effect an existing look and feel. Finally, other look
* and feels might not configure themselves from the defaults table in
* any way. None-the-less it is usually the case that a look and feel
* expects certain defaults, so that in general
* a {@code ComponentUI} provided by one look and feel will not
* work with another look and feel.
* <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 Thomas Ball
* @author Hans Muller
*/
public class UIManager implements Serializable
{
/** {@collect.stats}
* This class defines the state managed by the <code>UIManager</code>. For
* Swing applications the fields in this class could just as well
* be static members of <code>UIManager</code> however we give them
* "AppContext"
* scope instead so that applets (and potentially multiple lightweight
* applications running in a single VM) have their own state. For example,
* an applet can alter its look and feel, see <code>setLookAndFeel</code>.
* Doing so has no affect on other applets (or the browser).
*/
private static class LAFState
{
Properties swingProps;
private UIDefaults[] tables = new UIDefaults[2];
boolean initialized = false;
MultiUIDefaults multiUIDefaults = new MultiUIDefaults(tables);
LookAndFeel lookAndFeel;
LookAndFeel multiLookAndFeel = null;
Vector auxLookAndFeels = null;
SwingPropertyChangeSupport changeSupport;
LookAndFeelInfo[] installedLAFs;
UIDefaults getLookAndFeelDefaults() { return tables[0]; }
void setLookAndFeelDefaults(UIDefaults x) { tables[0] = x; }
UIDefaults getSystemDefaults() { return tables[1]; }
void setSystemDefaults(UIDefaults x) { tables[1] = x; }
/** {@collect.stats}
* Returns the SwingPropertyChangeSupport for the current
* AppContext. If <code>create</code> is a true, a non-null
* <code>SwingPropertyChangeSupport</code> will be returned, if
* <code>create</code> is false and this has not been invoked
* with true, null will be returned.
*/
public synchronized SwingPropertyChangeSupport
getPropertyChangeSupport(boolean create) {
if (create && changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(
UIManager.class);
}
return changeSupport;
}
}
/* Lock object used in place of class object for synchronization. (4187686)
*/
private static final Object classLock = new Object();
/** {@collect.stats}
* Return the <code>LAFState</code> object, lazily create one if necessary.
* All access to the <code>LAFState</code> fields is done via this method,
* for example:
* <pre>
* getLAFState().initialized = true;
* </pre>
*/
private static LAFState getLAFState() {
LAFState rv = (LAFState)SwingUtilities.appContextGet(
SwingUtilities2.LAF_STATE_KEY);
if (rv == null) {
synchronized (classLock) {
rv = (LAFState)SwingUtilities.appContextGet(
SwingUtilities2.LAF_STATE_KEY);
if (rv == null) {
SwingUtilities.appContextPut(
SwingUtilities2.LAF_STATE_KEY,
(rv = new LAFState()));
}
}
}
return rv;
}
/* Keys used for the properties file in <java.home>/lib/swing.properties.
* See loadUserProperties(), initialize().
*/
private static final String defaultLAFKey = "swing.defaultlaf";
private static final String auxiliaryLAFsKey = "swing.auxiliarylaf";
private static final String multiplexingLAFKey = "swing.plaf.multiplexinglaf";
private static final String installedLAFsKey = "swing.installedlafs";
private static final String disableMnemonicKey = "swing.disablenavaids";
/** {@collect.stats}
* Return a swing.properties file key for the attribute of specified
* look and feel. The attr is either "name" or "class", a typical
* key would be: "swing.installedlaf.windows.name"
*/
private static String makeInstalledLAFKey(String laf, String attr) {
return "swing.installedlaf." + laf + "." + attr;
}
/** {@collect.stats}
* The filename for swing.properties is a path like this (Unix version):
* <java.home>/lib/swing.properties. This method returns a bogus
* filename if java.home isn't defined.
*/
private static String makeSwingPropertiesFilename() {
String sep = File.separator;
// No need to wrap this in a doPrivileged as it's called from
// a doPrivileged.
String javaHome = System.getProperty("java.home");
if (javaHome == null) {
javaHome = "<java.home undefined>";
}
return javaHome + sep + "lib" + sep + "swing.properties";
}
/** {@collect.stats}
* Provides a little information about an installed
* <code>LookAndFeel</code> for the sake of configuring a menu or
* for initial application set up.
*
* @see UIManager#getInstalledLookAndFeels
* @see LookAndFeel
*/
public static class LookAndFeelInfo {
private String name;
private String className;
/** {@collect.stats}
* Constructs a <code>UIManager</code>s
* <code>LookAndFeelInfo</code> object.
*
* @param name a <code>String</code> specifying the name of
* the look and feel
* @param className a <code>String</code> specifiying the name of
* the class that implements the look and feel
*/
public LookAndFeelInfo(String name, String className) {
this.name = name;
this.className = className;
}
/** {@collect.stats}
* Returns the name of the look and feel in a form suitable
* for a menu or other presentation
* @return a <code>String</code> containing the name
* @see LookAndFeel#getName
*/
public String getName() {
return name;
}
/** {@collect.stats}
* Returns the name of the class that implements this look and feel.
* @return the name of the class that implements this
* <code>LookAndFeel</code>
* @see LookAndFeel
*/
public String getClassName() {
return className;
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a <code>String</code> representation of this object
*/
public String toString() {
return getClass().getName() + "[" + getName() + " " + getClassName() + "]";
}
}
/** {@collect.stats}
* The default value of <code>installedLAFS</code> is used when no
* swing.properties
* file is available or if the file doesn't contain a "swing.installedlafs"
* property.
*
* @see #initializeInstalledLAFs
*/
private static LookAndFeelInfo[] installedLAFs;
static {
ArrayList iLAFs = new ArrayList(4);
iLAFs.add(new LookAndFeelInfo(
"Metal", "javax.swing.plaf.metal.MetalLookAndFeel"));
iLAFs.add(new LookAndFeelInfo(
"Nimbus", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"));
iLAFs.add(new LookAndFeelInfo("CDE/Motif",
"com.sun.java.swing.plaf.motif.MotifLookAndFeel"));
// Only include windows on Windows boxs.
OSInfo.OSType osType = AccessController.doPrivileged(OSInfo.getOSTypeAction());
if (osType == OSInfo.OSType.WINDOWS) {
iLAFs.add(new LookAndFeelInfo("Windows",
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel"));
if (Toolkit.getDefaultToolkit().getDesktopProperty(
"win.xpstyle.themeActive") != null) {
iLAFs.add(new LookAndFeelInfo("Windows Classic",
"com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"));
}
}
else {
// GTK is not shipped on Windows.
iLAFs.add(new LookAndFeelInfo("GTK+",
"com.sun.java.swing.plaf.gtk.GTKLookAndFeel"));
}
installedLAFs = (LookAndFeelInfo[])iLAFs.toArray(
new LookAndFeelInfo[iLAFs.size()]);
}
/** {@collect.stats}
* Returns an array of {@code LookAndFeelInfo}s representing the
* {@code LookAndFeel} implementations currently available. The
* <code>LookAndFeelInfo</code> objects can be used by an
* application to construct a menu of look and feel options for
* the user, or to determine which look and feel to set at startup
* time. To avoid the penalty of creating numerous {@code
* LookAndFeel} objects, {@code LookAndFeelInfo} maintains the
* class name of the {@code LookAndFeel} class, not the actual
* {@code LookAndFeel} instance.
* <p>
* The following example illustrates setting the current look and feel
* from an instance of {@code LookAndFeelInfo}:
* <pre>
* UIManager.setLookAndFeel(info.getClassName());
* </pre>
*
* @return an array of <code>LookAndFeelInfo</code> objects
* @see #setLookAndFeel
*/
public static LookAndFeelInfo[] getInstalledLookAndFeels() {
maybeInitialize();
LookAndFeelInfo[] ilafs = getLAFState().installedLAFs;
if (ilafs == null) {
ilafs = installedLAFs;
}
LookAndFeelInfo[] rv = new LookAndFeelInfo[ilafs.length];
System.arraycopy(ilafs, 0, rv, 0, ilafs.length);
return rv;
}
/** {@collect.stats}
* Sets the set of available look and feels. While this method does
* not check to ensure all of the {@code LookAndFeelInfos} are
* {@code non-null}, it is strongly recommended that only {@code non-null}
* values are supplied in the {@code infos} array.
*
* @param infos set of <code>LookAndFeelInfo</code> objects specifying
* the available look and feels
*
* @see #getInstalledLookAndFeels
* @throws NullPointerException if {@code infos} is {@code null}
*/
public static void setInstalledLookAndFeels(LookAndFeelInfo[] infos)
throws SecurityException
{
maybeInitialize();
LookAndFeelInfo[] newInfos = new LookAndFeelInfo[infos.length];
System.arraycopy(infos, 0, newInfos, 0, infos.length);
getLAFState().installedLAFs = newInfos;
}
/** {@collect.stats}
* Adds the specified look and feel to the set of available look
* and feels. While this method allows a {@code null} {@code info},
* it is strongly recommended that a {@code non-null} value be used.
*
* @param info a <code>LookAndFeelInfo</code> object that names the
* look and feel and identifies the class that implements it
* @see #setInstalledLookAndFeels
*/
public static void installLookAndFeel(LookAndFeelInfo info) {
LookAndFeelInfo[] infos = getInstalledLookAndFeels();
LookAndFeelInfo[] newInfos = new LookAndFeelInfo[infos.length + 1];
System.arraycopy(infos, 0, newInfos, 0, infos.length);
newInfos[infos.length] = info;
setInstalledLookAndFeels(newInfos);
}
/** {@collect.stats}
* Adds the specified look and feel to the set of available look
* and feels. While this method does not check the
* arguments in any way, it is strongly recommended that {@code
* non-null} values be supplied.
*
* @param name descriptive name of the look and feel
* @param className name of the class that implements the look and feel
* @see #setInstalledLookAndFeels
*/
public static void installLookAndFeel(String name, String className) {
installLookAndFeel(new LookAndFeelInfo(name, className));
}
/** {@collect.stats}
* Returns the current look and feel or <code>null</code>.
*
* @return current look and feel, or <code>null</code>
* @see #setLookAndFeel
*/
public static LookAndFeel getLookAndFeel() {
maybeInitialize();
return getLAFState().lookAndFeel;
}
/** {@collect.stats}
* Sets the current look and feel to {@code newLookAndFeel}.
* If the current look and feel is {@code non-null} {@code
* uninitialize} is invoked on it. If {@code newLookAndFeel} is
* {@code non-null}, {@code initialize} is invoked on it followed
* by {@code getDefaults}. The defaults returned from {@code
* newLookAndFeel.getDefaults()} replace those of the defaults
* from the previous look and feel. If the {@code newLookAndFeel} is
* {@code null}, the look and feel defaults are set to {@code null}.
* <p>
* A value of {@code null} can be used to set the look and feel
* to {@code null}. As the {@code LookAndFeel} is required for
* most of Swing to function, setting the {@code LookAndFeel} to
* {@code null} is strongly discouraged.
* <p>
* This is a JavaBeans bound property.
*
* @param newLookAndFeel {@code LookAndFeel} to install
* @throws UnsupportedLookAndFeelException if
* {@code newLookAndFeel} is {@code non-null} and
* {@code newLookAndFeel.isSupportedLookAndFeel()} returns
* {@code false}
* @see #getLookAndFeel
*/
public static void setLookAndFeel(LookAndFeel newLookAndFeel)
throws UnsupportedLookAndFeelException
{
if ((newLookAndFeel != null) && !newLookAndFeel.isSupportedLookAndFeel()) {
String s = newLookAndFeel.toString() + " not supported on this platform";
throw new UnsupportedLookAndFeelException(s);
}
LAFState lafState = getLAFState();
LookAndFeel oldLookAndFeel = lafState.lookAndFeel;
if (oldLookAndFeel != null) {
oldLookAndFeel.uninitialize();
}
lafState.lookAndFeel = newLookAndFeel;
if (newLookAndFeel != null) {
sun.swing.DefaultLookup.setDefaultLookup(null);
newLookAndFeel.initialize();
lafState.setLookAndFeelDefaults(newLookAndFeel.getDefaults());
}
else {
lafState.setLookAndFeelDefaults(null);
}
SwingPropertyChangeSupport changeSupport = lafState.
getPropertyChangeSupport(false);
if (changeSupport != null) {
changeSupport.firePropertyChange("lookAndFeel", oldLookAndFeel,
newLookAndFeel);
}
}
/** {@collect.stats}
* Loads the {@code LookAndFeel} specified by the given class
* name, using the current thread's context class loader, and
* passes it to {@code setLookAndFeel(LookAndFeel)}.
*
* @param className a string specifying the name of the class that implements
* the look and feel
* @exception ClassNotFoundException if the <code>LookAndFeel</code>
* class could not be found
* @exception InstantiationException if a new instance of the class
* couldn't be created
* @exception IllegalAccessException if the class or initializer isn't accessible
* @exception UnsupportedLookAndFeelException if
* <code>lnf.isSupportedLookAndFeel()</code> is false
* @throws ClassCastException if {@code className} does not identify
* a class that extends {@code LookAndFeel}
*/
public static void setLookAndFeel(String className)
throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
UnsupportedLookAndFeelException
{
if ("javax.swing.plaf.metal.MetalLookAndFeel".equals(className)) {
// Avoid reflection for the common case of metal.
setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel());
}
else {
Class lnfClass = SwingUtilities.loadSystemClass(className);
setLookAndFeel((LookAndFeel)(lnfClass.newInstance()));
}
}
/** {@collect.stats}
* Returns the name of the <code>LookAndFeel</code> class that implements
* the native system look and feel if there is one, otherwise
* the name of the default cross platform <code>LookAndFeel</code>
* class. This value can be overriden by setting the
* <code>swing.systemlaf</code> system property.
*
* @return the <code>String</code> of the <code>LookAndFeel</code>
* class
*
* @see #setLookAndFeel
* @see #getCrossPlatformLookAndFeelClassName
*/
public static String getSystemLookAndFeelClassName() {
String systemLAF = AccessController.doPrivileged(
new GetPropertyAction("swing.systemlaf"));
if (systemLAF != null) {
return systemLAF;
}
OSInfo.OSType osType = AccessController.doPrivileged(OSInfo.getOSTypeAction());
if (osType == OSInfo.OSType.WINDOWS) {
return "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
} else {
String desktop = AccessController.doPrivileged(new GetPropertyAction("sun.desktop"));
Toolkit toolkit = Toolkit.getDefaultToolkit();
if ("gnome".equals(desktop) &&
toolkit instanceof SunToolkit &&
((SunToolkit) toolkit).isNativeGTKAvailable()) {
// May be set on Linux and Solaris boxs.
return "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
}
if (osType == OSInfo.OSType.SOLARIS) {
return "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
}
}
return getCrossPlatformLookAndFeelClassName();
}
/** {@collect.stats}
* Returns the name of the <code>LookAndFeel</code> class that implements
* the default cross platform look and feel -- the Java
* Look and Feel (JLF). This value can be overriden by setting the
* <code>swing.crossplatformlaf</code> system property.
*
* @return a string with the JLF implementation-class
* @see #setLookAndFeel
* @see #getSystemLookAndFeelClassName
*/
public static String getCrossPlatformLookAndFeelClassName() {
String laf = (String)AccessController.doPrivileged(
new GetPropertyAction("swing.crossplatformlaf"));
if (laf != null) {
return laf;
}
return "javax.swing.plaf.metal.MetalLookAndFeel";
}
/** {@collect.stats}
* Returns the defaults. The returned defaults resolve using the
* logic specified in the class documentation.
*
* @return a <code>UIDefaults</code> object containing the default values
*/
public static UIDefaults getDefaults() {
maybeInitialize();
return getLAFState().multiUIDefaults;
}
/** {@collect.stats}
* Returns a font from the defaults. If the value for {@code key} is
* not a {@code Font}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the font
* @return the <code>Font</code> object
* @throws NullPointerException if {@code key} is {@code null}
*/
public static Font getFont(Object key) {
return getDefaults().getFont(key);
}
/** {@collect.stats}
* Returns a font from the defaults that is appropriate
* for the given locale. If the value for {@code key} is
* not a {@code Font}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the font
* @param l the <code>Locale</code> for which the font is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the <code>Font</code> object
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static Font getFont(Object key, Locale l) {
return getDefaults().getFont(key,l);
}
/** {@collect.stats}
* Returns a color from the defaults. If the value for {@code key} is
* not a {@code Color}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the color
* @return the <code>Color</code> object
* @throws NullPointerException if {@code key} is {@code null}
*/
public static Color getColor(Object key) {
return getDefaults().getColor(key);
}
/** {@collect.stats}
* Returns a color from the defaults that is appropriate
* for the given locale. If the value for {@code key} is
* not a {@code Color}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the color
* @param l the <code>Locale</code> for which the color is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the <code>Color</code> object
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static Color getColor(Object key, Locale l) {
return getDefaults().getColor(key,l);
}
/** {@collect.stats}
* Returns an <code>Icon</code> from the defaults. If the value for
* {@code key} is not an {@code Icon}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the icon
* @return the <code>Icon</code> object
* @throws NullPointerException if {@code key} is {@code null}
*/
public static Icon getIcon(Object key) {
return getDefaults().getIcon(key);
}
/** {@collect.stats}
* Returns an <code>Icon</code> from the defaults that is appropriate
* for the given locale. If the value for
* {@code key} is not an {@code Icon}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the icon
* @param l the <code>Locale</code> for which the icon is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the <code>Icon</code> object
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static Icon getIcon(Object key, Locale l) {
return getDefaults().getIcon(key,l);
}
/** {@collect.stats}
* Returns a border from the defaults. If the value for
* {@code key} is not a {@code Border}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the border
* @return the <code>Border</code> object
* @throws NullPointerException if {@code key} is {@code null}
*/
public static Border getBorder(Object key) {
return getDefaults().getBorder(key);
}
/** {@collect.stats}
* Returns a border from the defaults that is appropriate
* for the given locale. If the value for
* {@code key} is not a {@code Border}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the border
* @param l the <code>Locale</code> for which the border is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the <code>Border</code> object
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static Border getBorder(Object key, Locale l) {
return getDefaults().getBorder(key,l);
}
/** {@collect.stats}
* Returns a string from the defaults. If the value for
* {@code key} is not a {@code String}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the string
* @return the <code>String</code>
* @throws NullPointerException if {@code key} is {@code null}
*/
public static String getString(Object key) {
return getDefaults().getString(key);
}
/** {@collect.stats}
* Returns a string from the defaults that is appropriate for the
* given locale. If the value for
* {@code key} is not a {@code String}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the string
* @param l the <code>Locale</code> for which the string is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the <code>String</code>
* @since 1.4
* @throws NullPointerException if {@code key} is {@code null}
*/
public static String getString(Object key, Locale l) {
return getDefaults().getString(key,l);
}
/** {@collect.stats}
* Returns a string from the defaults that is appropriate for the
* given locale. If the value for
* {@code key} is not a {@code String}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the string
* @param c {@code Component} used to determine the locale;
* {@code null} implies the default locale as
* returned by {@code Locale.getDefault()}
* @return the <code>String</code>
* @throws NullPointerException if {@code key} is {@code null}
*/
static String getString(Object key, Component c) {
Locale l = (c == null) ? Locale.getDefault() : c.getLocale();
return getString(key, l);
}
/** {@collect.stats}
* Returns an integer from the defaults. If the value for
* {@code key} is not an {@code Integer}, or does not exist,
* {@code 0} is returned.
*
* @param key an <code>Object</code> specifying the int
* @return the int
* @throws NullPointerException if {@code key} is {@code null}
*/
public static int getInt(Object key) {
return getDefaults().getInt(key);
}
/** {@collect.stats}
* Returns an integer from the defaults that is appropriate
* for the given locale. If the value for
* {@code key} is not an {@code Integer}, or does not exist,
* {@code 0} is returned.
*
* @param key an <code>Object</code> specifying the int
* @param l the <code>Locale</code> for which the int is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the int
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static int getInt(Object key, Locale l) {
return getDefaults().getInt(key,l);
}
/** {@collect.stats}
* Returns a boolean from the defaults which is associated with
* the key value. If the key is not found or the key doesn't represent
* a boolean value then {@code false} is returned.
*
* @param key an <code>Object</code> specifying the key for the desired boolean value
* @return the boolean value corresponding to the key
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static boolean getBoolean(Object key) {
return getDefaults().getBoolean(key);
}
/** {@collect.stats}
* Returns a boolean from the defaults which is associated with
* the key value and the given <code>Locale</code>. If the key is not
* found or the key doesn't represent
* a boolean value then {@code false} will be returned.
*
* @param key an <code>Object</code> specifying the key for the desired
* boolean value
* @param l the <code>Locale</code> for which the boolean is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the boolean value corresponding to the key
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static boolean getBoolean(Object key, Locale l) {
return getDefaults().getBoolean(key,l);
}
/** {@collect.stats}
* Returns an <code>Insets</code> object from the defaults. If the value
* for {@code key} is not an {@code Insets}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the <code>Insets</code> object
* @return the <code>Insets</code> object
* @throws NullPointerException if {@code key} is {@code null}
*/
public static Insets getInsets(Object key) {
return getDefaults().getInsets(key);
}
/** {@collect.stats}
* Returns an <code>Insets</code> object from the defaults that is
* appropriate for the given locale. If the value
* for {@code key} is not an {@code Insets}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the <code>Insets</code> object
* @param l the <code>Locale</code> for which the object is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the <code>Insets</code> object
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static Insets getInsets(Object key, Locale l) {
return getDefaults().getInsets(key,l);
}
/** {@collect.stats}
* Returns a dimension from the defaults. If the value
* for {@code key} is not a {@code Dimension}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the dimension object
* @return the <code>Dimension</code> object
* @throws NullPointerException if {@code key} is {@code null}
*/
public static Dimension getDimension(Object key) {
return getDefaults().getDimension(key);
}
/** {@collect.stats}
* Returns a dimension from the defaults that is appropriate
* for the given locale. If the value
* for {@code key} is not a {@code Dimension}, {@code null} is returned.
*
* @param key an <code>Object</code> specifying the dimension object
* @param l the <code>Locale</code> for which the object is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the <code>Dimension</code> object
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static Dimension getDimension(Object key, Locale l) {
return getDefaults().getDimension(key,l);
}
/** {@collect.stats}
* Returns an object from the defaults.
*
* @param key an <code>Object</code> specifying the desired object
* @return the <code>Object</code>
* @throws NullPointerException if {@code key} is {@code null}
*/
public static Object get(Object key) {
return getDefaults().get(key);
}
/** {@collect.stats}
* Returns an object from the defaults that is appropriate for
* the given locale.
*
* @param key an <code>Object</code> specifying the desired object
* @param l the <code>Locale</code> for which the object is desired; refer
* to {@code UIDefaults} for details on how a {@code null}
* {@code Locale} is handled
* @return the <code>Object</code>
* @throws NullPointerException if {@code key} is {@code null}
* @since 1.4
*/
public static Object get(Object key, Locale l) {
return getDefaults().get(key,l);
}
/** {@collect.stats}
* Stores an object in the developer defaults. This is a cover method
* for {@code getDefaults().put(key, value)}. This only effects the
* developer defaults, not the system or look and feel defaults.
*
* @param key an <code>Object</code> specifying the retrieval key
* @param value the <code>Object</code> to store; refer to
* {@code UIDefaults} for details on how {@code null} is
* handled
* @return the <code>Object</code> returned by {@link UIDefaults#put}
* @throws NullPointerException if {@code key} is {@code null}
* @see UIDefaults#put
*/
public static Object put(Object key, Object value) {
return getDefaults().put(key, value);
}
/** {@collect.stats}
* Returns the appropriate {@code ComponentUI} implementation for
* {@code target}. Typically, this is a cover for
* {@code getDefaults().getUI(target)}. However, if an auxiliary
* look and feel has been installed, this first invokes
* {@code getUI(target)} on the multiplexing look and feel's
* defaults, and returns that value if it is {@code non-null}.
*
* @param target the <code>JComponent</code> to return the
* {@code ComponentUI} for
* @return the <code>ComponentUI</code> object for {@code target}
* @throws NullPointerException if {@code target} is {@code null}
* @see UIDefaults#getUI
*/
public static ComponentUI getUI(JComponent target) {
maybeInitialize();
ComponentUI ui = null;
LookAndFeel multiLAF = getLAFState().multiLookAndFeel;
if (multiLAF != null) {
// This can return null if the multiplexing look and feel
// doesn't support a particular UI.
ui = multiLAF.getDefaults().getUI(target);
}
if (ui == null) {
ui = getDefaults().getUI(target);
}
return ui;
}
/** {@collect.stats}
* Returns the {@code UIDefaults} from the current look and feel,
* that were obtained at the time the look and feel was installed.
* <p>
* In general, developers should use the {@code UIDefaults} returned from
* {@code getDefaults()}. As the current look and feel may expect
* certain values to exist, altering the {@code UIDefaults} returned
* from this method could have unexpected results.
*
* @return <code>UIDefaults</code> from the current look and feel
* @see #getDefaults
* @see #setLookAndFeel(LookAndFeel)
* @see LookAndFeel#getDefaults
*/
public static UIDefaults getLookAndFeelDefaults() {
maybeInitialize();
return getLAFState().getLookAndFeelDefaults();
}
/** {@collect.stats}
* Finds the Multiplexing <code>LookAndFeel</code>.
*/
private static LookAndFeel getMultiLookAndFeel() {
LookAndFeel multiLookAndFeel = getLAFState().multiLookAndFeel;
if (multiLookAndFeel == null) {
String defaultName = "javax.swing.plaf.multi.MultiLookAndFeel";
String className = getLAFState().swingProps.getProperty(multiplexingLAFKey, defaultName);
try {
Class lnfClass = SwingUtilities.loadSystemClass(className);
multiLookAndFeel = (LookAndFeel)lnfClass.newInstance();
} catch (Exception exc) {
System.err.println("UIManager: failed loading " + className);
}
}
return multiLookAndFeel;
}
/** {@collect.stats}
* Adds a <code>LookAndFeel</code> to the list of auxiliary look and feels.
* The auxiliary look and feels tell the multiplexing look and feel what
* other <code>LookAndFeel</code> classes for a component instance are to be used
* in addition to the default <code>LookAndFeel</code> class when creating a
* multiplexing UI. The change will only take effect when a new
* UI class is created or when the default look and feel is changed
* on a component instance.
* <p>Note these are not the same as the installed look and feels.
*
* @param laf the <code>LookAndFeel</code> object
* @see #removeAuxiliaryLookAndFeel
* @see #setLookAndFeel
* @see #getAuxiliaryLookAndFeels
* @see #getInstalledLookAndFeels
*/
static public void addAuxiliaryLookAndFeel(LookAndFeel laf) {
maybeInitialize();
if (!laf.isSupportedLookAndFeel()) {
// Ideally we would throw an exception here, but it's too late
// for that.
return;
}
Vector v = getLAFState().auxLookAndFeels;
if (v == null) {
v = new Vector();
}
if (!v.contains(laf)) {
v.addElement(laf);
laf.initialize();
getLAFState().auxLookAndFeels = v;
if (getLAFState().multiLookAndFeel == null) {
getLAFState().multiLookAndFeel = getMultiLookAndFeel();
}
}
}
/** {@collect.stats}
* Removes a <code>LookAndFeel</code> from the list of auxiliary look and feels.
* The auxiliary look and feels tell the multiplexing look and feel what
* other <code>LookAndFeel</code> classes for a component instance are to be used
* in addition to the default <code>LookAndFeel</code> class when creating a
* multiplexing UI. The change will only take effect when a new
* UI class is created or when the default look and feel is changed
* on a component instance.
* <p>Note these are not the same as the installed look and feels.
* @return true if the <code>LookAndFeel</code> was removed from the list
* @see #removeAuxiliaryLookAndFeel
* @see #getAuxiliaryLookAndFeels
* @see #setLookAndFeel
* @see #getInstalledLookAndFeels
*/
static public boolean removeAuxiliaryLookAndFeel(LookAndFeel laf) {
maybeInitialize();
boolean result;
Vector v = getLAFState().auxLookAndFeels;
if ((v == null) || (v.size() == 0)) {
return false;
}
result = v.removeElement(laf);
if (result) {
if (v.size() == 0) {
getLAFState().auxLookAndFeels = null;
getLAFState().multiLookAndFeel = null;
} else {
getLAFState().auxLookAndFeels = v;
}
}
laf.uninitialize();
return result;
}
/** {@collect.stats}
* Returns the list of auxiliary look and feels (can be <code>null</code>).
* The auxiliary look and feels tell the multiplexing look and feel what
* other <code>LookAndFeel</code> classes for a component instance are
* to be used in addition to the default LookAndFeel class when creating a
* multiplexing UI.
* <p>Note these are not the same as the installed look and feels.
*
* @return list of auxiliary <code>LookAndFeel</code>s or <code>null</code>
* @see #addAuxiliaryLookAndFeel
* @see #removeAuxiliaryLookAndFeel
* @see #setLookAndFeel
* @see #getInstalledLookAndFeels
*/
static public LookAndFeel[] getAuxiliaryLookAndFeels() {
maybeInitialize();
Vector v = getLAFState().auxLookAndFeels;
if ((v == null) || (v.size() == 0)) {
return null;
}
else {
LookAndFeel[] rv = new LookAndFeel[v.size()];
for (int i = 0; i < rv.length; i++) {
rv[i] = (LookAndFeel)v.elementAt(i);
}
return rv;
}
}
/** {@collect.stats}
* Adds a <code>PropertyChangeListener</code> to the listener list.
* The listener is registered for all properties.
*
* @param listener the <code>PropertyChangeListener</code> to be added
* @see java.beans.PropertyChangeSupport
*/
public static void addPropertyChangeListener(PropertyChangeListener listener)
{
synchronized (classLock) {
getLAFState().getPropertyChangeSupport(true).
addPropertyChangeListener(listener);
}
}
/** {@collect.stats}
* Removes a <code>PropertyChangeListener</code> from the listener list.
* This removes a <code>PropertyChangeListener</code> that was registered
* for all properties.
*
* @param listener the <code>PropertyChangeListener</code> to be removed
* @see java.beans.PropertyChangeSupport
*/
public static void removePropertyChangeListener(PropertyChangeListener listener)
{
synchronized (classLock) {
getLAFState().getPropertyChangeSupport(true).
removePropertyChangeListener(listener);
}
}
/** {@collect.stats}
* Returns an array of all the <code>PropertyChangeListener</code>s added
* to this UIManager with addPropertyChangeListener().
*
* @return all of the <code>PropertyChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public static PropertyChangeListener[] getPropertyChangeListeners() {
synchronized(classLock) {
return getLAFState().getPropertyChangeSupport(true).
getPropertyChangeListeners();
}
}
private static Properties loadSwingProperties()
{
/* Don't bother checking for Swing properties if untrusted, as
* there's no way to look them up without triggering SecurityExceptions.
*/
if (UIManager.class.getClassLoader() != null) {
return new Properties();
}
else {
final Properties props = new Properties();
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
try {
File file = new File(makeSwingPropertiesFilename());
if (file.exists()) {
// InputStream has been buffered in Properties
// class
FileInputStream ins = new FileInputStream(file);
props.load(ins);
ins.close();
}
}
catch (Exception e) {
// No such file, or file is otherwise non-readable.
}
// Check whether any properties were overridden at the
// command line.
checkProperty(props, defaultLAFKey);
checkProperty(props, auxiliaryLAFsKey);
checkProperty(props, multiplexingLAFKey);
checkProperty(props, installedLAFsKey);
checkProperty(props, disableMnemonicKey);
// Don't care about return value.
return null;
}
});
return props;
}
}
private static void checkProperty(Properties props, String key) {
// No need to do catch the SecurityException here, this runs
// in a doPrivileged.
String value = System.getProperty(key);
if (value != null) {
props.put(key, value);
}
}
/** {@collect.stats}
* If a swing.properties file exist and it has a swing.installedlafs property
* then initialize the <code>installedLAFs</code> field.
*
* @see #getInstalledLookAndFeels
*/
private static void initializeInstalledLAFs(Properties swingProps)
{
String ilafsString = swingProps.getProperty(installedLAFsKey);
if (ilafsString == null) {
return;
}
/* Create a vector that contains the value of the swing.installedlafs
* property. For example given "swing.installedlafs=motif,windows"
* lafs = {"motif", "windows"}.
*/
Vector lafs = new Vector();
StringTokenizer st = new StringTokenizer(ilafsString, ",", false);
while (st.hasMoreTokens()) {
lafs.addElement(st.nextToken());
}
/* Look up the name and class for each name in the "swing.installedlafs"
* list. If they both exist then add a LookAndFeelInfo to
* the installedLafs array.
*/
Vector ilafs = new Vector(lafs.size());
for(int i = 0; i < lafs.size(); i++) {
String laf = (String)lafs.elementAt(i);
String name = swingProps.getProperty(makeInstalledLAFKey(laf, "name"), laf);
String cls = swingProps.getProperty(makeInstalledLAFKey(laf, "class"));
if (cls != null) {
ilafs.addElement(new LookAndFeelInfo(name, cls));
}
}
LookAndFeelInfo[] installedLAFs = new LookAndFeelInfo[ilafs.size()];
for(int i = 0; i < ilafs.size(); i++) {
installedLAFs[i] = (LookAndFeelInfo)(ilafs.elementAt(i));
}
getLAFState().installedLAFs = installedLAFs;
}
/** {@collect.stats}
* If the user has specified a default look and feel, use that.
* Otherwise use the look and feel that's native to this platform.
* If this code is called after the application has explicitly
* set it's look and feel, do nothing.
*
* @see #maybeInitialize
*/
private static void initializeDefaultLAF(Properties swingProps)
{
if (getLAFState().lookAndFeel != null) {
return;
}
String metalLnf = getCrossPlatformLookAndFeelClassName();
String lnfDefault = metalLnf;
String lnfName = "<undefined>" ;
try {
lnfName = swingProps.getProperty(defaultLAFKey, lnfDefault);
setLookAndFeel(lnfName);
} catch (Exception e) {
try {
lnfName = swingProps.getProperty(defaultLAFKey, metalLnf);
setLookAndFeel(lnfName);
} catch (Exception e2) {
throw new Error("can't load " + lnfName);
}
}
}
private static void initializeAuxiliaryLAFs(Properties swingProps)
{
String auxLookAndFeelNames = swingProps.getProperty(auxiliaryLAFsKey);
if (auxLookAndFeelNames == null) {
return;
}
Vector auxLookAndFeels = new Vector();
StringTokenizer p = new StringTokenizer(auxLookAndFeelNames,",");
String factoryName;
/* Try to load each LookAndFeel subclass in the list.
*/
while (p.hasMoreTokens()) {
String className = p.nextToken();
try {
Class lnfClass = SwingUtilities.loadSystemClass(className);
LookAndFeel newLAF = (LookAndFeel)lnfClass.newInstance();
newLAF.initialize();
auxLookAndFeels.addElement(newLAF);
}
catch (Exception e) {
System.err.println("UIManager: failed loading auxiliary look and feel " + className);
}
}
/* If there were problems and no auxiliary look and feels were
* loaded, make sure we reset auxLookAndFeels to null.
* Otherwise, we are going to use the MultiLookAndFeel to get
* all component UI's, so we need to load it now.
*/
if (auxLookAndFeels.size() == 0) {
auxLookAndFeels = null;
}
else {
getLAFState().multiLookAndFeel = getMultiLookAndFeel();
if (getLAFState().multiLookAndFeel == null) {
auxLookAndFeels = null;
}
}
getLAFState().auxLookAndFeels = auxLookAndFeels;
}
private static void initializeSystemDefaults(Properties swingProps) {
getLAFState().swingProps = swingProps;
}
/*
* This method is called before any code that depends on the
* <code>AppContext</code> specific LAFState object runs. When the AppContext
* corresponds to a set of applets it's possible for this method
* to be re-entered, which is why we grab a lock before calling
* initialize().
*/
private static void maybeInitialize() {
synchronized (classLock) {
if (!getLAFState().initialized) {
getLAFState().initialized = true;
initialize();
}
}
}
/*
* Only called by maybeInitialize().
*/
private static void initialize() {
Properties swingProps = loadSwingProperties();
initializeSystemDefaults(swingProps);
initializeDefaultLAF(swingProps);
initializeAuxiliaryLAFs(swingProps);
initializeInstalledLAFs(swingProps);
// Enable the Swing default LayoutManager.
String toolkitName = Toolkit.getDefaultToolkit().getClass().getName();
// don't set default policy if this is XAWT.
if (!"sun.awt.X11.XToolkit".equals(toolkitName)) {
if (FocusManager.isFocusManagerEnabled()) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
setDefaultFocusTraversalPolicy(
new LayoutFocusTraversalPolicy());
}
}
// Install Swing's PaintEventDispatcher
if (RepaintManager.HANDLE_TOP_LEVEL_PAINT) {
sun.awt.PaintEventDispatcher.setPaintEventDispatcher(
new SwingPaintEventDispatcher());
}
// Install a hook that will be invoked if no one consumes the
// KeyEvent. If the source isn't a JComponent this will process
// key bindings, if the source is a JComponent it implies that
// processKeyEvent was already invoked and thus no need to process
// the bindings again, unless the Component is disabled, in which
// case KeyEvents will no longer be dispatched to it so that we
// handle it here.
KeyboardFocusManager.getCurrentKeyboardFocusManager().
addKeyEventPostProcessor(new KeyEventPostProcessor() {
public boolean postProcessKeyEvent(KeyEvent e) {
Component c = e.getComponent();
if ((!(c instanceof JComponent) ||
(c != null && !((JComponent)c).isEnabled())) &&
JComponent.KeyboardState.shouldProcess(e) &&
SwingUtilities.processKeyBindings(e)) {
e.consume();
return true;
}
return false;
}
});
try {
Method setRequestFocusControllerM = java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction<Method>() {
public Method run() throws Exception {
Method method =
Component.class.getDeclaredMethod("setRequestFocusController",
sun.awt.RequestFocusController.class);
method.setAccessible(true);
return method;
}
});
setRequestFocusControllerM.invoke(null, JComponent.focusController);
} catch (Exception e) {
// perhaps we should log this
assert false;
}
}
}
|
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;
import java.awt.*;
/** {@collect.stats}
* This class has been obsoleted by the 1.4 focus APIs. While client code may
* still use this class, developers are strongly encouraged to use
* <code>java.awt.KeyboardFocusManager</code> and
* <code>java.awt.DefaultKeyboardFocusManager</code> instead.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>, and the
* <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
* for more information.
*
* @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
*
* @author Arnaud Weber
* @author David Mendenhall
*/
public abstract class FocusManager extends DefaultKeyboardFocusManager {
/** {@collect.stats}
* This field is obsolete, and its use is discouraged since its
* specification is incompatible with the 1.4 focus APIs.
* The current FocusManager is no longer a property of the UI.
* Client code must query for the current FocusManager using
* <code>KeyboardFocusManager.getCurrentKeyboardFocusManager()</code>.
* See the Focus Specification for more information.
*
* @see java.awt.KeyboardFocusManager#getCurrentKeyboardFocusManager
* @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
*/
public static final String FOCUS_MANAGER_CLASS_PROPERTY =
"FocusManagerClassName";
private static boolean enabled = true;
/** {@collect.stats}
* Returns the current <code>KeyboardFocusManager</code> instance
* for the calling thread's context.
*
* @return this thread's context's <code>KeyboardFocusManager</code>
* @see #setCurrentManager
*/
public static FocusManager getCurrentManager() {
KeyboardFocusManager manager =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
if (manager instanceof FocusManager) {
return (FocusManager)manager;
} else {
return new DelegatingDefaultFocusManager(manager);
}
}
/** {@collect.stats}
* Sets the current <code>KeyboardFocusManager</code> instance
* for the calling thread's context. If <code>null</code> is
* specified, then the current <code>KeyboardFocusManager</code>
* is replaced with a new instance of
* <code>DefaultKeyboardFocusManager</code>.
* <p>
* If a <code>SecurityManager</code> is installed,
* the calling thread must be granted the <code>AWTPermission</code>
* "replaceKeyboardFocusManager" in order to replace the
* the current <code>KeyboardFocusManager</code>.
* If this permission is not granted,
* this method will throw a <code>SecurityException</code>,
* and the current <code>KeyboardFocusManager</code> will be unchanged.
*
* @param aFocusManager the new <code>KeyboardFocusManager</code>
* for this thread's context
* @see #getCurrentManager
* @see java.awt.DefaultKeyboardFocusManager
* @throws SecurityException if the calling thread does not have permission
* to replace the current <code>KeyboardFocusManager</code>
*/
public static void setCurrentManager(FocusManager aFocusManager)
throws SecurityException
{
// Note: This method is not backward-compatible with 1.3 and earlier
// releases. It now throws a SecurityException in an applet, whereas
// in previous releases, it did not. This issue was discussed at
// length, and ultimately approved by Hans.
KeyboardFocusManager toSet =
(aFocusManager instanceof DelegatingDefaultFocusManager)
? ((DelegatingDefaultFocusManager)aFocusManager).getDelegate()
: aFocusManager;
KeyboardFocusManager.setCurrentKeyboardFocusManager(toSet);
}
/** {@collect.stats}
* Changes the current <code>KeyboardFocusManager</code>'s default
* <code>FocusTraversalPolicy</code> to
* <code>DefaultFocusTraversalPolicy</code>.
*
* @see java.awt.DefaultFocusTraversalPolicy
* @see java.awt.KeyboardFocusManager#setDefaultFocusTraversalPolicy
* @deprecated as of 1.4, replaced by
* <code>KeyboardFocusManager.setDefaultFocusTraversalPolicy(FocusTraversalPolicy)</code>
*/
@Deprecated
public static void disableSwingFocusManager() {
if (enabled) {
enabled = false;
KeyboardFocusManager.getCurrentKeyboardFocusManager().
setDefaultFocusTraversalPolicy(
new DefaultFocusTraversalPolicy());
}
}
/** {@collect.stats}
* Returns whether the application has invoked
* <code>disableSwingFocusManager()</code>.
*
* @see #disableSwingFocusManager
* @deprecated As of 1.4, replaced by
* <code>KeyboardFocusManager.getDefaultFocusTraversalPolicy()</code>
*/
@Deprecated
public static boolean isFocusManagerEnabled() {
return enabled;
}
}
|
Java
|
/*
* Copyright (c) 1998, 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 javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.awt.Component;
import java.awt.Color;
import java.awt.Rectangle;
import java.io.Serializable;
import sun.swing.DefaultLookup;
/** {@collect.stats}
* Renders an item in a list.
* <p>
* <strong><a name="override">Implementation Note:</a></strong>
* This class overrides
* <code>invalidate</code>,
* <code>validate</code>,
* <code>revalidate</code>,
* <code>repaint</code>,
* <code>isOpaque</code>,
* and
* <code>firePropertyChange</code>
* solely to improve performance.
* If not overridden, these frequently called methods would execute code paths
* that are unnecessary for the default list cell renderer.
* If you write your own renderer,
* take care to weigh the benefits and
* drawbacks of overriding these methods.
*
* <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 Philip Milne
* @author Hans Muller
*/
public class DefaultListCellRenderer extends JLabel
implements ListCellRenderer, Serializable
{
/** {@collect.stats}
* An empty <code>Border</code>. This field might not be used. To change the
* <code>Border</code> used by this renderer override the
* <code>getListCellRendererComponent</code> method and set the border
* of the returned component directly.
*/
private static final Border SAFE_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
private static final Border DEFAULT_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
protected static Border noFocusBorder = DEFAULT_NO_FOCUS_BORDER;
/** {@collect.stats}
* Constructs a default renderer object for an item
* in a list.
*/
public DefaultListCellRenderer() {
super();
setOpaque(true);
setBorder(getNoFocusBorder());
setName("List.cellRenderer");
}
private Border getNoFocusBorder() {
Border border = DefaultLookup.getBorder(this, ui, "List.cellNoFocusBorder");
if (System.getSecurityManager() != null) {
if (border != null) return border;
return SAFE_NO_FOCUS_BORDER;
} else {
if (border != null &&
(noFocusBorder == null ||
noFocusBorder == DEFAULT_NO_FOCUS_BORDER)) {
return border;
}
return noFocusBorder;
}
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
setComponentOrientation(list.getComponentOrientation());
Color bg = null;
Color fg = null;
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index) {
bg = DefaultLookup.getColor(this, ui, "List.dropCellBackground");
fg = DefaultLookup.getColor(this, ui, "List.dropCellForeground");
isSelected = true;
}
if (isSelected) {
setBackground(bg == null ? list.getSelectionBackground() : bg);
setForeground(fg == null ? list.getSelectionForeground() : fg);
}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
if (value instanceof Icon) {
setIcon((Icon)value);
setText("");
}
else {
setIcon(null);
setText((value == null) ? "" : value.toString());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
Border border = null;
if (cellHasFocus) {
if (isSelected) {
border = DefaultLookup.getBorder(this, ui, "List.focusSelectedCellHighlightBorder");
}
if (border == null) {
border = DefaultLookup.getBorder(this, ui, "List.focusCellHighlightBorder");
}
} else {
border = getNoFocusBorder();
}
setBorder(border);
return this;
}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*
* @since 1.5
* @return <code>true</code> if the background is completely opaque
* and differs from the JList's background;
* <code>false</code> otherwise
*/
@Override
public boolean isOpaque() {
Color back = getBackground();
Component p = getParent();
if (p != null) {
p = p.getParent();
}
// p should now be the JList.
boolean colorMatch = (back != null) && (p != null) &&
back.equals(p.getBackground()) &&
p.isOpaque();
return !colorMatch && super.isOpaque();
}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void validate() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*
* @since 1.5
*/
@Override
public void invalidate() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*
* @since 1.5
*/
@Override
public void repaint() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void revalidate() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void repaint(long tm, int x, int y, int width, int height) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void repaint(Rectangle r) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
// Strings get interned...
if (propertyName == "text"
|| ((propertyName == "font" || propertyName == "foreground")
&& oldValue != newValue
&& getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey) != null)) {
super.firePropertyChange(propertyName, oldValue, newValue);
}
}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void firePropertyChange(String propertyName, char oldValue, char newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void firePropertyChange(String propertyName, short oldValue, short newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void firePropertyChange(String propertyName, long oldValue, long newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void firePropertyChange(String propertyName, float oldValue, float newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void firePropertyChange(String propertyName, double oldValue, double newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
@Override
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
/** {@collect.stats}
* A subclass of DefaultListCellRenderer that implements UIResource.
* DefaultListCellRenderer doesn't implement UIResource
* directly so that applications can safely override the
* cellRenderer property with DefaultListCellRenderer subclasses.
* <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}.
*/
public static class UIResource extends DefaultListCellRenderer
implements javax.swing.plaf.UIResource
{
}
}
|
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 sun.swing.SwingUtilities2;
import sun.swing.UIAction;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.DropTarget;
import java.lang.reflect.*;
import javax.accessibility.*;
import javax.swing.event.MenuDragMouseEvent;
import javax.swing.plaf.UIResource;
import javax.swing.text.View;
import java.security.AccessController;
import sun.security.action.GetPropertyAction;
import sun.awt.AppContext;
/** {@collect.stats}
* A collection of utility methods for Swing.
*
* @author unknown
*/
public class SwingUtilities implements SwingConstants
{
// These states are system-wide, rather than AppContext wide.
private static boolean canAccessEventQueue = false;
private static boolean eventQueueTested = false;
/** {@collect.stats}
* Indicates if we should change the drop target when a
* {@code TransferHandler} is set.
*/
private static boolean suppressDropSupport;
/** {@collect.stats}
* Indiciates if we've checked the system property for suppressing
* drop support.
*/
private static boolean checkedSuppressDropSupport;
/** {@collect.stats}
* Returns true if <code>setTransferHandler</code> should change the
* <code>DropTarget</code>.
*/
private static boolean getSuppressDropTarget() {
if (!checkedSuppressDropSupport) {
suppressDropSupport = Boolean.valueOf(
AccessController.doPrivileged(
new GetPropertyAction("suppressSwingDropSupport")));
checkedSuppressDropSupport = true;
}
return suppressDropSupport;
}
/** {@collect.stats}
* Installs a {@code DropTarget} on the component as necessary for a
* {@code TransferHandler} change.
*/
static void installSwingDropTargetAsNecessary(Component c,
TransferHandler t) {
if (!getSuppressDropTarget()) {
DropTarget dropHandler = c.getDropTarget();
if ((dropHandler == null) || (dropHandler instanceof UIResource)) {
if (t == null) {
c.setDropTarget(null);
} else if (!GraphicsEnvironment.isHeadless()) {
c.setDropTarget(new TransferHandler.SwingDropTarget(c));
}
}
}
}
/** {@collect.stats}
* Return true if <code>a</code> contains <code>b</code>
*/
public static final boolean isRectangleContainingRectangle(Rectangle a,Rectangle b) {
if (b.x >= a.x && (b.x + b.width) <= (a.x + a.width) &&
b.y >= a.y && (b.y + b.height) <= (a.y + a.height)) {
return true;
}
return false;
}
/** {@collect.stats}
* Return the rectangle (0,0,bounds.width,bounds.height) for the component <code>aComponent</code>
*/
public static Rectangle getLocalBounds(Component aComponent) {
Rectangle b = new Rectangle(aComponent.getBounds());
b.x = b.y = 0;
return b;
}
/** {@collect.stats}
* Returns the first <code>Window </code> ancestor of <code>c</code>, or
* {@code null} if <code>c</code> is not contained inside a <code>Window</code>.
*
* @param c <code>Component</code> to get <code>Window</code> ancestor
* of.
* @return the first <code>Window </code> ancestor of <code>c</code>, or
* {@code null} if <code>c</code> is not contained inside a
* <code>Window</code>.
* @since 1.3
*/
public static Window getWindowAncestor(Component c) {
for(Container p = c.getParent(); p != null; p = p.getParent()) {
if (p instanceof Window) {
return (Window)p;
}
}
return null;
}
/** {@collect.stats}
* Converts the location <code>x</code> <code>y</code> to the
* parents coordinate system, returning the location.
*/
static Point convertScreenLocationToParent(Container parent,int x, int y) {
for (Container p = parent; p != null; p = p.getParent()) {
if (p instanceof Window) {
Point point = new Point(x, y);
SwingUtilities.convertPointFromScreen(point, parent);
return point;
}
}
throw new Error("convertScreenLocationToParent: no window ancestor");
}
/** {@collect.stats}
* Convert a <code>aPoint</code> in <code>source</code> coordinate system to
* <code>destination</code> coordinate system.
* If <code>source</code> is {@code null}, <code>aPoint</code> is assumed to be in <code>destination</code>'s
* root component coordinate system.
* If <code>destination</code> is {@code null}, <code>aPoint</code> will be converted to <code>source</code>'s
* root component coordinate system.
* If both <code>source</code> and <code>destination</code> are {@code null}, return <code>aPoint</code>
* without any conversion.
*/
public static Point convertPoint(Component source,Point aPoint,Component destination) {
Point p;
if(source == null && destination == null)
return aPoint;
if(source == null) {
source = getWindowAncestor(destination);
if(source == null)
throw new Error("Source component not connected to component tree hierarchy");
}
p = new Point(aPoint);
convertPointToScreen(p,source);
if(destination == null) {
destination = getWindowAncestor(source);
if(destination == null)
throw new Error("Destination component not connected to component tree hierarchy");
}
convertPointFromScreen(p,destination);
return p;
}
/** {@collect.stats}
* Convert the point <code>(x,y)</code> in <code>source</code> coordinate system to
* <code>destination</code> coordinate system.
* If <code>source</code> is {@code null}, <code>(x,y)</code> is assumed to be in <code>destination</code>'s
* root component coordinate system.
* If <code>destination</code> is {@code null}, <code>(x,y)</code> will be converted to <code>source</code>'s
* root component coordinate system.
* If both <code>source</code> and <code>destination</code> are {@code null}, return <code>(x,y)</code>
* without any conversion.
*/
public static Point convertPoint(Component source,int x, int y,Component destination) {
Point point = new Point(x,y);
return convertPoint(source,point,destination);
}
/** {@collect.stats}
* Convert the rectangle <code>aRectangle</code> in <code>source</code> coordinate system to
* <code>destination</code> coordinate system.
* If <code>source</code> is {@code null}, <code>aRectangle</code> is assumed to be in <code>destination</code>'s
* root component coordinate system.
* If <code>destination</code> is {@code null}, <code>aRectangle</code> will be converted to <code>source</code>'s
* root component coordinate system.
* If both <code>source</code> and <code>destination</code> are {@code null}, return <code>aRectangle</code>
* without any conversion.
*/
public static Rectangle convertRectangle(Component source,Rectangle aRectangle,Component destination) {
Point point = new Point(aRectangle.x,aRectangle.y);
point = convertPoint(source,point,destination);
return new Rectangle(point.x,point.y,aRectangle.width,aRectangle.height);
}
/** {@collect.stats}
* Convenience method for searching above <code>comp</code> in the
* component hierarchy and returns the first object of class <code>c</code> it
* finds. Can return {@code null}, if a class <code>c</code> cannot be found.
*/
public static Container getAncestorOfClass(Class<?> c, Component comp)
{
if(comp == null || c == null)
return null;
Container parent = comp.getParent();
while(parent != null && !(c.isInstance(parent)))
parent = parent.getParent();
return parent;
}
/** {@collect.stats}
* Convenience method for searching above <code>comp</code> in the
* component hierarchy and returns the first object of <code>name</code> it
* finds. Can return {@code null}, if <code>name</code> cannot be found.
*/
public static Container getAncestorNamed(String name, Component comp) {
if(comp == null || name == null)
return null;
Container parent = comp.getParent();
while(parent != null && !(name.equals(parent.getName())))
parent = parent.getParent();
return parent;
}
/** {@collect.stats}
* Returns the deepest visible descendent Component of <code>parent</code>
* that contains the location <code>x</code>, <code>y</code>.
* If <code>parent</code> does not contain the specified location,
* then <code>null</code> is returned. If <code>parent</code> is not a
* container, or none of <code>parent</code>'s visible descendents
* contain the specified location, <code>parent</code> is returned.
*
* @param parent the root component to begin the search
* @param x the x target location
* @param y the y target location
*/
public static Component getDeepestComponentAt(Component parent, int x, int y) {
if (!parent.contains(x, y)) {
return null;
}
if (parent instanceof Container) {
Component components[] = ((Container)parent).getComponents();
for (int i = 0 ; i < components.length ; i++) {
Component comp = components[i];
if (comp != null && comp.isVisible()) {
Point loc = comp.getLocation();
if (comp instanceof Container) {
comp = getDeepestComponentAt(comp, x - loc.x, y - loc.y);
} else {
comp = comp.getComponentAt(x - loc.x, y - loc.y);
}
if (comp != null && comp.isVisible()) {
return comp;
}
}
}
}
return parent;
}
/** {@collect.stats}
* Returns a MouseEvent similar to <code>sourceEvent</code> except that its x
* and y members have been converted to <code>destination</code>'s coordinate
* system. If <code>source</code> is {@code null}, <code>sourceEvent</code> x and y members
* are assumed to be into <code>destination</code>'s root component coordinate system.
* If <code>destination</code> is <code>null</code>, the
* returned MouseEvent will be in <code>source</code>'s coordinate system.
* <code>sourceEvent</code> will not be changed. A new event is returned.
* the <code>source</code> field of the returned event will be set
* to <code>destination</code> if destination is non-{@code null}
* use the translateMouseEvent() method to translate a mouse event from
* one component to another without changing the source.
*/
public static MouseEvent convertMouseEvent(Component source,
MouseEvent sourceEvent,
Component destination) {
Point p = convertPoint(source,new Point(sourceEvent.getX(),
sourceEvent.getY()),
destination);
Component newSource;
if(destination != null)
newSource = destination;
else
newSource = source;
MouseEvent newEvent;
if (sourceEvent instanceof MouseWheelEvent) {
MouseWheelEvent sourceWheelEvent = (MouseWheelEvent)sourceEvent;
newEvent = new MouseWheelEvent(newSource,
sourceWheelEvent.getID(),
sourceWheelEvent.getWhen(),
sourceWheelEvent.getModifiers(),
p.x,p.y,
sourceWheelEvent.getXOnScreen(),
sourceWheelEvent.getYOnScreen(),
sourceWheelEvent.getClickCount(),
sourceWheelEvent.isPopupTrigger(),
sourceWheelEvent.getScrollType(),
sourceWheelEvent.getScrollAmount(),
sourceWheelEvent.getWheelRotation());
}
else if (sourceEvent instanceof MenuDragMouseEvent) {
MenuDragMouseEvent sourceMenuDragEvent = (MenuDragMouseEvent)sourceEvent;
newEvent = new MenuDragMouseEvent(newSource,
sourceMenuDragEvent.getID(),
sourceMenuDragEvent.getWhen(),
sourceMenuDragEvent.getModifiers(),
p.x,p.y,
sourceMenuDragEvent.getXOnScreen(),
sourceMenuDragEvent.getYOnScreen(),
sourceMenuDragEvent.getClickCount(),
sourceMenuDragEvent.isPopupTrigger(),
sourceMenuDragEvent.getPath(),
sourceMenuDragEvent.getMenuSelectionManager());
}
else {
newEvent = new MouseEvent(newSource,
sourceEvent.getID(),
sourceEvent.getWhen(),
sourceEvent.getModifiers(),
p.x,p.y,
sourceEvent.getXOnScreen(),
sourceEvent.getYOnScreen(),
sourceEvent.getClickCount(),
sourceEvent.isPopupTrigger(),
MouseEvent.NOBUTTON );
}
return newEvent;
}
/** {@collect.stats}
* Convert a point from a component's coordinate system to
* screen coordinates.
*
* @param p a Point object (converted to the new coordinate system)
* @param c a Component object
*/
public static void convertPointToScreen(Point p,Component c) {
Rectangle b;
int x,y;
do {
if(c instanceof JComponent) {
x = ((JComponent)c).getX();
y = ((JComponent)c).getY();
} else if(c instanceof java.applet.Applet ||
c instanceof java.awt.Window) {
try {
Point pp = c.getLocationOnScreen();
x = pp.x;
y = pp.y;
} catch (IllegalComponentStateException icse) {
x = c.getX();
y = c.getY();
}
} else {
x = c.getX();
y = c.getY();
}
p.x += x;
p.y += y;
if(c instanceof java.awt.Window || c instanceof java.applet.Applet)
break;
c = c.getParent();
} while(c != null);
}
/** {@collect.stats}
* Convert a point from a screen coordinates to a component's
* coordinate system
*
* @param p a Point object (converted to the new coordinate system)
* @param c a Component object
*/
public static void convertPointFromScreen(Point p,Component c) {
Rectangle b;
int x,y;
do {
if(c instanceof JComponent) {
x = ((JComponent)c).getX();
y = ((JComponent)c).getY();
} else if(c instanceof java.applet.Applet ||
c instanceof java.awt.Window) {
try {
Point pp = c.getLocationOnScreen();
x = pp.x;
y = pp.y;
} catch (IllegalComponentStateException icse) {
x = c.getX();
y = c.getY();
}
} else {
x = c.getX();
y = c.getY();
}
p.x -= x;
p.y -= y;
if(c instanceof java.awt.Window || c instanceof java.applet.Applet)
break;
c = c.getParent();
} while(c != null);
}
/** {@collect.stats}
* Returns the first <code>Window </code> ancestor of <code>c</code>, or
* {@code null} if <code>c</code> is not contained inside a <code>Window</code>.
* <p>
* Note: This method provides the same functionality as
* <code>getWindowAncestor</code>.
*
* @param c <code>Component</code> to get <code>Window</code> ancestor
* of.
* @return the first <code>Window </code> ancestor of <code>c</code>, or
* {@code null} if <code>c</code> is not contained inside a
* <code>Window</code>.
*/
public static Window windowForComponent(Component c) {
return getWindowAncestor(c);
}
/** {@collect.stats}
* Return <code>true</code> if a component <code>a</code> descends from a component <code>b</code>
*/
public static boolean isDescendingFrom(Component a,Component b) {
if(a == b)
return true;
for(Container p = a.getParent();p!=null;p=p.getParent())
if(p == b)
return true;
return false;
}
/** {@collect.stats}
* Convenience to calculate the intersection of two rectangles
* without allocating a new rectangle.
* If the two rectangles don't intersect,
* then the returned rectangle begins at (0,0)
* and has zero width and height.
*
* @param x the X coordinate of the first rectangle's top-left point
* @param y the Y coordinate of the first rectangle's top-left point
* @param width the width of the first rectangle
* @param height the height of the first rectangle
* @param dest the second rectangle
*
* @return <code>dest</code>, modified to specify the intersection
*/
public static Rectangle computeIntersection(int x,int y,int width,int height,Rectangle dest) {
int x1 = (x > dest.x) ? x : dest.x;
int x2 = ((x+width) < (dest.x + dest.width)) ? (x+width) : (dest.x + dest.width);
int y1 = (y > dest.y) ? y : dest.y;
int y2 = ((y + height) < (dest.y + dest.height) ? (y+height) : (dest.y + dest.height));
dest.x = x1;
dest.y = y1;
dest.width = x2 - x1;
dest.height = y2 - y1;
// If rectangles don't intersect, return zero'd intersection.
if (dest.width < 0 || dest.height < 0) {
dest.x = dest.y = dest.width = dest.height = 0;
}
return dest;
}
/** {@collect.stats}
* Convenience method that calculates the union of two rectangles
* without allocating a new rectangle.
*
* @param x the x-coordinate of the first rectangle
* @param y the y-coordinate of the first rectangle
* @param width the width of the first rectangle
* @param height the height of the first rectangle
* @param dest the coordinates of the second rectangle; the union
* of the two rectangles is returned in this rectangle
* @return the <code>dest</code> <code>Rectangle</code>
*/
public static Rectangle computeUnion(int x,int y,int width,int height,Rectangle dest) {
int x1 = (x < dest.x) ? x : dest.x;
int x2 = ((x+width) > (dest.x + dest.width)) ? (x+width) : (dest.x + dest.width);
int y1 = (y < dest.y) ? y : dest.y;
int y2 = ((y+height) > (dest.y + dest.height)) ? (y+height) : (dest.y + dest.height);
dest.x = x1;
dest.y = y1;
dest.width = (x2 - x1);
dest.height= (y2 - y1);
return dest;
}
/** {@collect.stats}
* Convenience returning an array of rect representing the regions within
* <code>rectA</code> that do not overlap with <code>rectB</code>. If the
* two Rects do not overlap, returns an empty array
*/
public static Rectangle[] computeDifference(Rectangle rectA,Rectangle rectB) {
if (rectB == null || !rectA.intersects(rectB) || isRectangleContainingRectangle(rectB,rectA)) {
return new Rectangle[0];
}
Rectangle t = new Rectangle();
Rectangle a=null,b=null,c=null,d=null;
Rectangle result[];
int rectCount = 0;
/* rectA contains rectB */
if (isRectangleContainingRectangle(rectA,rectB)) {
t.x = rectA.x; t.y = rectA.y; t.width = rectB.x - rectA.x; t.height = rectA.height;
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.x = rectB.x; t.y = rectA.y; t.width = rectB.width; t.height = rectB.y - rectA.y;
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
t.x = rectB.x; t.y = rectB.y + rectB.height; t.width = rectB.width;
t.height = rectA.y + rectA.height - (rectB.y + rectB.height);
if(t.width > 0 && t.height > 0) {
c = new Rectangle(t);
rectCount++;
}
t.x = rectB.x + rectB.width; t.y = rectA.y; t.width = rectA.x + rectA.width - (rectB.x + rectB.width);
t.height = rectA.height;
if(t.width > 0 && t.height > 0) {
d = new Rectangle(t);
rectCount++;
}
} else {
/* 1 */
if (rectB.x <= rectA.x && rectB.y <= rectA.y) {
if ((rectB.x + rectB.width) > (rectA.x + rectA.width)) {
t.x = rectA.x; t.y = rectB.y + rectB.height;
t.width = rectA.width; t.height = rectA.y + rectA.height - (rectB.y + rectB.height);
if(t.width > 0 && t.height > 0) {
a = t;
rectCount++;
}
} else if ((rectB.y + rectB.height) > (rectA.y + rectA.height)) {
t.setBounds((rectB.x + rectB.width), rectA.y,
(rectA.x + rectA.width) - (rectB.x + rectB.width), rectA.height);
if(t.width > 0 && t.height > 0) {
a = t;
rectCount++;
}
} else {
t.setBounds((rectB.x + rectB.width), rectA.y,
(rectA.x + rectA.width) - (rectB.x + rectB.width),
(rectB.y + rectB.height) - rectA.y);
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
(rectA.y + rectA.height) - (rectB.y + rectB.height));
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
}
} else if (rectB.x <= rectA.x && (rectB.y + rectB.height) >= (rectA.y + rectA.height)) {
if ((rectB.x + rectB.width) > (rectA.x + rectA.width)) {
t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
if(t.width > 0 && t.height > 0) {
a = t;
rectCount++;
}
} else {
t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds((rectB.x + rectB.width), rectB.y,
(rectA.x + rectA.width) - (rectB.x + rectB.width),
(rectA.y + rectA.height) - rectB.y);
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
}
} else if (rectB.x <= rectA.x) {
if ((rectB.x + rectB.width) >= (rectA.x + rectA.width)) {
t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
if(t.width>0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
(rectA.y + rectA.height) - (rectB.y + rectB.height));
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
} else {
t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds((rectB.x + rectB.width), rectB.y,
(rectA.x + rectA.width) - (rectB.x + rectB.width),
rectB.height);
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
(rectA.y + rectA.height) - (rectB.y + rectB.height));
if(t.width > 0 && t.height > 0) {
c = new Rectangle(t);
rectCount++;
}
}
} else if (rectB.x <= (rectA.x + rectA.width) && (rectB.x + rectB.width) > (rectA.x + rectA.width)) {
if (rectB.y <= rectA.y && (rectB.y + rectB.height) > (rectA.y + rectA.height)) {
t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x, rectA.height);
if(t.width > 0 && t.height > 0) {
a = t;
rectCount++;
}
} else if (rectB.y <= rectA.y) {
t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x,
(rectB.y + rectB.height) - rectA.y);
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
(rectA.y + rectA.height) - (rectB.y + rectB.height));
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
} else if ((rectB.y + rectB.height) > (rectA.y + rectA.height)) {
t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds(rectA.x, rectB.y, rectB.x - rectA.x,
(rectA.y + rectA.height) - rectB.y);
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
} else {
t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds(rectA.x, rectB.y, rectB.x - rectA.x,
rectB.height);
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
(rectA.y + rectA.height) - (rectB.y + rectB.height));
if(t.width > 0 && t.height > 0) {
c = new Rectangle(t);
rectCount++;
}
}
} else if (rectB.x >= rectA.x && (rectB.x + rectB.width) <= (rectA.x + rectA.width)) {
if (rectB.y <= rectA.y && (rectB.y + rectB.height) > (rectA.y + rectA.height)) {
t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x, rectA.height);
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds((rectB.x + rectB.width), rectA.y,
(rectA.x + rectA.width) - (rectB.x + rectB.width), rectA.height);
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
} else if (rectB.y <= rectA.y) {
t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x, rectA.height);
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds(rectB.x, (rectB.y + rectB.height),
rectB.width,
(rectA.y + rectA.height) - (rectB.y + rectB.height));
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
t.setBounds((rectB.x + rectB.width), rectA.y,
(rectA.x + rectA.width) - (rectB.x + rectB.width), rectA.height);
if(t.width > 0 && t.height > 0) {
c = new Rectangle(t);
rectCount++;
}
} else {
t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x, rectA.height);
if(t.width > 0 && t.height > 0) {
a = new Rectangle(t);
rectCount++;
}
t.setBounds(rectB.x, rectA.y, rectB.width,
rectB.y - rectA.y);
if(t.width > 0 && t.height > 0) {
b = new Rectangle(t);
rectCount++;
}
t.setBounds((rectB.x + rectB.width), rectA.y,
(rectA.x + rectA.width) - (rectB.x + rectB.width), rectA.height);
if(t.width > 0 && t.height > 0) {
c = new Rectangle(t);
rectCount++;
}
}
}
}
result = new Rectangle[rectCount];
rectCount = 0;
if(a != null)
result[rectCount++] = a;
if(b != null)
result[rectCount++] = b;
if(c != null)
result[rectCount++] = c;
if(d != null)
result[rectCount++] = d;
return result;
}
/** {@collect.stats}
* Returns true if the mouse event specifies the left mouse button.
*
* @param anEvent a MouseEvent object
* @return true if the left mouse button was active
*/
public static boolean isLeftMouseButton(MouseEvent anEvent) {
return ((anEvent.getModifiers() & InputEvent.BUTTON1_MASK) != 0);
}
/** {@collect.stats}
* Returns true if the mouse event specifies the middle mouse button.
*
* @param anEvent a MouseEvent object
* @return true if the middle mouse button was active
*/
public static boolean isMiddleMouseButton(MouseEvent anEvent) {
return ((anEvent.getModifiers() & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK);
}
/** {@collect.stats}
* Returns true if the mouse event specifies the right mouse button.
*
* @param anEvent a MouseEvent object
* @return true if the right mouse button was active
*/
public static boolean isRightMouseButton(MouseEvent anEvent) {
return ((anEvent.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK);
}
/** {@collect.stats}
* Compute the width of the string using a font with the specified
* "metrics" (sizes).
*
* @param fm a FontMetrics object to compute with
* @param str the String to compute
* @return an int containing the string width
*/
public static int computeStringWidth(FontMetrics fm,String str) {
// You can't assume that a string's width is the sum of its
// characters' widths in Java2D -- it may be smaller due to
// kerning, etc.
return SwingUtilities2.stringWidth(null, fm, str);
}
/** {@collect.stats}
* Compute and return the location of the icons origin, the
* location of origin of the text baseline, and a possibly clipped
* version of the compound labels string. Locations are computed
* relative to the viewR rectangle.
* The JComponents orientation (LEADING/TRAILING) will also be taken
* into account and translated into LEFT/RIGHT values accordingly.
*/
public static String layoutCompoundLabel(JComponent c,
FontMetrics fm,
String text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap)
{
boolean orientationIsLeftToRight = true;
int hAlign = horizontalAlignment;
int hTextPos = horizontalTextPosition;
if (c != null) {
if (!(c.getComponentOrientation().isLeftToRight())) {
orientationIsLeftToRight = false;
}
}
// Translate LEADING/TRAILING values in horizontalAlignment
// to LEFT/RIGHT values depending on the components orientation
switch (horizontalAlignment) {
case LEADING:
hAlign = (orientationIsLeftToRight) ? LEFT : RIGHT;
break;
case TRAILING:
hAlign = (orientationIsLeftToRight) ? RIGHT : LEFT;
break;
}
// Translate LEADING/TRAILING values in horizontalTextPosition
// to LEFT/RIGHT values depending on the components orientation
switch (horizontalTextPosition) {
case LEADING:
hTextPos = (orientationIsLeftToRight) ? LEFT : RIGHT;
break;
case TRAILING:
hTextPos = (orientationIsLeftToRight) ? RIGHT : LEFT;
break;
}
return layoutCompoundLabelImpl(c,
fm,
text,
icon,
verticalAlignment,
hAlign,
verticalTextPosition,
hTextPos,
viewR,
iconR,
textR,
textIconGap);
}
/** {@collect.stats}
* Compute and return the location of the icons origin, the
* location of origin of the text baseline, and a possibly clipped
* version of the compound labels string. Locations are computed
* relative to the viewR rectangle.
* This layoutCompoundLabel() does not know how to handle LEADING/TRAILING
* values in horizontalTextPosition (they will default to RIGHT) and in
* horizontalAlignment (they will default to CENTER).
* Use the other version of layoutCompoundLabel() instead.
*/
public static String layoutCompoundLabel(
FontMetrics fm,
String text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap)
{
return layoutCompoundLabelImpl(null, fm, text, icon,
verticalAlignment,
horizontalAlignment,
verticalTextPosition,
horizontalTextPosition,
viewR, iconR, textR, textIconGap);
}
/** {@collect.stats}
* Compute and return the location of the icons origin, the
* location of origin of the text baseline, and a possibly clipped
* version of the compound labels string. Locations are computed
* relative to the viewR rectangle.
* This layoutCompoundLabel() does not know how to handle LEADING/TRAILING
* values in horizontalTextPosition (they will default to RIGHT) and in
* horizontalAlignment (they will default to CENTER).
* Use the other version of layoutCompoundLabel() instead.
*/
private static String layoutCompoundLabelImpl(
JComponent c,
FontMetrics fm,
String text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap)
{
/* Initialize the icon bounds rectangle iconR.
*/
if (icon != null) {
iconR.width = icon.getIconWidth();
iconR.height = icon.getIconHeight();
}
else {
iconR.width = iconR.height = 0;
}
/* Initialize the text bounds rectangle textR. If a null
* or and empty String was specified we substitute "" here
* and use 0,0,0,0 for textR.
*/
boolean textIsEmpty = (text == null) || text.equals("");
int lsb = 0;
int rsb = 0;
/* Unless both text and icon are non-null, we effectively ignore
* the value of textIconGap.
*/
int gap;
View v = null;
if (textIsEmpty) {
textR.width = textR.height = 0;
text = "";
gap = 0;
}
else {
int availTextWidth;
gap = (icon == null) ? 0 : textIconGap;
if (horizontalTextPosition == CENTER) {
availTextWidth = viewR.width;
}
else {
availTextWidth = viewR.width - (iconR.width + gap);
}
v = (c != null) ? (View) c.getClientProperty("html") : null;
if (v != null) {
textR.width = Math.min(availTextWidth,
(int) v.getPreferredSpan(View.X_AXIS));
textR.height = (int) v.getPreferredSpan(View.Y_AXIS);
} else {
textR.width = SwingUtilities2.stringWidth(c, fm, text);
// Take into account the left and right side bearings.
// This gives more space than it is actually needed,
// but there are two reasons:
// 1. If we set the width to the actual bounds,
// all callers would have to account for the bearings
// themselves. NOTE: all pref size calculations don't do it.
// 2. You can do a drawString at the returned location
// and the text won't be clipped.
lsb = SwingUtilities2.getLeftSideBearing(c, fm, text);
if (lsb < 0) {
textR.width -= lsb;
}
rsb = SwingUtilities2.getRightSideBearing(c, fm, text);
if (rsb > 0) {
textR.width += rsb;
}
if (textR.width > availTextWidth) {
text = SwingUtilities2.clipString(c, fm, text,
availTextWidth);
textR.width = SwingUtilities2.stringWidth(c, fm, text);
}
textR.height = fm.getHeight();
}
}
/* Compute textR.x,y given the verticalTextPosition and
* horizontalTextPosition properties
*/
if (verticalTextPosition == TOP) {
if (horizontalTextPosition != CENTER) {
textR.y = 0;
}
else {
textR.y = -(textR.height + gap);
}
}
else if (verticalTextPosition == CENTER) {
textR.y = (iconR.height / 2) - (textR.height / 2);
}
else { // (verticalTextPosition == BOTTOM)
if (horizontalTextPosition != CENTER) {
textR.y = iconR.height - textR.height;
}
else {
textR.y = (iconR.height + gap);
}
}
if (horizontalTextPosition == LEFT) {
textR.x = -(textR.width + gap);
}
else if (horizontalTextPosition == CENTER) {
textR.x = (iconR.width / 2) - (textR.width / 2);
}
else { // (horizontalTextPosition == RIGHT)
textR.x = (iconR.width + gap);
}
// WARNING: DefaultTreeCellEditor uses a shortened version of
// this algorithm to position it's Icon. If you change how this
// is calculated, be sure and update DefaultTreeCellEditor too.
/* labelR is the rectangle that contains iconR and textR.
* Move it to its proper position given the labelAlignment
* properties.
*
* To avoid actually allocating a Rectangle, Rectangle.union
* has been inlined below.
*/
int labelR_x = Math.min(iconR.x, textR.x);
int labelR_width = Math.max(iconR.x + iconR.width,
textR.x + textR.width) - labelR_x;
int labelR_y = Math.min(iconR.y, textR.y);
int labelR_height = Math.max(iconR.y + iconR.height,
textR.y + textR.height) - labelR_y;
int dx, dy;
if (verticalAlignment == TOP) {
dy = viewR.y - labelR_y;
}
else if (verticalAlignment == CENTER) {
dy = (viewR.y + (viewR.height / 2)) - (labelR_y + (labelR_height / 2));
}
else { // (verticalAlignment == BOTTOM)
dy = (viewR.y + viewR.height) - (labelR_y + labelR_height);
}
if (horizontalAlignment == LEFT) {
dx = viewR.x - labelR_x;
}
else if (horizontalAlignment == RIGHT) {
dx = (viewR.x + viewR.width) - (labelR_x + labelR_width);
}
else { // (horizontalAlignment == CENTER)
dx = (viewR.x + (viewR.width / 2)) -
(labelR_x + (labelR_width / 2));
}
/* Translate textR and glypyR by dx,dy.
*/
textR.x += dx;
textR.y += dy;
iconR.x += dx;
iconR.y += dy;
if (lsb < 0) {
// lsb is negative. Shift the x location so that the text is
// visually drawn at the right location.
textR.x -= lsb;
textR.width += lsb;
}
if (rsb > 0) {
textR.width -= rsb;
}
return text;
}
/** {@collect.stats}
* Paints a component to the specified <code>Graphics</code>.
* This method is primarily useful to render
* <code>Component</code>s that don't exist as part of the visible
* containment hierarchy, but are used for rendering. For
* example, if you are doing your own rendering and want to render
* some text (or even HTML), you could make use of
* <code>JLabel</code>'s text rendering support and have it paint
* directly by way of this method, without adding the label to the
* visible containment hierarchy.
* <p>
* This method makes use of <code>CellRendererPane</code> to handle
* the actual painting, and is only recommended if you use one
* component for rendering. If you make use of multiple components
* to handle the rendering, as <code>JTable</code> does, use
* <code>CellRendererPane</code> directly. Otherwise, as described
* below, you could end up with a <code>CellRendererPane</code>
* per <code>Component</code>.
* <p>
* If <code>c</code>'s parent is not a <code>CellRendererPane</code>,
* a new <code>CellRendererPane</code> is created, <code>c</code> is
* added to it, and the <code>CellRendererPane</code> is added to
* <code>p</code>. If <code>c</code>'s parent is a
* <code>CellRendererPane</code> and the <code>CellRendererPane</code>s
* parent is not <code>p</code>, it is added to <code>p</code>.
* <p>
* The component should either descend from <code>JComponent</code>
* or be another kind of lightweight component.
* A lightweight component is one whose "lightweight" property
* (returned by the <code>Component</code>
* <code>isLightweight</code> method)
* is true. If the Component is not lightweight, bad things map happen:
* crashes, exceptions, painting problems...
*
* @param g the <code>Graphics</code> object to draw on
* @param c the <code>Component</code> to draw
* @param p the intermediate <code>Container</code>
* @param x an int specifying the left side of the area draw in, in pixels,
* measured from the left edge of the graphics context
* @param y an int specifying the top of the area to draw in, in pixels
* measured down from the top edge of the graphics context
* @param w an int specifying the width of the area draw in, in pixels
* @param h an int specifying the height of the area draw in, in pixels
*
* @see CellRendererPane
* @see java.awt.Component#isLightweight
*/
public static void paintComponent(Graphics g, Component c, Container p, int x, int y, int w, int h) {
getCellRendererPane(c, p).paintComponent(g, c, p, x, y, w, h,false);
}
/** {@collect.stats}
* Paints a component to the specified <code>Graphics</code>. This
* is a cover method for
* {@link #paintComponent(Graphics,Component,Container,int,int,int,int)}.
* Refer to it for more information.
*
* @param g the <code>Graphics</code> object to draw on
* @param c the <code>Component</code> to draw
* @param p the intermediate <code>Container</code>
* @param r the <code>Rectangle</code> to draw in
*
* @see #paintComponent(Graphics,Component,Container,int,int,int,int)
* @see CellRendererPane
*/
public static void paintComponent(Graphics g, Component c, Container p, Rectangle r) {
paintComponent(g, c, p, r.x, r.y, r.width, r.height);
}
/*
* Ensures that cell renderer <code>c</code> has a
* <code>ComponentShell</code> parent and that
* the shell's parent is p.
*/
private static CellRendererPane getCellRendererPane(Component c, Container p) {
Container shell = c.getParent();
if (shell instanceof CellRendererPane) {
if (shell.getParent() != p) {
p.add(shell);
}
} else {
shell = new CellRendererPane();
shell.add(c);
p.add(shell);
}
return (CellRendererPane)shell;
}
/** {@collect.stats}
* A simple minded look and feel change: ask each node in the tree
* to <code>updateUI()</code> -- that is, to initialize its UI property
* with the current look and feel.
*/
public static void updateComponentTreeUI(Component c) {
updateComponentTreeUI0(c);
c.invalidate();
c.validate();
c.repaint();
}
private static void updateComponentTreeUI0(Component c) {
if (c instanceof JComponent) {
JComponent jc = (JComponent) c;
jc.updateUI();
JPopupMenu jpm =jc.getComponentPopupMenu();
if(jpm != null) {
updateComponentTreeUI(jpm);
}
}
Component[] children = null;
if (c instanceof JMenu) {
children = ((JMenu)c).getMenuComponents();
}
else if (c instanceof Container) {
children = ((Container)c).getComponents();
}
if (children != null) {
for(int i = 0; i < children.length; i++) {
updateComponentTreeUI0(children[i]);
}
}
}
/** {@collect.stats}
* Causes <i>doRun.run()</i> to be executed asynchronously on the
* AWT event dispatching thread. This will happen after all
* pending AWT events have been processed. This method should
* be used when an application thread needs to update the GUI.
* In the following example the <code>invokeLater</code> call queues
* the <code>Runnable</code> object <code>doHelloWorld</code>
* on the event dispatching thread and
* then prints a message.
* <pre>
* Runnable doHelloWorld = new Runnable() {
* public void run() {
* System.out.println("Hello World on " + Thread.currentThread());
* }
* };
*
* SwingUtilities.invokeLater(doHelloWorld);
* System.out.println("This might well be displayed before the other message.");
* </pre>
* If invokeLater is called from the event dispatching thread --
* for example, from a JButton's ActionListener -- the <i>doRun.run()</i> will
* still be deferred until all pending events have been processed.
* Note that if the <i>doRun.run()</i> throws an uncaught exception
* the event dispatching thread will unwind (not the current thread).
* <p>
* Additional documentation and examples for this method can be
* found in
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How to Use Threads</a>,
* in <em>The Java Tutorial</em>.
* <p>
* As of 1.3 this method is just a cover for <code>java.awt.EventQueue.invokeLater()</code>.
* <p>
* Unlike the rest of Swing, this method can be invoked from any thread.
*
* @see #invokeAndWait
*/
public static void invokeLater(Runnable doRun) {
EventQueue.invokeLater(doRun);
}
/** {@collect.stats}
* Causes <code>doRun.run()</code> to be executed synchronously on the
* AWT event dispatching thread. This call blocks until
* all pending AWT events have been processed and (then)
* <code>doRun.run()</code> returns. This method should
* be used when an application thread needs to update the GUI.
* It shouldn't be called from the event dispatching thread.
* Here's an example that creates a new application thread
* that uses <code>invokeAndWait</code> to print a string from the event
* dispatching thread and then, when that's finished, print
* a string from the application thread.
* <pre>
* final Runnable doHelloWorld = new Runnable() {
* public void run() {
* System.out.println("Hello World on " + Thread.currentThread());
* }
* };
*
* Thread appThread = new Thread() {
* public void run() {
* try {
* SwingUtilities.invokeAndWait(doHelloWorld);
* }
* catch (Exception e) {
* e.printStackTrace();
* }
* System.out.println("Finished on " + Thread.currentThread());
* }
* };
* appThread.start();
* </pre>
* Note that if the <code>Runnable.run</code> method throws an
* uncaught exception
* (on the event dispatching thread) it's caught and rethrown, as
* an <code>InvocationTargetException</code>, on the caller's thread.
* <p>
* Additional documentation and examples for this method can be
* found in
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How to Use Threads</a>,
* in <em>The Java Tutorial</em>.
* <p>
* As of 1.3 this method is just a cover for
* <code>java.awt.EventQueue.invokeAndWait()</code>.
*
* @exception InterruptedException if we're interrupted while waiting for
* the event dispatching thread to finish excecuting
* <code>doRun.run()</code>
* @exception InvocationTargetException if an exception is thrown
* while running <code>doRun</code>
*
* @see #invokeLater
*/
public static void invokeAndWait(final Runnable doRun)
throws InterruptedException, InvocationTargetException
{
EventQueue.invokeAndWait(doRun);
}
/** {@collect.stats}
* Returns true if the current thread is an AWT event dispatching thread.
* <p>
* As of 1.3 this method is just a cover for
* <code>java.awt.EventQueue.isDispatchThread()</code>.
*
* @return true if the current thread is an AWT event dispatching thread
*/
public static boolean isEventDispatchThread()
{
return EventQueue.isDispatchThread();
}
/*
* --- Accessibility Support ---
*
*/
/** {@collect.stats}
* Get the index of this object in its accessible parent.<p>
*
* Note: as of the Java 2 platform v1.3, it is recommended that developers call
* Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead
* of using this method.
*
* @return -1 of this object does not have an accessible parent.
* Otherwise, the index of the child in its accessible parent.
*/
public static int getAccessibleIndexInParent(Component c) {
return c.getAccessibleContext().getAccessibleIndexInParent();
}
/** {@collect.stats}
* Returns the <code>Accessible</code> child contained at the
* local coordinate <code>Point</code>, if one exists.
* Otherwise returns <code>null</code>.
*
* @return the <code>Accessible</code> at the specified location,
* if it exists; otherwise <code>null</code>
*/
public static Accessible getAccessibleAt(Component c, Point p) {
if (c instanceof Container) {
return c.getAccessibleContext().getAccessibleComponent().getAccessibleAt(p);
} else if (c instanceof Accessible) {
Accessible a = (Accessible) c;
if (a != null) {
AccessibleContext ac = a.getAccessibleContext();
if (ac != null) {
AccessibleComponent acmp;
Point location;
int nchildren = ac.getAccessibleChildrenCount();
for (int i=0; i < nchildren; i++) {
a = ac.getAccessibleChild(i);
if ((a != null)) {
ac = a.getAccessibleContext();
if (ac != null) {
acmp = ac.getAccessibleComponent();
if ((acmp != null) && (acmp.isShowing())) {
location = acmp.getLocation();
Point np = new Point(p.x-location.x,
p.y-location.y);
if (acmp.contains(np)){
return a;
}
}
}
}
}
}
}
return (Accessible) c;
}
return null;
}
/** {@collect.stats}
* Get the state of this object. <p>
*
* Note: as of the Java 2 platform v1.3, it is recommended that developers call
* Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead
* of using this method.
*
* @return an instance of AccessibleStateSet containing the current state
* set of the object
* @see AccessibleState
*/
public static AccessibleStateSet getAccessibleStateSet(Component c) {
return c.getAccessibleContext().getAccessibleStateSet();
}
/** {@collect.stats}
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object. <p>
*
* Note: as of the Java 2 platform v1.3, it is recommended that developers call
* Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead
* of using this method.
*
* @return the number of accessible children in the object.
*/
public static int getAccessibleChildrenCount(Component c) {
return c.getAccessibleContext().getAccessibleChildrenCount();
}
/** {@collect.stats}
* Return the nth Accessible child of the object. <p>
*
* Note: as of the Java 2 platform v1.3, it is recommended that developers call
* Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead
* of using this method.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public static Accessible getAccessibleChild(Component c, int i) {
return c.getAccessibleContext().getAccessibleChild(i);
}
/** {@collect.stats}
* Return the child <code>Component</code> of the specified
* <code>Component</code> that is the focus owner, if any.
*
* @param c the root of the <code>Component</code> hierarchy to
* search for the focus owner
* @return the focus owner, or <code>null</code> if there is no focus
* owner, or if the focus owner is not <code>comp</code>, or a
* descendant of <code>comp</code>
*
* @see java.awt.KeyboardFocusManager#getFocusOwner
* @deprecated As of 1.4, replaced by
* <code>KeyboardFocusManager.getFocusOwner()</code>.
*/
@Deprecated
public static Component findFocusOwner(Component c) {
Component focusOwner = KeyboardFocusManager.
getCurrentKeyboardFocusManager().getFocusOwner();
// verify focusOwner is a descendant of c
for (Component temp = focusOwner; temp != null;
temp = (temp instanceof Window) ? null : temp.getParent())
{
if (temp == c) {
return focusOwner;
}
}
return null;
}
/** {@collect.stats}
* If c is a JRootPane descendant return its JRootPane ancestor.
* If c is a RootPaneContainer then return its JRootPane.
* @return the JRootPane for Component c or {@code null}.
*/
public static JRootPane getRootPane(Component c) {
if (c instanceof RootPaneContainer) {
return ((RootPaneContainer)c).getRootPane();
}
for( ; c != null; c = c.getParent()) {
if (c instanceof JRootPane) {
return (JRootPane)c;
}
}
return null;
}
/** {@collect.stats}
* Returns the root component for the current component tree.
* @return the first ancestor of c that's a Window or the last Applet ancestor
*/
public static Component getRoot(Component c) {
Component applet = null;
for(Component p = c; p != null; p = p.getParent()) {
if (p instanceof Window) {
return p;
}
if (p instanceof Applet) {
applet = p;
}
}
return applet;
}
/** {@collect.stats}
* Process the key bindings for the <code>Component</code> associated with
* <code>event</code>. This method is only useful if
* <code>event.getComponent()</code> does not descend from
* <code>JComponent</code>, or your are not invoking
* <code>super.processKeyEvent</code> from within your
* <code>JComponent</code> subclass. <code>JComponent</code>
* automatically processes bindings from within its
* <code>processKeyEvent</code> method, hence you rarely need
* to directly invoke this method.
*
* @param event KeyEvent used to identify which bindings to process, as
* well as which Component has focus.
* @return true if a binding has found and processed
* @since 1.4
*/
public static boolean processKeyBindings(KeyEvent event) {
if (event != null) {
if (event.isConsumed()) {
return false;
}
Component component = event.getComponent();
boolean pressed = (event.getID() == KeyEvent.KEY_PRESSED);
if (!isValidKeyEventForKeyBindings(event)) {
return false;
}
// Find the first JComponent in the ancestor hierarchy, and
// invoke processKeyBindings on it
while (component != null) {
if (component instanceof JComponent) {
return ((JComponent)component).processKeyBindings(
event, pressed);
}
if ((component instanceof Applet) ||
(component instanceof Window)) {
// No JComponents, if Window or Applet parent, process
// WHEN_IN_FOCUSED_WINDOW bindings.
return JComponent.processKeyBindingsForAllComponents(
event, (Container)component, pressed);
}
component = component.getParent();
}
}
return false;
}
/** {@collect.stats}
* Returns true if the <code>e</code> is a valid KeyEvent to use in
* processing the key bindings associated with JComponents.
*/
static boolean isValidKeyEventForKeyBindings(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_TYPED) {
int mod = e.getModifiers();
if (((mod & ActionEvent.ALT_MASK) != 0) &&
((mod & ActionEvent.CTRL_MASK) == 0)) {
// filter out typed "alt-?" keys, but not those created
// with AltGr, and not control characters
return false;
}
}
return true;
}
/** {@collect.stats}
* Invokes <code>actionPerformed</code> on <code>action</code> if
* <code>action</code> is enabled (and non-{@code null}). The command for the
* ActionEvent is determined by:
* <ol>
* <li>If the action was registered via
* <code>registerKeyboardAction</code>, then the command string
* passed in ({@code null} will be used if {@code null} was passed in).
* <li>Action value with name Action.ACTION_COMMAND_KEY, unless {@code null}.
* <li>String value of the KeyEvent, unless <code>getKeyChar</code>
* returns KeyEvent.CHAR_UNDEFINED..
* </ol>
* This will return true if <code>action</code> is non-{@code null} and
* actionPerformed is invoked on it.
*
* @since 1.3
*/
public static boolean notifyAction(Action action, KeyStroke ks,
KeyEvent event, Object sender,
int modifiers) {
if (action == null) {
return false;
}
if (action instanceof UIAction) {
if (!((UIAction)action).isEnabled(sender)) {
return false;
}
}
else if (!action.isEnabled()) {
return false;
}
Object commandO;
boolean stayNull;
// Get the command object.
commandO = action.getValue(Action.ACTION_COMMAND_KEY);
if (commandO == null && (action instanceof JComponent.ActionStandin)) {
// ActionStandin is used for historical reasons to support
// registerKeyboardAction with a null value.
stayNull = true;
}
else {
stayNull = false;
}
// Convert it to a string.
String command;
if (commandO != null) {
command = commandO.toString();
}
else if (!stayNull && event.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
command = String.valueOf(event.getKeyChar());
}
else {
// Do null for undefined chars, or if registerKeyboardAction
// was called with a null.
command = null;
}
action.actionPerformed(new ActionEvent(sender,
ActionEvent.ACTION_PERFORMED, command, event.getWhen(),
modifiers));
return true;
}
/** {@collect.stats}
* Convenience method to change the UI InputMap for <code>component</code>
* to <code>uiInputMap</code>. If <code>uiInputMap</code> is {@code null},
* this removes any previously installed UI InputMap.
*
* @since 1.3
*/
public static void replaceUIInputMap(JComponent component, int type,
InputMap uiInputMap) {
InputMap map = component.getInputMap(type, (uiInputMap != null));
while (map != null) {
InputMap parent = map.getParent();
if (parent == null || (parent instanceof UIResource)) {
map.setParent(uiInputMap);
return;
}
map = parent;
}
}
/** {@collect.stats}
* Convenience method to change the UI ActionMap for <code>component</code>
* to <code>uiActionMap</code>. If <code>uiActionMap</code> is {@code null},
* this removes any previously installed UI ActionMap.
*
* @since 1.3
*/
public static void replaceUIActionMap(JComponent component,
ActionMap uiActionMap) {
ActionMap map = component.getActionMap((uiActionMap != null));;
while (map != null) {
ActionMap parent = map.getParent();
if (parent == null || (parent instanceof UIResource)) {
map.setParent(uiActionMap);
return;
}
map = parent;
}
}
/** {@collect.stats}
* Returns the InputMap provided by the UI for condition
* <code>condition</code> in component <code>component</code>.
* <p>This will return {@code null} if the UI has not installed a InputMap
* of the specified type.
*
* @since 1.3
*/
public static InputMap getUIInputMap(JComponent component, int condition) {
InputMap map = component.getInputMap(condition, false);
while (map != null) {
InputMap parent = map.getParent();
if (parent instanceof UIResource) {
return parent;
}
map = parent;
}
return null;
}
/** {@collect.stats}
* Returns the ActionMap provided by the UI
* in component <code>component</code>.
* <p>This will return {@code null} if the UI has not installed an ActionMap.
*
* @since 1.3
*/
public static ActionMap getUIActionMap(JComponent component) {
ActionMap map = component.getActionMap(false);
while (map != null) {
ActionMap parent = map.getParent();
if (parent instanceof UIResource) {
return parent;
}
map = parent;
}
return null;
}
// Don't use String, as it's not guaranteed to be unique in a Hashtable.
private static final Object sharedOwnerFrameKey = new Object(); // SwingUtilities.sharedOwnerFrame
static class SharedOwnerFrame extends Frame implements WindowListener {
public void addNotify() {
super.addNotify();
installListeners();
}
/** {@collect.stats}
* Install window listeners on owned windows to watch for displayability changes
*/
void installListeners() {
Window[] windows = getOwnedWindows();
for (int ind = 0; ind < windows.length; ind++){
Window window = windows[ind];
if (window != null) {
window.removeWindowListener(this);
window.addWindowListener(this);
}
}
}
/** {@collect.stats}
* Watches for displayability changes and disposes shared instance if there are no
* displayable children left.
*/
public void windowClosed(WindowEvent e) {
synchronized(getTreeLock()) {
Window[] windows = getOwnedWindows();
for (int ind = 0; ind < windows.length; ind++) {
Window window = windows[ind];
if (window != null) {
if (window.isDisplayable()) {
return;
}
window.removeWindowListener(this);
}
}
dispose();
}
}
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void show() {
// This frame can never be shown
}
public void dispose() {
try {
getToolkit().getSystemEventQueue();
super.dispose();
} catch (Exception e) {
// untrusted code not allowed to dispose
}
}
}
/** {@collect.stats}
* Returns a toolkit-private, shared, invisible Frame
* to be the owner for JDialogs and JWindows created with
* {@code null} owners.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
static Frame getSharedOwnerFrame() throws HeadlessException {
Frame sharedOwnerFrame =
(Frame)SwingUtilities.appContextGet(sharedOwnerFrameKey);
if (sharedOwnerFrame == null) {
sharedOwnerFrame = new SharedOwnerFrame();
SwingUtilities.appContextPut(sharedOwnerFrameKey,
sharedOwnerFrame);
}
return sharedOwnerFrame;
}
/** {@collect.stats}
* Returns a SharedOwnerFrame's shutdown listener to dispose the SharedOwnerFrame
* if it has no more displayable children.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
static WindowListener getSharedOwnerFrameShutdownListener() throws HeadlessException {
Frame sharedOwnerFrame = getSharedOwnerFrame();
return (WindowListener)sharedOwnerFrame;
}
/* Don't make these AppContext accessors public or protected --
* since AppContext is in sun.awt in 1.2, we shouldn't expose it
* even indirectly with a public API.
*/
// REMIND(aim): phase out use of 4 methods below since they
// are just private covers for AWT methods (?)
static Object appContextGet(Object key) {
return AppContext.getAppContext().get(key);
}
static void appContextPut(Object key, Object value) {
AppContext.getAppContext().put(key, value);
}
static void appContextRemove(Object key) {
AppContext.getAppContext().remove(key);
}
static Class loadSystemClass(String className) throws ClassNotFoundException {
return Class.forName(className, true, Thread.currentThread().
getContextClassLoader());
}
/*
* Convenience function for determining ComponentOrientation. Helps us
* avoid having Munge directives throughout the code.
*/
static boolean isLeftToRight( Component c ) {
return c.getComponentOrientation().isLeftToRight();
}
private SwingUtilities() {
throw new Error("SwingUtilities is just a container for static methods");
}
/** {@collect.stats}
* Returns true if the Icon <code>icon</code> is an instance of
* ImageIcon, and the image it contains is the same as <code>image</code>.
*/
static boolean doesIconReferenceImage(Icon icon, Image image) {
Image iconImage = (icon != null && (icon instanceof ImageIcon)) ?
((ImageIcon)icon).getImage() : null;
return (iconImage == image);
}
/** {@collect.stats}
* Returns index of the first occurrence of <code>mnemonic</code>
* within string <code>text</code>. Matching algorithm is not
* case-sensitive.
*
* @param text The text to search through, may be {@code null}
* @param mnemonic The mnemonic to find the character for.
* @return index into the string if exists, otherwise -1
*/
static int findDisplayedMnemonicIndex(String text, int mnemonic) {
if (text == null || mnemonic == '\0') {
return -1;
}
char uc = Character.toUpperCase((char)mnemonic);
char lc = Character.toLowerCase((char)mnemonic);
int uci = text.indexOf(uc);
int lci = text.indexOf(lc);
if (uci == -1) {
return lci;
} else if(lci == -1) {
return uci;
} else {
return (lci < uci) ? lci : uci;
}
}
/** {@collect.stats}
* Stores the position and size of
* the inner painting area of the specified component
* in <code>r</code> and returns <code>r</code>.
* The position and size specify the bounds of the component,
* adjusted so as not to include the border area (the insets).
* This method is useful for classes
* that implement painting code.
*
* @param c the JComponent in question; if {@code null}, this method returns {@code null}
* @param r the Rectangle instance to be modified;
* may be {@code null}
* @return {@code null} if the Component is {@code null};
* otherwise, returns the passed-in rectangle (if non-{@code null})
* or a new rectangle specifying position and size information
*
* @since 1.4
*/
public static Rectangle calculateInnerArea(JComponent c, Rectangle r) {
if (c == null) {
return null;
}
Rectangle rect = r;
Insets insets = c.getInsets();
if (rect == null) {
rect = new Rectangle();
}
rect.x = insets.left;
rect.y = insets.top;
rect.width = c.getWidth() - insets.left - insets.right;
rect.height = c.getHeight() - insets.top - insets.bottom;
return rect;
}
static void updateRendererOrEditorUI(Object rendererOrEditor) {
if (rendererOrEditor == null) {
return;
}
Component component = null;
if (rendererOrEditor instanceof Component) {
component = (Component)rendererOrEditor;
}
if (rendererOrEditor instanceof DefaultCellEditor) {
component = ((DefaultCellEditor)rendererOrEditor).getComponent();
}
if (component != null) {
SwingUtilities.updateComponentTreeUI(component);
}
}
}
|
Java
|
/*
* Copyright (c) 2000, 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.awt.event.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.plaf.SpinnerUI;
import java.util.*;
import java.beans.*;
import java.text.*;
import java.io.*;
import java.util.HashMap;
import sun.util.resources.LocaleData;
import javax.accessibility.*;
/** {@collect.stats}
* A single line input field that lets the user select a
* number or an object value from an ordered sequence. Spinners typically
* provide a pair of tiny arrow buttons for stepping through the elements
* of the sequence. The keyboard up/down arrow keys also cycle through the
* elements. The user may also be allowed to type a (legal) value directly
* into the spinner. Although combo boxes provide similar functionality,
* spinners are sometimes preferred because they don't require a drop down list
* that can obscure important data.
* <p>
* A <code>JSpinner</code>'s sequence value is defined by its
* <code>SpinnerModel</code>.
* The <code>model</code> can be specified as a constructor argument and
* changed with the <code>model</code> property. <code>SpinnerModel</code>
* classes for some common types are provided: <code>SpinnerListModel</code>,
* <code>SpinnerNumberModel</code>, and <code>SpinnerDateModel</code>.
* <p>
* A <code>JSpinner</code> has a single child component that's
* responsible for displaying
* and potentially changing the current element or <i>value</i> of
* the model, which is called the <code>editor</code>. The editor is created
* by the <code>JSpinner</code>'s constructor and can be changed with the
* <code>editor</code> property. The <code>JSpinner</code>'s editor stays
* in sync with the model by listening for <code>ChangeEvent</code>s. If the
* user has changed the value displayed by the <code>editor</code> it is
* possible for the <code>model</code>'s value to differ from that of
* the <code>editor</code>. To make sure the <code>model</code> has the same
* value as the editor use the <code>commitEdit</code> method, eg:
* <pre>
* try {
* spinner.commitEdit();
* }
* catch (ParseException pe) {{
* // Edited value is invalid, spinner.getValue() will return
* // the last valid value, you could revert the spinner to show that:
* JComponent editor = spinner.getEditor()
* if (editor instanceof DefaultEditor) {
* ((DefaultEditor)editor).getTextField().setValue(spinner.getValue();
* }
* // reset the value to some known value:
* spinner.setValue(fallbackValue);
* // or treat the last valid value as the current, in which
* // case you don't need to do anything.
* }
* return spinner.getValue();
* </pre>
* <p>
* For information and examples of using spinner see
* <a href="http://java.sun.com/doc/books/tutorial/uiswing/components/spinner.html">How to Use Spinners</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 false
* description: A single line input field that lets the user select a
* number or an object value from an ordered set.
*
* @see SpinnerModel
* @see AbstractSpinnerModel
* @see SpinnerListModel
* @see SpinnerNumberModel
* @see SpinnerDateModel
* @see JFormattedTextField
*
* @author Hans Muller
* @author Lynn Monsanto (accessibility)
* @since 1.4
*/
public class JSpinner extends JComponent implements Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "SpinnerUI";
private static final Action DISABLED_ACTION = new DisabledAction();
private transient SpinnerModel model;
private JComponent editor;
private ChangeListener modelListener;
private transient ChangeEvent changeEvent;
private boolean editorExplicitlySet = false;
/** {@collect.stats}
* Constructs a complete spinner with pair of next/previous buttons
* and an editor for the <code>SpinnerModel</code>.
*/
public JSpinner(SpinnerModel model) {
this.model = model;
this.editor = createEditor(model);
setUIProperty("opaque",true);
updateUI();
}
/** {@collect.stats}
* Constructs a spinner with an <code>Integer SpinnerNumberModel</code>
* with initial value 0 and no minimum or maximum limits.
*/
public JSpinner() {
this(new SpinnerNumberModel());
}
/** {@collect.stats}
* Returns the look and feel (L&F) object that renders this component.
*
* @return the <code>SpinnerUI</code> object that renders this component
*/
public SpinnerUI getUI() {
return (SpinnerUI)ui;
}
/** {@collect.stats}
* Sets the look and feel (L&F) object that renders this component.
*
* @param ui the <code>SpinnerUI</code> L&F object
* @see UIDefaults#getUI
*/
public void setUI(SpinnerUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Returns the suffix used to construct the name of the look and feel
* (L&F) class used to render this component.
*
* @return the string "SpinnerUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Resets the UI property with the value from the current look and feel.
*
* @see UIManager#getUI
*/
public void updateUI() {
setUI((SpinnerUI)UIManager.getUI(this));
invalidate();
}
/** {@collect.stats}
* This method is called by the constructors to create the
* <code>JComponent</code>
* that displays the current value of the sequence. The editor may
* also allow the user to enter an element of the sequence directly.
* An editor must listen for <code>ChangeEvents</code> on the
* <code>model</code> and keep the value it displays
* in sync with the value of the model.
* <p>
* Subclasses may override this method to add support for new
* <code>SpinnerModel</code> classes. Alternatively one can just
* replace the editor created here with the <code>setEditor</code>
* method. The default mapping from model type to editor is:
* <ul>
* <li> <code>SpinnerNumberModel => JSpinner.NumberEditor</code>
* <li> <code>SpinnerDateModel => JSpinner.DateEditor</code>
* <li> <code>SpinnerListModel => JSpinner.ListEditor</code>
* <li> <i>all others</i> => <code>JSpinner.DefaultEditor</code>
* </ul>
*
* @return a component that displays the current value of the sequence
* @param model the value of getModel
* @see #getModel
* @see #setEditor
*/
protected JComponent createEditor(SpinnerModel model) {
if (model instanceof SpinnerDateModel) {
return new DateEditor(this);
}
else if (model instanceof SpinnerListModel) {
return new ListEditor(this);
}
else if (model instanceof SpinnerNumberModel) {
return new NumberEditor(this);
}
else {
return new DefaultEditor(this);
}
}
/** {@collect.stats}
* Changes the model that represents the value of this spinner.
* If the editor property has not been explicitly set,
* the editor property is (implicitly) set after the <code>"model"</code>
* <code>PropertyChangeEvent</code> has been fired. The editor
* property is set to the value returned by <code>createEditor</code>,
* as in:
* <pre>
* setEditor(createEditor(model));
* </pre>
*
* @param model the new <code>SpinnerModel</code>
* @see #getModel
* @see #getEditor
* @see #setEditor
* @throws IllegalArgumentException if model is <code>null</code>
*
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Model that represents the value of this spinner.
*/
public void setModel(SpinnerModel model) {
if (model == null) {
throw new IllegalArgumentException("null model");
}
if (!model.equals(this.model)) {
SpinnerModel oldModel = this.model;
this.model = model;
if (modelListener != null) {
oldModel.removeChangeListener(modelListener);
this.model.addChangeListener(modelListener);
}
firePropertyChange("model", oldModel, model);
if (!editorExplicitlySet) {
setEditor(createEditor(model)); // sets editorExplicitlySet true
editorExplicitlySet = false;
}
repaint();
revalidate();
}
}
/** {@collect.stats}
* Returns the <code>SpinnerModel</code> that defines
* this spinners sequence of values.
*
* @return the value of the model property
* @see #setModel
*/
public SpinnerModel getModel() {
return model;
}
/** {@collect.stats}
* Returns the current value of the model, typically
* this value is displayed by the <code>editor</code>. If the
* user has changed the value displayed by the <code>editor</code> it is
* possible for the <code>model</code>'s value to differ from that of
* the <code>editor</code>, refer to the class level javadoc for examples
* of how to deal with this.
* <p>
* This method simply delegates to the <code>model</code>.
* It is equivalent to:
* <pre>
* getModel().getValue()
* </pre>
*
* @see #setValue
* @see SpinnerModel#getValue
*/
public Object getValue() {
return getModel().getValue();
}
/** {@collect.stats}
* Changes current value of the model, typically
* this value is displayed by the <code>editor</code>.
* If the <code>SpinnerModel</code> implementation
* doesn't support the specified value then an
* <code>IllegalArgumentException</code> is thrown.
* <p>
* This method simply delegates to the <code>model</code>.
* It is equivalent to:
* <pre>
* getModel().setValue(value)
* </pre>
*
* @throws IllegalArgumentException if <code>value</code> isn't allowed
* @see #getValue
* @see SpinnerModel#setValue
*/
public void setValue(Object value) {
getModel().setValue(value);
}
/** {@collect.stats}
* Returns the object in the sequence that comes after the object returned
* by <code>getValue()</code>. If the end of the sequence has been reached
* then return <code>null</code>.
* Calling this method does not effect <code>value</code>.
* <p>
* This method simply delegates to the <code>model</code>.
* It is equivalent to:
* <pre>
* getModel().getNextValue()
* </pre>
*
* @return the next legal value or <code>null</code> if one doesn't exist
* @see #getValue
* @see #getPreviousValue
* @see SpinnerModel#getNextValue
*/
public Object getNextValue() {
return getModel().getNextValue();
}
/** {@collect.stats}
* We pass <code>Change</code> events along to the listeners with the
* the slider (instead of the model itself) as the event source.
*/
private class ModelListener implements ChangeListener, Serializable {
public void stateChanged(ChangeEvent e) {
fireStateChanged();
}
}
/** {@collect.stats}
* Adds a listener to the list that is notified each time a change
* to the model occurs. The source of <code>ChangeEvents</code>
* delivered to <code>ChangeListeners</code> will be this
* <code>JSpinner</code>. Note also that replacing the model
* will not affect listeners added directly to JSpinner.
* Applications can add listeners to the model directly. In that
* case is that the source of the event would be the
* <code>SpinnerModel</code>.
*
* @param listener the <code>ChangeListener</code> to add
* @see #removeChangeListener
* @see #getModel
*/
public void addChangeListener(ChangeListener listener) {
if (modelListener == null) {
modelListener = new ModelListener();
getModel().addChangeListener(modelListener);
}
listenerList.add(ChangeListener.class, listener);
}
/** {@collect.stats}
* Removes a <code>ChangeListener</code> from this spinner.
*
* @param listener the <code>ChangeListener</code> to remove
* @see #fireStateChanged
* @see #addChangeListener
*/
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(ChangeListener.class, listener);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this JSpinner with addChangeListener().
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Sends a <code>ChangeEvent</code>, whose source is this
* <code>JSpinner</code>, to each <code>ChangeListener</code>.
* When a <code>ChangeListener</code> has been added
* to the spinner, this method method is called each time
* a <code>ChangeEvent</code> is received from the model.
*
* @see #addChangeListener
* @see #removeChangeListener
* @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 the object in the sequence that comes
* before the object returned by <code>getValue()</code>.
* If the end of the sequence has been reached then
* return <code>null</code>. Calling this method does
* not effect <code>value</code>.
* <p>
* This method simply delegates to the <code>model</code>.
* It is equivalent to:
* <pre>
* getModel().getPreviousValue()
* </pre>
*
* @return the previous legal value or <code>null</code>
* if one doesn't exist
* @see #getValue
* @see #getNextValue
* @see SpinnerModel#getPreviousValue
*/
public Object getPreviousValue() {
return getModel().getPreviousValue();
}
/** {@collect.stats}
* Changes the <code>JComponent</code> that displays the current value
* of the <code>SpinnerModel</code>. It is the responsibility of this
* method to <i>disconnect</i> the old editor from the model and to
* connect the new editor. This may mean removing the
* old editors <code>ChangeListener</code> from the model or the
* spinner itself and adding one for the new editor.
*
* @param editor the new editor
* @see #getEditor
* @see #createEditor
* @see #getModel
* @throws IllegalArgumentException if editor is <code>null</code>
*
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: JComponent that displays the current value of the model
*/
public void setEditor(JComponent editor) {
if (editor == null) {
throw new IllegalArgumentException("null editor");
}
if (!editor.equals(this.editor)) {
JComponent oldEditor = this.editor;
this.editor = editor;
if (oldEditor instanceof DefaultEditor) {
((DefaultEditor)oldEditor).dismiss(this);
}
editorExplicitlySet = true;
firePropertyChange("editor", oldEditor, editor);
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the component that displays and potentially
* changes the model's value.
*
* @return the component that displays and potentially
* changes the model's value
* @see #setEditor
* @see #createEditor
*/
public JComponent getEditor() {
return editor;
}
/** {@collect.stats}
* Commits the currently edited value to the <code>SpinnerModel</code>.
* <p>
* If the editor is an instance of <code>DefaultEditor</code>, the
* call if forwarded to the editor, otherwise this does nothing.
*
* @throws ParseException if the currently edited value couldn't
* be commited.
*/
public void commitEdit() throws ParseException {
JComponent editor = getEditor();
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).commitEdit();
}
}
/*
* 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();
HashMap additionalValues = new HashMap(1);
SpinnerModel model = getModel();
if (model instanceof Serializable) {
additionalValues.put("model", model);
}
s.writeObject(additionalValues);
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
Map additionalValues = (Map)s.readObject();
model = (SpinnerModel)additionalValues.get("model");
}
/** {@collect.stats}
* A simple base class for more specialized editors
* that displays a read-only view of the model's current
* value with a <code>JFormattedTextField</code>. Subclasses
* can configure the <code>JFormattedTextField</code> to create
* an editor that's appropriate for the type of model they
* support and they may want to override
* the <code>stateChanged</code> and <code>propertyChanged</code>
* methods, which keep the model and the text field in sync.
* <p>
* This class defines a <code>dismiss</code> method that removes the
* editors <code>ChangeListener</code> from the <code>JSpinner</code>
* that it's part of. The <code>setEditor</code> method knows about
* <code>DefaultEditor.dismiss</code>, so if the developer
* replaces an editor that's derived from <code>JSpinner.DefaultEditor</code>
* its <code>ChangeListener</code> connection back to the
* <code>JSpinner</code> will be removed. However after that,
* it's up to the developer to manage their editor listeners.
* Similarly, if a subclass overrides <code>createEditor</code>,
* it's up to the subclasser to deal with their editor
* subsequently being replaced (with <code>setEditor</code>).
* We expect that in most cases, and in editor installed
* with <code>setEditor</code> or created by a <code>createEditor</code>
* override, will not be replaced anyway.
* <p>
* This class is the <code>LayoutManager</code> for it's single
* <code>JFormattedTextField</code> child. By default the
* child is just centered with the parents insets.
* @since 1.4
*/
public static class DefaultEditor extends JPanel
implements ChangeListener, PropertyChangeListener, LayoutManager
{
/** {@collect.stats}
* Constructs an editor component for the specified <code>JSpinner</code>.
* This <code>DefaultEditor</code> is it's own layout manager and
* it is added to the spinner's <code>ChangeListener</code> list.
* The constructor creates a single <code>JFormattedTextField</code> child,
* initializes it's value to be the spinner model's current value
* and adds it to <code>this</code> <code>DefaultEditor</code>.
*
* @param spinner the spinner whose model <code>this</code> editor will monitor
* @see #getTextField
* @see JSpinner#addChangeListener
*/
public DefaultEditor(JSpinner spinner) {
super(null);
JFormattedTextField ftf = new JFormattedTextField();
ftf.setName("Spinner.formattedTextField");
ftf.setValue(spinner.getValue());
ftf.addPropertyChangeListener(this);
ftf.setEditable(false);
ftf.setInheritsPopupMenu(true);
String toolTipText = spinner.getToolTipText();
if (toolTipText != null) {
ftf.setToolTipText(toolTipText);
}
add(ftf);
setLayout(this);
spinner.addChangeListener(this);
// We want the spinner's increment/decrement actions to be
// active vs those of the JFormattedTextField. As such we
// put disabled actions in the JFormattedTextField's actionmap.
// A binding to a disabled action is treated as a nonexistant
// binding.
ActionMap ftfMap = ftf.getActionMap();
if (ftfMap != null) {
ftfMap.put("increment", DISABLED_ACTION);
ftfMap.put("decrement", DISABLED_ACTION);
}
}
/** {@collect.stats}
* Disconnect <code>this</code> editor from the specified
* <code>JSpinner</code>. By default, this method removes
* itself from the spinners <code>ChangeListener</code> list.
*
* @param spinner the <code>JSpinner</code> to disconnect this
* editor from; the same spinner as was passed to the constructor.
*/
public void dismiss(JSpinner spinner) {
spinner.removeChangeListener(this);
}
/** {@collect.stats}
* Returns the <code>JSpinner</code> ancestor of this editor or
* <code>null</code> if none of the ancestors are a
* <code>JSpinner</code>.
* Typically the editor's parent is a <code>JSpinner</code> however
* subclasses of <code>JSpinner</code> may override the
* the <code>createEditor</code> method and insert one or more containers
* between the <code>JSpinner</code> and it's editor.
*
* @return <code>JSpinner</code> ancestor; <code>null</code>
* if none of the ancestors are a <code>JSpinner</code>
*
* @see JSpinner#createEditor
*/
public JSpinner getSpinner() {
for (Component c = this; c != null; c = c.getParent()) {
if (c instanceof JSpinner) {
return (JSpinner)c;
}
}
return null;
}
/** {@collect.stats}
* Returns the <code>JFormattedTextField</code> child of this
* editor. By default the text field is the first and only
* child of editor.
*
* @return the <code>JFormattedTextField</code> that gives the user
* access to the <code>SpinnerDateModel's</code> value.
* @see #getSpinner
* @see #getModel
*/
public JFormattedTextField getTextField() {
return (JFormattedTextField)getComponent(0);
}
/** {@collect.stats}
* This method is called when the spinner's model's state changes.
* It sets the <code>value</code> of the text field to the current
* value of the spinners model.
*
* @param e the <code>ChangeEvent</code> whose source is the
* <code>JSpinner</code> whose model has changed.
* @see #getTextField
* @see JSpinner#getValue
*/
public void stateChanged(ChangeEvent e) {
JSpinner spinner = (JSpinner)(e.getSource());
getTextField().setValue(spinner.getValue());
}
/** {@collect.stats}
* Called by the <code>JFormattedTextField</code>
* <code>PropertyChangeListener</code>. When the <code>"value"</code>
* property changes, which implies that the user has typed a new
* number, we set the value of the spinners model.
* <p>
* This class ignores <code>PropertyChangeEvents</code> whose
* source is not the <code>JFormattedTextField</code>, so subclasses
* may safely make <code>this</code> <code>DefaultEditor</code> a
* <code>PropertyChangeListener</code> on other objects.
*
* @param e the <code>PropertyChangeEvent</code> whose source is
* the <code>JFormattedTextField</code> created by this class.
* @see #getTextField
*/
public void propertyChange(PropertyChangeEvent e)
{
JSpinner spinner = getSpinner();
if (spinner == null) {
// Indicates we aren't installed anywhere.
return;
}
Object source = e.getSource();
String name = e.getPropertyName();
if ((source instanceof JFormattedTextField) && "value".equals(name)) {
Object lastValue = spinner.getValue();
// Try to set the new value
try {
spinner.setValue(getTextField().getValue());
} catch (IllegalArgumentException iae) {
// SpinnerModel didn't like new value, reset
try {
((JFormattedTextField)source).setValue(lastValue);
} catch (IllegalArgumentException iae2) {
// Still bogus, nothing else we can do, the
// SpinnerModel and JFormattedTextField are now out
// of sync.
}
}
}
}
/** {@collect.stats}
* This <code>LayoutManager</code> method does nothing. We're
* only managing a single child and there's no support
* for layout constraints.
*
* @param name ignored
* @param child ignored
*/
public void addLayoutComponent(String name, Component child) {
}
/** {@collect.stats}
* This <code>LayoutManager</code> method does nothing. There
* isn't any per-child state.
*
* @param child ignored
*/
public void removeLayoutComponent(Component child) {
}
/** {@collect.stats}
* Returns the size of the parents insets.
*/
private Dimension insetSize(Container parent) {
Insets insets = parent.getInsets();
int w = insets.left + insets.right;
int h = insets.top + insets.bottom;
return new Dimension(w, h);
}
/** {@collect.stats}
* Returns the preferred size of first (and only) child plus the
* size of the parents insets.
*
* @param parent the Container that's managing the layout
* @return the preferred dimensions to lay out the subcomponents
* of the specified container.
*/
public Dimension preferredLayoutSize(Container parent) {
Dimension preferredSize = insetSize(parent);
if (parent.getComponentCount() > 0) {
Dimension childSize = getComponent(0).getPreferredSize();
preferredSize.width += childSize.width;
preferredSize.height += childSize.height;
}
return preferredSize;
}
/** {@collect.stats}
* Returns the minimum size of first (and only) child plus the
* size of the parents insets.
*
* @param parent the Container that's managing the layout
* @return the minimum dimensions needed to lay out the subcomponents
* of the specified container.
*/
public Dimension minimumLayoutSize(Container parent) {
Dimension minimumSize = insetSize(parent);
if (parent.getComponentCount() > 0) {
Dimension childSize = getComponent(0).getMinimumSize();
minimumSize.width += childSize.width;
minimumSize.height += childSize.height;
}
return minimumSize;
}
/** {@collect.stats}
* Resize the one (and only) child to completely fill the area
* within the parents insets.
*/
public void layoutContainer(Container parent) {
if (parent.getComponentCount() > 0) {
Insets insets = parent.getInsets();
int w = parent.getWidth() - (insets.left + insets.right);
int h = parent.getHeight() - (insets.top + insets.bottom);
getComponent(0).setBounds(insets.left, insets.top, w, h);
}
}
/** {@collect.stats}
* Pushes the currently edited value to the <code>SpinnerModel</code>.
* <p>
* The default implementation invokes <code>commitEdit</code> on the
* <code>JFormattedTextField</code>.
*
* @throws ParseException if the edited value is not legal
*/
public void commitEdit() throws ParseException {
// If the value in the JFormattedTextField is legal, this will have
// the result of pushing the value to the SpinnerModel
// by way of the <code>propertyChange</code> method.
JFormattedTextField ftf = getTextField();
ftf.commitEdit();
}
/** {@collect.stats}
* Returns the baseline.
*
* @throws IllegalArgumentException {@inheritDoc}
* @see javax.swing.JComponent#getBaseline(int,int)
* @see javax.swing.JComponent#getBaselineResizeBehavior()
* @since 1.6
*/
public int getBaseline(int width, int height) {
// check size.
super.getBaseline(width, height);
Insets insets = getInsets();
width = width - insets.left - insets.right;
height = height - insets.top - insets.bottom;
int baseline = getComponent(0).getBaseline(width, height);
if (baseline >= 0) {
return baseline + insets.top;
}
return -1;
}
/** {@collect.stats}
* Returns an enum indicating how the baseline of the component
* changes as the size changes.
*
* @throws NullPointerException {@inheritDoc}
* @see javax.swing.JComponent#getBaseline(int, int)
* @since 1.6
*/
public BaselineResizeBehavior getBaselineResizeBehavior() {
return getComponent(0).getBaselineResizeBehavior();
}
}
/** {@collect.stats}
* This subclass of javax.swing.DateFormatter maps the minimum/maximum
* properties to te start/end properties of a SpinnerDateModel.
*/
private static class DateEditorFormatter extends DateFormatter {
private final SpinnerDateModel model;
DateEditorFormatter(SpinnerDateModel model, DateFormat format) {
super(format);
this.model = model;
}
public void setMinimum(Comparable min) {
model.setStart(min);
}
public Comparable getMinimum() {
return model.getStart();
}
public void setMaximum(Comparable max) {
model.setEnd(max);
}
public Comparable getMaximum() {
return model.getEnd();
}
}
/** {@collect.stats}
* An editor for a <code>JSpinner</code> whose model is a
* <code>SpinnerDateModel</code>. The value of the editor is
* displayed with a <code>JFormattedTextField</code> whose format
* is defined by a <code>DateFormatter</code> instance whose
* <code>minimum</code> and <code>maximum</code> properties
* are mapped to the <code>SpinnerDateModel</code>.
* @since 1.4
*/
// PENDING(hmuller): more example javadoc
public static class DateEditor extends DefaultEditor
{
// This is here until SimpleDateFormat gets a constructor that
// takes a Locale: 4923525
private static String getDefaultPattern(Locale loc) {
ResourceBundle r = LocaleData.getDateFormatData(loc);
String[] dateTimePatterns = r.getStringArray("DateTimePatterns");
Object[] dateTimeArgs = {dateTimePatterns[DateFormat.SHORT],
dateTimePatterns[DateFormat.SHORT + 4]};
return MessageFormat.format(dateTimePatterns[8], dateTimeArgs);
}
/** {@collect.stats}
* Construct a <code>JSpinner</code> editor that supports displaying
* and editing the value of a <code>SpinnerDateModel</code>
* with a <code>JFormattedTextField</code>. <code>This</code>
* <code>DateEditor</code> becomes both a <code>ChangeListener</code>
* on the spinners model and a <code>PropertyChangeListener</code>
* on the new <code>JFormattedTextField</code>.
*
* @param spinner the spinner whose model <code>this</code> editor will monitor
* @exception IllegalArgumentException if the spinners model is not
* an instance of <code>SpinnerDateModel</code>
*
* @see #getModel
* @see #getFormat
* @see SpinnerDateModel
*/
public DateEditor(JSpinner spinner) {
this(spinner, getDefaultPattern(spinner.getLocale()));
}
/** {@collect.stats}
* Construct a <code>JSpinner</code> editor that supports displaying
* and editing the value of a <code>SpinnerDateModel</code>
* with a <code>JFormattedTextField</code>. <code>This</code>
* <code>DateEditor</code> becomes both a <code>ChangeListener</code>
* on the spinner and a <code>PropertyChangeListener</code>
* on the new <code>JFormattedTextField</code>.
*
* @param spinner the spinner whose model <code>this</code> editor will monitor
* @param dateFormatPattern the initial pattern for the
* <code>SimpleDateFormat</code> object that's used to display
* and parse the value of the text field.
* @exception IllegalArgumentException if the spinners model is not
* an instance of <code>SpinnerDateModel</code>
*
* @see #getModel
* @see #getFormat
* @see SpinnerDateModel
* @see java.text.SimpleDateFormat
*/
public DateEditor(JSpinner spinner, String dateFormatPattern) {
this(spinner, new SimpleDateFormat(dateFormatPattern,
spinner.getLocale()));
}
/** {@collect.stats}
* Construct a <code>JSpinner</code> editor that supports displaying
* and editing the value of a <code>SpinnerDateModel</code>
* with a <code>JFormattedTextField</code>. <code>This</code>
* <code>DateEditor</code> becomes both a <code>ChangeListener</code>
* on the spinner and a <code>PropertyChangeListener</code>
* on the new <code>JFormattedTextField</code>.
*
* @param spinner the spinner whose model <code>this</code> editor
* will monitor
* @param format <code>DateFormat</code> object that's used to display
* and parse the value of the text field.
* @exception IllegalArgumentException if the spinners model is not
* an instance of <code>SpinnerDateModel</code>
*
* @see #getModel
* @see #getFormat
* @see SpinnerDateModel
* @see java.text.SimpleDateFormat
*/
private DateEditor(JSpinner spinner, DateFormat format) {
super(spinner);
if (!(spinner.getModel() instanceof SpinnerDateModel)) {
throw new IllegalArgumentException(
"model not a SpinnerDateModel");
}
SpinnerDateModel model = (SpinnerDateModel)spinner.getModel();
DateFormatter formatter = new DateEditorFormatter(model, format);
DefaultFormatterFactory factory = new DefaultFormatterFactory(
formatter);
JFormattedTextField ftf = getTextField();
ftf.setEditable(true);
ftf.setFormatterFactory(factory);
/* TBD - initializing the column width of the text field
* is imprecise and doing it here is tricky because
* the developer may configure the formatter later.
*/
try {
String maxString = formatter.valueToString(model.getStart());
String minString = formatter.valueToString(model.getEnd());
ftf.setColumns(Math.max(maxString.length(),
minString.length()));
}
catch (ParseException e) {
// PENDING: hmuller
}
}
/** {@collect.stats}
* Returns the <code>java.text.SimpleDateFormat</code> object the
* <code>JFormattedTextField</code> uses to parse and format
* numbers.
*
* @return the value of <code>getTextField().getFormatter().getFormat()</code>.
* @see #getTextField
* @see java.text.SimpleDateFormat
*/
public SimpleDateFormat getFormat() {
return (SimpleDateFormat)((DateFormatter)(getTextField().getFormatter())).getFormat();
}
/** {@collect.stats}
* Return our spinner ancestor's <code>SpinnerDateModel</code>.
*
* @return <code>getSpinner().getModel()</code>
* @see #getSpinner
* @see #getTextField
*/
public SpinnerDateModel getModel() {
return (SpinnerDateModel)(getSpinner().getModel());
}
}
/** {@collect.stats}
* This subclass of javax.swing.NumberFormatter maps the minimum/maximum
* properties to a SpinnerNumberModel and initializes the valueClass
* of the NumberFormatter to match the type of the initial models value.
*/
private static class NumberEditorFormatter extends NumberFormatter {
private final SpinnerNumberModel model;
NumberEditorFormatter(SpinnerNumberModel model, NumberFormat format) {
super(format);
this.model = model;
setValueClass(model.getValue().getClass());
}
public void setMinimum(Comparable min) {
model.setMinimum(min);
}
public Comparable getMinimum() {
return model.getMinimum();
}
public void setMaximum(Comparable max) {
model.setMaximum(max);
}
public Comparable getMaximum() {
return model.getMaximum();
}
}
/** {@collect.stats}
* An editor for a <code>JSpinner</code> whose model is a
* <code>SpinnerNumberModel</code>. The value of the editor is
* displayed with a <code>JFormattedTextField</code> whose format
* is defined by a <code>NumberFormatter</code> instance whose
* <code>minimum</code> and <code>maximum</code> properties
* are mapped to the <code>SpinnerNumberModel</code>.
* @since 1.4
*/
// PENDING(hmuller): more example javadoc
public static class NumberEditor extends DefaultEditor
{
// This is here until DecimalFormat gets a constructor that
// takes a Locale: 4923525
private static String getDefaultPattern(Locale locale) {
// Get the pattern for the default locale.
ResourceBundle rb = LocaleData.getNumberFormatData(locale);
String[] all = rb.getStringArray("NumberPatterns");
return all[0];
}
/** {@collect.stats}
* Construct a <code>JSpinner</code> editor that supports displaying
* and editing the value of a <code>SpinnerNumberModel</code>
* with a <code>JFormattedTextField</code>. <code>This</code>
* <code>NumberEditor</code> becomes both a <code>ChangeListener</code>
* on the spinner and a <code>PropertyChangeListener</code>
* on the new <code>JFormattedTextField</code>.
*
* @param spinner the spinner whose model <code>this</code> editor will monitor
* @exception IllegalArgumentException if the spinners model is not
* an instance of <code>SpinnerNumberModel</code>
*
* @see #getModel
* @see #getFormat
* @see SpinnerNumberModel
*/
public NumberEditor(JSpinner spinner) {
this(spinner, getDefaultPattern(spinner.getLocale()));
}
/** {@collect.stats}
* Construct a <code>JSpinner</code> editor that supports displaying
* and editing the value of a <code>SpinnerNumberModel</code>
* with a <code>JFormattedTextField</code>. <code>This</code>
* <code>NumberEditor</code> becomes both a <code>ChangeListener</code>
* on the spinner and a <code>PropertyChangeListener</code>
* on the new <code>JFormattedTextField</code>.
*
* @param spinner the spinner whose model <code>this</code> editor will monitor
* @param decimalFormatPattern the initial pattern for the
* <code>DecimalFormat</code> object that's used to display
* and parse the value of the text field.
* @exception IllegalArgumentException if the spinners model is not
* an instance of <code>SpinnerNumberModel</code> or if
* <code>decimalFormatPattern</code> is not a legal
* argument to <code>DecimalFormat</code>
*
* @see #getTextField
* @see SpinnerNumberModel
* @see java.text.DecimalFormat
*/
public NumberEditor(JSpinner spinner, String decimalFormatPattern) {
this(spinner, new DecimalFormat(decimalFormatPattern));
}
/** {@collect.stats}
* Construct a <code>JSpinner</code> editor that supports displaying
* and editing the value of a <code>SpinnerNumberModel</code>
* with a <code>JFormattedTextField</code>. <code>This</code>
* <code>NumberEditor</code> becomes both a <code>ChangeListener</code>
* on the spinner and a <code>PropertyChangeListener</code>
* on the new <code>JFormattedTextField</code>.
*
* @param spinner the spinner whose model <code>this</code> editor will monitor
* @param decimalFormatPattern the initial pattern for the
* <code>DecimalFormat</code> object that's used to display
* and parse the value of the text field.
* @exception IllegalArgumentException if the spinners model is not
* an instance of <code>SpinnerNumberModel</code>
*
* @see #getTextField
* @see SpinnerNumberModel
* @see java.text.DecimalFormat
*/
private NumberEditor(JSpinner spinner, DecimalFormat format) {
super(spinner);
if (!(spinner.getModel() instanceof SpinnerNumberModel)) {
throw new IllegalArgumentException(
"model not a SpinnerNumberModel");
}
SpinnerNumberModel model = (SpinnerNumberModel)spinner.getModel();
NumberFormatter formatter = new NumberEditorFormatter(model,
format);
DefaultFormatterFactory factory = new DefaultFormatterFactory(
formatter);
JFormattedTextField ftf = getTextField();
ftf.setEditable(true);
ftf.setFormatterFactory(factory);
ftf.setHorizontalAlignment(JTextField.RIGHT);
/* TBD - initializing the column width of the text field
* is imprecise and doing it here is tricky because
* the developer may configure the formatter later.
*/
try {
String maxString = formatter.valueToString(model.getMinimum());
String minString = formatter.valueToString(model.getMaximum());
ftf.setColumns(Math.max(maxString.length(),
minString.length()));
}
catch (ParseException e) {
// TBD should throw a chained error here
}
}
/** {@collect.stats}
* Returns the <code>java.text.DecimalFormat</code> object the
* <code>JFormattedTextField</code> uses to parse and format
* numbers.
*
* @return the value of <code>getTextField().getFormatter().getFormat()</code>.
* @see #getTextField
* @see java.text.DecimalFormat
*/
public DecimalFormat getFormat() {
return (DecimalFormat)((NumberFormatter)(getTextField().getFormatter())).getFormat();
}
/** {@collect.stats}
* Return our spinner ancestor's <code>SpinnerNumberModel</code>.
*
* @return <code>getSpinner().getModel()</code>
* @see #getSpinner
* @see #getTextField
*/
public SpinnerNumberModel getModel() {
return (SpinnerNumberModel)(getSpinner().getModel());
}
}
/** {@collect.stats}
* An editor for a <code>JSpinner</code> whose model is a
* <code>SpinnerListModel</code>.
* @since 1.4
*/
public static class ListEditor extends DefaultEditor
{
/** {@collect.stats}
* Construct a <code>JSpinner</code> editor that supports displaying
* and editing the value of a <code>SpinnerListModel</code>
* with a <code>JFormattedTextField</code>. <code>This</code>
* <code>ListEditor</code> becomes both a <code>ChangeListener</code>
* on the spinner and a <code>PropertyChangeListener</code>
* on the new <code>JFormattedTextField</code>.
*
* @param spinner the spinner whose model <code>this</code> editor will monitor
* @exception IllegalArgumentException if the spinners model is not
* an instance of <code>SpinnerListModel</code>
*
* @see #getModel
* @see SpinnerListModel
*/
public ListEditor(JSpinner spinner) {
super(spinner);
if (!(spinner.getModel() instanceof SpinnerListModel)) {
throw new IllegalArgumentException("model not a SpinnerListModel");
}
getTextField().setEditable(true);
getTextField().setFormatterFactory(new
DefaultFormatterFactory(new ListFormatter()));
}
/** {@collect.stats}
* Return our spinner ancestor's <code>SpinnerNumberModel</code>.
*
* @return <code>getSpinner().getModel()</code>
* @see #getSpinner
* @see #getTextField
*/
public SpinnerListModel getModel() {
return (SpinnerListModel)(getSpinner().getModel());
}
/** {@collect.stats}
* ListFormatter provides completion while text is being input
* into the JFormattedTextField. Completion is only done if the
* user is inserting text at the end of the document. Completion
* is done by way of the SpinnerListModel method findNextMatch.
*/
private class ListFormatter extends
JFormattedTextField.AbstractFormatter {
private DocumentFilter filter;
public String valueToString(Object value) throws ParseException {
if (value == null) {
return "";
}
return value.toString();
}
public Object stringToValue(String string) throws ParseException {
return string;
}
protected DocumentFilter getDocumentFilter() {
if (filter == null) {
filter = new Filter();
}
return filter;
}
private class Filter extends DocumentFilter {
public void replace(FilterBypass fb, int offset, int length,
String string, AttributeSet attrs) throws
BadLocationException {
if (string != null && (offset + length) ==
fb.getDocument().getLength()) {
Object next = getModel().findNextMatch(
fb.getDocument().getText(0, offset) +
string);
String value = (next != null) ? next.toString() : null;
if (value != null) {
fb.remove(0, offset + length);
fb.insertString(0, value, null);
getFormattedTextField().select(offset +
string.length(),
value.length());
return;
}
}
super.replace(fb, offset, length, string, attrs);
}
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
replace(fb, offset, 0, string, attr);
}
}
}
}
/** {@collect.stats}
* An Action implementation that is always disabled.
*/
private static class DisabledAction implements Action {
public Object getValue(String key) {
return null;
}
public void putValue(String key, Object value) {
}
public void setEnabled(boolean b) {
}
public boolean isEnabled() {
return false;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
}
public void removePropertyChangeListener(PropertyChangeListener l) {
}
public void actionPerformed(ActionEvent ae) {
}
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> for the <code>JSpinner</code>
*
* @return the <code>AccessibleContext</code> for the <code>JSpinner</code>
* @since 1.5
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJSpinner();
}
return accessibleContext;
}
/** {@collect.stats}
* <code>AccessibleJSpinner</code> implements accessibility
* support for the <code>JSpinner</code> class.
* @since 1.5
*/
protected class AccessibleJSpinner extends AccessibleJComponent
implements AccessibleValue, AccessibleAction, AccessibleText,
AccessibleEditableText, ChangeListener {
private Object oldModelValue = null;
/** {@collect.stats}
* AccessibleJSpinner constructor
*/
protected AccessibleJSpinner() {
// model is guaranteed to be non-null
oldModelValue = model.getValue();
JSpinner.this.addChangeListener(this);
}
/** {@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();
}
Object newModelValue = model.getValue();
firePropertyChange(ACCESSIBLE_VALUE_PROPERTY,
oldModelValue,
newModelValue);
firePropertyChange(ACCESSIBLE_TEXT_PROPERTY,
null,
0); // entire text may have changed
oldModelValue = newModelValue;
}
/* ===== Begin AccessibleContext methods ===== */
/** {@collect.stats}
* Gets the role of this object. The role of the object is the generic
* purpose or use of the class of this object. For example, the role
* of a push button is AccessibleRole.PUSH_BUTTON. The roles in
* AccessibleRole are provided so component developers can pick from
* a set of predefined roles. This enables assistive technologies to
* provide a consistent interface to various tweaked subclasses of
* components (e.g., use AccessibleRole.PUSH_BUTTON for all components
* that act like a push button) as well as distinguish between sublasses
* that behave differently (e.g., AccessibleRole.CHECK_BOX for check boxes
* and AccessibleRole.RADIO_BUTTON for radio buttons).
* <p>Note that the AccessibleRole class is also extensible, so
* custom component developers can define their own AccessibleRole's
* if the set of predefined roles is inadequate.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.SPIN_BOX;
}
/** {@collect.stats}
* Returns the number of accessible children of the object.
*
* @return the number of accessible children of the object.
*/
public int getAccessibleChildrenCount() {
// the JSpinner has one child, the editor
if (editor.getAccessibleContext() != null) {
return 1;
}
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) {
// the JSpinner has one child, the editor
if (i != 0) {
return null;
}
if (editor.getAccessibleContext() != null) {
return (Accessible)editor;
}
return null;
}
/* ===== End AccessibleContext methods ===== */
/** {@collect.stats}
* Gets the AccessibleAction associated with this object that supports
* one or more actions.
*
* @return AccessibleAction if supported by object; else return null
* @see AccessibleAction
*/
public AccessibleAction getAccessibleAction() {
return this;
}
/** {@collect.stats}
* Gets the AccessibleText associated with this object presenting
* text on the display.
*
* @return AccessibleText if supported by object; else return null
* @see AccessibleText
*/
public AccessibleText getAccessibleText() {
return this;
}
/*
* Returns the AccessibleContext for the JSpinner editor
*/
private AccessibleContext getEditorAccessibleContext() {
if (editor instanceof DefaultEditor) {
JTextField textField = ((DefaultEditor)editor).getTextField();
if (textField != null) {
return textField.getAccessibleContext();
}
} else if (editor instanceof Accessible) {
return ((Accessible)editor).getAccessibleContext();
}
return null;
}
/*
* Returns the AccessibleText for the JSpinner editor
*/
private AccessibleText getEditorAccessibleText() {
AccessibleContext ac = getEditorAccessibleContext();
if (ac != null) {
return ac.getAccessibleText();
}
return null;
}
/*
* Returns the AccessibleEditableText for the JSpinner editor
*/
private AccessibleEditableText getEditorAccessibleEditableText() {
AccessibleText at = getEditorAccessibleText();
if (at instanceof AccessibleEditableText) {
return (AccessibleEditableText)at;
}
return null;
}
/** {@collect.stats}
* Gets the AccessibleValue associated with this object.
*
* @return AccessibleValue if supported by object; else return null
* @see AccessibleValue
*
*/
public AccessibleValue getAccessibleValue() {
return this;
}
/* ===== Begin AccessibleValue impl ===== */
/** {@collect.stats}
* Get the value of this object as a Number. If the value has not been
* set, the return value will be null.
*
* @return value of the object
* @see #setCurrentAccessibleValue
*/
public Number getCurrentAccessibleValue() {
Object o = model.getValue();
if (o instanceof Number) {
return (Number)o;
}
return null;
}
/** {@collect.stats}
* Set the value of this object as a Number.
*
* @param n the value to set for this object
* @return true if the value was set; else False
* @see #getCurrentAccessibleValue
*/
public boolean setCurrentAccessibleValue(Number n) {
// try to set the new value
try {
model.setValue(n);
return true;
} catch (IllegalArgumentException iae) {
// SpinnerModel didn't like new value
}
return false;
}
/** {@collect.stats}
* Get the minimum value of this object as a Number.
*
* @return Minimum value of the object; null if this object does not
* have a minimum value
* @see #getMaximumAccessibleValue
*/
public Number getMinimumAccessibleValue() {
if (model instanceof SpinnerNumberModel) {
SpinnerNumberModel numberModel = (SpinnerNumberModel)model;
Object o = numberModel.getMinimum();
if (o instanceof Number) {
return (Number)o;
}
}
return null;
}
/** {@collect.stats}
* Get the maximum value of this object as a Number.
*
* @return Maximum value of the object; null if this object does not
* have a maximum value
* @see #getMinimumAccessibleValue
*/
public Number getMaximumAccessibleValue() {
if (model instanceof SpinnerNumberModel) {
SpinnerNumberModel numberModel = (SpinnerNumberModel)model;
Object o = numberModel.getMaximum();
if (o instanceof Number) {
return (Number)o;
}
}
return null;
}
/* ===== End AccessibleValue impl ===== */
/* ===== Begin AccessibleAction impl ===== */
/** {@collect.stats}
* Returns the number of accessible actions available in this object
* If there are more than one, the first one is considered the "default"
* action of the object.
*
* Two actions are supported: AccessibleAction.INCREMENT which
* increments the spinner value and AccessibleAction.DECREMENT
* which decrements the spinner value
*
* @return the zero-based number of Actions in this object
*/
public int getAccessibleActionCount() {
return 2;
}
/** {@collect.stats}
* Returns a description of the specified action of the object.
*
* @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) {
return AccessibleAction.INCREMENT;
} else if (i == 1) {
return AccessibleAction.DECREMENT;
}
return null;
}
/** {@collect.stats}
* Performs the specified Action on the object
*
* @param i zero-based index of actions. The first action
* (index 0) is AccessibleAction.INCREMENT and the second
* action (index 1) is AccessibleAction.DECREMENT.
* @return true if the action was performed; otherwise false.
* @see #getAccessibleActionCount
*/
public boolean doAccessibleAction(int i) {
if (i < 0 || i > 1) {
return false;
}
Object o = null;
if (i == 0) {
o = getNextValue(); // AccessibleAction.INCREMENT
} else {
o = getPreviousValue(); // AccessibleAction.DECREMENT
}
// try to set the new value
try {
model.setValue(o);
return true;
} catch (IllegalArgumentException iae) {
// SpinnerModel didn't like new value
}
return false;
}
/* ===== End AccessibleAction impl ===== */
/* ===== Begin AccessibleText impl ===== */
/*
* Returns whether source and destination components have the
* same window ancestor
*/
private boolean sameWindowAncestor(Component src, Component dest) {
if (src == null || dest == null) {
return false;
}
return SwingUtilities.getWindowAncestor(src) ==
SwingUtilities.getWindowAncestor(dest);
}
/** {@collect.stats}
* Given a point in local coordinates, return the zero-based index
* of the character under that Point. If the point is invalid,
* this method returns -1.
*
* @param p the Point in local coordinates
* @return the zero-based index of the character under Point p; if
* Point is invalid return -1.
*/
public int getIndexAtPoint(Point p) {
AccessibleText at = getEditorAccessibleText();
if (at != null && sameWindowAncestor(JSpinner.this, editor)) {
// convert point from the JSpinner bounds (source) to
// editor bounds (destination)
Point editorPoint = SwingUtilities.convertPoint(JSpinner.this,
p,
editor);
if (editorPoint != null) {
return at.getIndexAtPoint(editorPoint);
}
}
return -1;
}
/** {@collect.stats}
* Determines the bounding box of the character at the given
* index into the string. The bounds are returned in local
* coordinates. If the index is invalid an empty rectangle is
* returned.
*
* @param i the index into the String
* @return the screen coordinates of the character's bounding box,
* if index is invalid return an empty rectangle.
*/
public Rectangle getCharacterBounds(int i) {
AccessibleText at = getEditorAccessibleText();
if (at != null ) {
Rectangle editorRect = at.getCharacterBounds(i);
if (editorRect != null &&
sameWindowAncestor(JSpinner.this, editor)) {
// return rectangle in the the JSpinner bounds
return SwingUtilities.convertRectangle(editor,
editorRect,
JSpinner.this);
}
}
return null;
}
/** {@collect.stats}
* Returns the number of characters (valid indicies)
*
* @return the number of characters
*/
public int getCharCount() {
AccessibleText at = getEditorAccessibleText();
if (at != null) {
return at.getCharCount();
}
return -1;
}
/** {@collect.stats}
* Returns the zero-based offset of the caret.
*
* Note: That to the right of the caret will have the same index
* value as the offset (the caret is between two characters).
* @return the zero-based offset of the caret.
*/
public int getCaretPosition() {
AccessibleText at = getEditorAccessibleText();
if (at != null) {
return at.getCaretPosition();
}
return -1;
}
/** {@collect.stats}
* Returns the String at a given index.
*
* @param part the CHARACTER, WORD, or SENTENCE to retrieve
* @param index an index within the text
* @return the letter, word, or sentence
*/
public String getAtIndex(int part, int index) {
AccessibleText at = getEditorAccessibleText();
if (at != null) {
return at.getAtIndex(part, index);
}
return null;
}
/** {@collect.stats}
* Returns the String after a given index.
*
* @param part the CHARACTER, WORD, or SENTENCE to retrieve
* @param index an index within the text
* @return the letter, word, or sentence
*/
public String getAfterIndex(int part, int index) {
AccessibleText at = getEditorAccessibleText();
if (at != null) {
return at.getAfterIndex(part, index);
}
return null;
}
/** {@collect.stats}
* Returns the String before a given index.
*
* @param part the CHARACTER, WORD, or SENTENCE to retrieve
* @param index an index within the text
* @return the letter, word, or sentence
*/
public String getBeforeIndex(int part, int index) {
AccessibleText at = getEditorAccessibleText();
if (at != null) {
return at.getBeforeIndex(part, index);
}
return null;
}
/** {@collect.stats}
* Returns the AttributeSet for a given character at a given index
*
* @param i the zero-based index into the text
* @return the AttributeSet of the character
*/
public AttributeSet getCharacterAttribute(int i) {
AccessibleText at = getEditorAccessibleText();
if (at != null) {
return at.getCharacterAttribute(i);
}
return null;
}
/** {@collect.stats}
* Returns the start offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
*
* @return the index into the text of the start of the selection
*/
public int getSelectionStart() {
AccessibleText at = getEditorAccessibleText();
if (at != null) {
return at.getSelectionStart();
}
return -1;
}
/** {@collect.stats}
* Returns the end offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
*
* @return the index into teh text of the end of the selection
*/
public int getSelectionEnd() {
AccessibleText at = getEditorAccessibleText();
if (at != null) {
return at.getSelectionEnd();
}
return -1;
}
/** {@collect.stats}
* Returns the portion of the text that is selected.
*
* @return the String portion of the text that is selected
*/
public String getSelectedText() {
AccessibleText at = getEditorAccessibleText();
if (at != null) {
return at.getSelectedText();
}
return null;
}
/* ===== End AccessibleText impl ===== */
/* ===== Begin AccessibleEditableText impl ===== */
/** {@collect.stats}
* Sets the text contents to the specified string.
*
* @param s the string to set the text contents
*/
public void setTextContents(String s) {
AccessibleEditableText at = getEditorAccessibleEditableText();
if (at != null) {
at.setTextContents(s);
}
}
/** {@collect.stats}
* Inserts the specified string at the given index/
*
* @param index the index in the text where the string will
* be inserted
* @param s the string to insert in the text
*/
public void insertTextAtIndex(int index, String s) {
AccessibleEditableText at = getEditorAccessibleEditableText();
if (at != null) {
at.insertTextAtIndex(index, s);
}
}
/** {@collect.stats}
* Returns the text string between two indices.
*
* @param startIndex the starting index in the text
* @param endIndex the ending index in the text
* @return the text string between the indices
*/
public String getTextRange(int startIndex, int endIndex) {
AccessibleEditableText at = getEditorAccessibleEditableText();
if (at != null) {
return at.getTextRange(startIndex, endIndex);
}
return null;
}
/** {@collect.stats}
* Deletes the text between two indices
*
* @param startIndex the starting index in the text
* @param endIndex the ending index in the text
*/
public void delete(int startIndex, int endIndex) {
AccessibleEditableText at = getEditorAccessibleEditableText();
if (at != null) {
at.delete(startIndex, endIndex);
}
}
/** {@collect.stats}
* Cuts the text between two indices into the system clipboard.
*
* @param startIndex the starting index in the text
* @param endIndex the ending index in the text
*/
public void cut(int startIndex, int endIndex) {
AccessibleEditableText at = getEditorAccessibleEditableText();
if (at != null) {
at.cut(startIndex, endIndex);
}
}
/** {@collect.stats}
* Pastes the text from the system clipboard into the text
* starting at the specified index.
*
* @param startIndex the starting index in the text
*/
public void paste(int startIndex) {
AccessibleEditableText at = getEditorAccessibleEditableText();
if (at != null) {
at.paste(startIndex);
}
}
/** {@collect.stats}
* Replaces the text between two indices with the specified
* string.
*
* @param startIndex the starting index in the text
* @param endIndex the ending index in the text
* @param s the string to replace the text between two indices
*/
public void replaceText(int startIndex, int endIndex, String s) {
AccessibleEditableText at = getEditorAccessibleEditableText();
if (at != null) {
at.replaceText(startIndex, endIndex, s);
}
}
/** {@collect.stats}
* Selects the text between two indices.
*
* @param startIndex the starting index in the text
* @param endIndex the ending index in the text
*/
public void selectText(int startIndex, int endIndex) {
AccessibleEditableText at = getEditorAccessibleEditableText();
if (at != null) {
at.selectText(startIndex, endIndex);
}
}
/** {@collect.stats}
* Sets attributes for the text between two indices.
*
* @param startIndex the starting index in the text
* @param endIndex the ending index in the text
* @param as the attribute set
* @see AttributeSet
*/
public void setAttributes(int startIndex, int endIndex, AttributeSet as) {
AccessibleEditableText at = getEditorAccessibleEditableText();
if (at != null) {
at.setAttributes(startIndex, endIndex, as);
}
}
} /* End AccessibleJSpinner */
}
|
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.awt.image.VolatileImage;
import java.awt.peer.ComponentPeer;
import java.applet.Applet;
import javax.swing.plaf.ViewportUI;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.accessibility.*;
import java.io.Serializable;
/** {@collect.stats}
* The "viewport" or "porthole" through which you see the underlying
* information. When you scroll, what moves is the viewport. It is like
* peering through a camera's viewfinder. Moving the viewfinder upwards
* brings new things into view at the top of the picture and loses
* things that were at the bottom.
* <p>
* By default, <code>JViewport</code> is opaque. To change this, use the
* <code>setOpaque</code> method.
* <p>
* <b>NOTE:</b>We have implemented a faster scrolling algorithm that
* does not require a buffer to draw in. The algorithm works as follows:
* <ol><li>The view and parent view and checked to see if they are
* <code>JComponents</code>,
* if they aren't, stop and repaint the whole viewport.
* <li>If the viewport is obscured by an ancestor, stop and repaint the whole
* viewport.
* <li>Compute the region that will become visible, if it is as big as
* the viewport, stop and repaint the whole view region.
* <li>Obtain the ancestor <code>Window</code>'s graphics and
* do a <code>copyArea</code> on the scrolled region.
* <li>Message the view to repaint the newly visible region.
* <li>The next time paint is invoked on the viewport, if the clip region
* is smaller than the viewport size a timer is kicked off to repaint the
* whole region.
* </ol>
* In general this approach is much faster. Compared to the backing store
* approach this avoids the overhead of maintaining an offscreen buffer and
* having to do two <code>copyArea</code>s.
* Compared to the non backing store case this
* approach will greatly reduce the painted region.
* <p>
* This approach can cause slower times than the backing store approach
* when the viewport is obscured by another window, or partially offscreen.
* When another window
* obscures the viewport the copyArea will copy garbage and a
* paint event will be generated by the system to inform us we need to
* paint the newly exposed region. The only way to handle this is to
* repaint the whole viewport, which can cause slower performance than the
* backing store case. In most applications very rarely will the user be
* scrolling while the viewport is obscured by another window or offscreen,
* so this optimization is usually worth the performance hit when obscured.
* <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}.
*
* @author Hans Muller
* @author Philip Milne
* @see JScrollPane
*/
public class JViewport extends JComponent implements Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ViewportUI";
/** {@collect.stats} Property used to indicate window blitting should not be done.
*/
static final Object EnableWindowBlit = "EnableWindowBlit";
/** {@collect.stats}
* True when the viewport dimensions have been determined.
* The default is false.
*/
protected boolean isViewSizeSet = false;
/** {@collect.stats}
* The last <code>viewPosition</code> that we've painted, so we know how
* much of the backing store image is valid.
*/
protected Point lastPaintPosition = null;
/** {@collect.stats}
* True when this viewport is maintaining an offscreen image of its
* contents, so that some scrolling can take place using fast "bit-blit"
* operations instead of by accessing the view object to construct the
* display. The default is <code>false</code>.
*
* @deprecated As of Java 2 platform v1.3
* @see #setScrollMode
*/
@Deprecated
protected boolean backingStore = false;
/** {@collect.stats} The view image used for a backing store. */
transient protected Image backingStoreImage = null;
/** {@collect.stats}
* The <code>scrollUnderway</code> flag is used for components like
* <code>JList</code>. When the downarrow key is pressed on a
* <code>JList</code> and the selected
* cell is the last in the list, the <code>scrollpane</code> autoscrolls.
* Here, the old selected cell needs repainting and so we need
* a flag to make the viewport do the optimized painting
* only when there is an explicit call to
* <code>setViewPosition(Point)</code>.
* When <code>setBounds</code> is called through other routes,
* the flag is off and the view repaints normally. Another approach
* would be to remove this from the <code>JViewport</code>
* class and have the <code>JList</code> manage this case by using
* <code>setBackingStoreEnabled</code>. The default is
* <code>false</code>.
*/
protected boolean scrollUnderway = false;
/*
* Listener that is notified each time the view changes size.
*/
private ComponentListener viewListener = null;
/* Only one <code>ChangeEvent</code> is needed per
* <code>JViewport</code> instance since the
* event's only (read-only) state is the source property. The source
* of events generated here is always "this".
*/
private transient ChangeEvent changeEvent = null;
/** {@collect.stats}
* Use <code>graphics.copyArea</code> to implement scrolling.
* This is the fastest for most applications.
*
* @see #setScrollMode
* @since 1.3
*/
public static final int BLIT_SCROLL_MODE = 1;
/** {@collect.stats}
* Draws viewport contents into an offscreen image.
* This was previously the default mode for <code>JTable</code>.
* This mode may offer advantages over "blit mode"
* in some cases, but it requires a large chunk of extra RAM.
*
* @see #setScrollMode
* @since 1.3
*/
public static final int BACKINGSTORE_SCROLL_MODE = 2;
/** {@collect.stats}
* This mode uses the very simple method of redrawing the entire
* contents of the scrollpane each time it is scrolled.
* This was the default behavior in Swing 1.0 and Swing 1.1.
* Either of the other two options will provide better performance
* in most cases.
*
* @see #setScrollMode
* @since 1.3
*/
public static final int SIMPLE_SCROLL_MODE = 0;
/** {@collect.stats}
* @see #setScrollMode
* @since 1.3
*/
private int scrollMode = BLIT_SCROLL_MODE;
//
// Window blitting:
//
// As mentioned in the javadoc when using windowBlit a paint event
// will be generated by the system if copyArea copies a non-visible
// portion of the view (in other words, it copies garbage). We are
// not guaranteed to receive the paint event before other mouse events,
// so we can not be sure we haven't already copied garbage a bunch of
// times to different parts of the view. For that reason when a blit
// happens and the Component is obscured (the check for obscurity
// is not supported on all platforms and is checked via ComponentPeer
// methods) the ivar repaintAll is set to true. When paint is received
// if repaintAll is true (we previously did a blit) it is set to
// false, and if the clip region is smaller than the viewport
// waitingForRepaint is set to true and a timer is started. When
// the timer fires if waitingForRepaint is true, repaint is invoked.
// In the mean time, if the view is asked to scroll and waitingForRepaint
// is true, a blit will not happen, instead the non-backing store case
// of scrolling will happen, which will reset waitingForRepaint.
// waitingForRepaint is set to false in paint when the clip rect is
// bigger (or equal) to the size of the viewport.
// A Timer is used instead of just a repaint as it appeared to offer
// better performance.
/** {@collect.stats}
* This is set to true in <code>setViewPosition</code>
* if doing a window blit and the viewport is obscured.
*/
private transient boolean repaintAll;
/** {@collect.stats}
* This is set to true in paint, if <code>repaintAll</code>
* is true and the clip rectangle does not match the bounds.
* If true, and scrolling happens the
* repaint manager is not cleared which then allows for the repaint
* previously invoked to succeed.
*/
private transient boolean waitingForRepaint;
/** {@collect.stats}
* Instead of directly invoking repaint, a <code>Timer</code>
* is started and when it fires, repaint is invoked.
*/
private transient Timer repaintTimer;
/** {@collect.stats}
* Set to true in paintView when paint is invoked.
*/
private transient boolean inBlitPaint;
/** {@collect.stats}
* Whether or not a valid view has been installed.
*/
private boolean hasHadValidView;
/** {@collect.stats} Creates a <code>JViewport</code>. */
public JViewport() {
super();
setLayout(createLayoutManager());
setOpaque(true);
updateUI();
setInheritsPopupMenu(true);
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return a <code>ViewportUI</code> object
* @since 1.3
*/
public ViewportUI getUI() {
return (ViewportUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the <code>ViewportUI</code> L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
* @since 1.3
*/
public void setUI(ViewportUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((ViewportUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns a string that specifies the name of the L&F class
* that renders this component.
*
* @return the string "ViewportUI"
*
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Sets the <code>JViewport</code>'s one lightweight child,
* which can be <code>null</code>.
* (Since there is only one child which occupies the entire viewport,
* the <code>constraints</code> and <code>index</code>
* arguments are ignored.)
*
* @param child the lightweight <code>child</code> of the viewport
* @param constraints the <code>constraints</code> to be respected
* @param index the index
* @see #setView
*/
protected void addImpl(Component child, Object constraints, int index) {
setView(child);
}
/** {@collect.stats}
* Removes the <code>Viewport</code>s one lightweight child.
*
* @see #setView
*/
public void remove(Component child) {
child.removeComponentListener(viewListener);
super.remove(child);
}
/** {@collect.stats}
* Scrolls the view so that <code>Rectangle</code>
* within the view becomes visible.
* <p>
* This attempts to validate the view before scrolling if the
* view is currently not valid - <code>isValid</code> returns false.
* To avoid excessive validation when the containment hierarchy is
* being created this will not validate if one of the ancestors does not
* have a peer, or there is no validate root ancestor, or one of the
* ancestors is not a <code>Window</code> or <code>Applet</code>.
* <p>
* Note that this method will not scroll outside of the
* valid viewport; for example, if <code>contentRect</code> is larger
* than the viewport, scrolling will be confined to the viewport's
* bounds.
*
* @param contentRect the <code>Rectangle</code> to display
* @see JComponent#isValidateRoot
* @see java.awt.Component#isValid
* @see java.awt.Component#getPeer
*/
public void scrollRectToVisible(Rectangle contentRect) {
Component view = getView();
if (view == null) {
return;
} else {
if (!view.isValid()) {
// If the view is not valid, validate. scrollRectToVisible
// may fail if the view is not valid first, contentRect
// could be bigger than invalid size.
validateView();
}
int dx = 0, dy = 0;
dx = positionAdjustment(getWidth(), contentRect.width, contentRect.x);
dy = positionAdjustment(getHeight(), contentRect.height, contentRect.y);
if (dx != 0 || dy != 0) {
Point viewPosition = getViewPosition();
Dimension viewSize = view.getSize();
int startX = viewPosition.x;
int startY = viewPosition.y;
Dimension extent = getExtentSize();
viewPosition.x -= dx;
viewPosition.y -= dy;
// Only constrain the location if the view is valid. If the
// the view isn't valid, it typically indicates the view
// isn't visible yet and most likely has a bogus size as will
// we, and therefore we shouldn't constrain the scrolling
if (view.isValid()) {
if (getParent().getComponentOrientation().isLeftToRight()) {
if (viewPosition.x + extent.width > viewSize.width) {
viewPosition.x = Math.max(0, viewSize.width - extent.width);
} else if (viewPosition.x < 0) {
viewPosition.x = 0;
}
} else {
if (extent.width > viewSize.width) {
viewPosition.x = viewSize.width - extent.width;
} else {
viewPosition.x = Math.max(0, Math.min(viewSize.width - extent.width, viewPosition.x));
}
}
if (viewPosition.y + extent.height > viewSize.height) {
viewPosition.y = Math.max(0, viewSize.height -
extent.height);
}
else if (viewPosition.y < 0) {
viewPosition.y = 0;
}
}
if (viewPosition.x != startX || viewPosition.y != startY) {
setViewPosition(viewPosition);
// NOTE: How JViewport currently works with the
// backing store is not foolproof. The sequence of
// events when setViewPosition
// (scrollRectToVisible) is called is to reset the
// views bounds, which causes a repaint on the
// visible region and sets an ivar indicating
// scrolling (scrollUnderway). When
// JViewport.paint is invoked if scrollUnderway is
// true, the backing store is blitted. This fails
// if between the time setViewPosition is invoked
// and paint is received another repaint is queued
// indicating part of the view is invalid. There
// is no way for JViewport to notice another
// repaint has occured and it ends up blitting
// what is now a dirty region and the repaint is
// never delivered.
// It just so happens JTable encounters this
// behavior by way of scrollRectToVisible, for
// this reason scrollUnderway is set to false
// here, which effectively disables the backing
// store.
scrollUnderway = false;
}
}
}
}
/** {@collect.stats}
* Ascends the <code>Viewport</code>'s parents stopping when
* a component is found that returns
* <code>true</code> to <code>isValidateRoot</code>.
* If all the <code>Component</code>'s parents are visible,
* <code>validate</code> will then be invoked on it. The
* <code>RepaintManager</code> is then invoked with
* <code>removeInvalidComponent</code>. This
* is the synchronous version of a <code>revalidate</code>.
*/
private void validateView() {
Component validateRoot = null;
/* Find the first JComponent ancestor of this component whose
* isValidateRoot() method returns true.
*/
for(Component c = this; c != null; c = c.getParent()) {
if ((c instanceof CellRendererPane) || (c.getPeer() == null)) {
return;
}
if ((c instanceof JComponent) &&
(((JComponent)c).isValidateRoot())) {
validateRoot = c;
break;
}
}
// If no validateRoot, nothing to validate from.
if (validateRoot == null) {
return;
}
// Make sure all ancestors are visible.
Component root = null;
for(Component c = validateRoot; c != null; c = c.getParent()) {
// We don't check isVisible here, otherwise if the component
// is contained in something like a JTabbedPane when the
// component is made visible again it won't have scrolled
// to the correct location.
if (c.getPeer() == null) {
return;
}
if ((c instanceof Window) || (c instanceof Applet)) {
root = c;
break;
}
}
// Make sure there is a Window ancestor.
if (root == null) {
return;
}
// Validate the root.
validateRoot.validate();
// And let the RepaintManager it does not have to validate from
// validateRoot anymore.
RepaintManager rm = RepaintManager.currentManager(this);
if (rm != null) {
rm.removeInvalidComponent((JComponent)validateRoot);
}
}
/* Used by the scrollRectToVisible method to determine the
* proper direction and amount to move by. The integer variables are named
* width, but this method is applicable to height also. The code assumes that
* parentWidth/childWidth are positive and childAt can be negative.
*/
private int positionAdjustment(int parentWidth, int childWidth, int childAt) {
// +-----+
// | --- | No Change
// +-----+
if (childAt >= 0 && childWidth + childAt <= parentWidth) {
return 0;
}
// +-----+
// --------- No Change
// +-----+
if (childAt <= 0 && childWidth + childAt >= parentWidth) {
return 0;
}
// +-----+ +-----+
// | ---- -> | ----|
// +-----+ +-----+
if (childAt > 0 && childWidth <= parentWidth) {
return -childAt + parentWidth - childWidth;
}
// +-----+ +-----+
// | -------- -> |--------
// +-----+ +-----+
if (childAt >= 0 && childWidth >= parentWidth) {
return -childAt;
}
// +-----+ +-----+
// ---- | -> |---- |
// +-----+ +-----+
if (childAt <= 0 && childWidth <= parentWidth) {
return -childAt;
}
// +-----+ +-----+
//-------- | -> --------|
// +-----+ +-----+
if (childAt < 0 && childWidth >= parentWidth) {
return -childAt + parentWidth - childWidth;
}
return 0;
}
/** {@collect.stats}
* The viewport "scrolls" its child (called the "view") by the
* normal parent/child clipping (typically the view is moved in
* the opposite direction of the scroll). A non-<code>null</code> border,
* or non-zero insets, isn't supported, to prevent the geometry
* of this component from becoming complex enough to inhibit
* subclassing. To create a <code>JViewport</code> with a border,
* add it to a <code>JPanel</code> that has a border.
* <p>Note: If <code>border</code> is non-<code>null</code>, this
* method will throw an exception as borders are not supported on
* a <code>JViewPort</code>.
*
* @param border the <code>Border</code> to set
* @exception IllegalArgumentException this method is not implemented
*/
public final void setBorder(Border border) {
if (border != null) {
throw new IllegalArgumentException("JViewport.setBorder() not supported");
}
}
/** {@collect.stats}
* Returns the insets (border) dimensions as (0,0,0,0), since borders
* are not supported on a <code>JViewport</code>.
*
* @return a <code>Rectange</code> of zero dimension and zero origin
* @see #setBorder
*/
public final Insets getInsets() {
return new Insets(0, 0, 0, 0);
}
/** {@collect.stats}
* Returns an <code>Insets</code> object containing this
* <code>JViewport</code>s inset values. The passed-in
* <code>Insets</code> object will be reinitialized, and
* all existing values within this object are overwritten.
*
* @param insets the <code>Insets</code> object which can be reused
* @return this viewports inset values
* @see #getInsets
* @beaninfo
* expert: true
*/
public final Insets getInsets(Insets insets) {
insets.left = insets.top = insets.right = insets.bottom = 0;
return insets;
}
private Graphics getBackingStoreGraphics(Graphics g) {
Graphics bsg = backingStoreImage.getGraphics();
bsg.setColor(g.getColor());
bsg.setFont(g.getFont());
bsg.setClip(g.getClipBounds());
return bsg;
}
private void paintViaBackingStore(Graphics g) {
Graphics bsg = getBackingStoreGraphics(g);
try {
super.paint(bsg);
g.drawImage(backingStoreImage, 0, 0, this);
} finally {
bsg.dispose();
}
}
private void paintViaBackingStore(Graphics g, Rectangle oClip) {
Graphics bsg = getBackingStoreGraphics(g);
try {
super.paint(bsg);
g.setClip(oClip);
g.drawImage(backingStoreImage, 0, 0, this);
} finally {
bsg.dispose();
}
}
/** {@collect.stats}
* The <code>JViewport</code> overrides the default implementation of
* this method (in <code>JComponent</code>) to return false.
* This ensures
* that the drawing machinery will call the <code>Viewport</code>'s
* <code>paint</code>
* implementation rather than messaging the <code>JViewport</code>'s
* children directly.
*
* @return false
*/
public boolean isOptimizedDrawingEnabled() {
return false;
}
/** {@collect.stats}
* Returns true if scroll mode is a BACKINGSTORE_SCROLL_MODE to cause
* painting to originate from <code>JViewport</code>, or one of its
* ancestors. Otherwise returns false.
*
* @return true if if scroll mode is a BACKINGSTORE_SCROLL_MODE.
* @see JComponent#isPaintingOrigin()
*/
boolean isPaintingOrigin() {
if (scrollMode == BACKINGSTORE_SCROLL_MODE) {
return true;
}
return false;
}
/** {@collect.stats}
* Only used by the paint method below.
*/
private Point getViewLocation() {
Component view = getView();
if (view != null) {
return view.getLocation();
}
else {
return new Point(0,0);
}
}
/** {@collect.stats}
* Depending on whether the <code>backingStore</code> is enabled,
* either paint the image through the backing store or paint
* just the recently exposed part, using the backing store
* to "blit" the remainder.
* <blockquote>
* The term "blit" is the pronounced version of the PDP-10
* BLT (BLock Transfer) instruction, which copied a block of
* bits. (In case you were curious.)
* </blockquote>
*
* @param g the <code>Graphics</code> context within which to paint
*/
public void paint(Graphics g)
{
int width = getWidth();
int height = getHeight();
if ((width <= 0) || (height <= 0)) {
return;
}
if (inBlitPaint) {
// We invoked paint as part of copyArea cleanup, let it through.
super.paint(g);
return;
}
if (repaintAll) {
repaintAll = false;
Rectangle clipB = g.getClipBounds();
if (clipB.width < getWidth() ||
clipB.height < getHeight()) {
waitingForRepaint = true;
if (repaintTimer == null) {
repaintTimer = createRepaintTimer();
}
repaintTimer.stop();
repaintTimer.start();
// We really don't need to paint, a future repaint will
// take care of it, but if we don't we get an ugly flicker.
}
else {
if (repaintTimer != null) {
repaintTimer.stop();
}
waitingForRepaint = false;
}
}
else if (waitingForRepaint) {
// Need a complete repaint before resetting waitingForRepaint
Rectangle clipB = g.getClipBounds();
if (clipB.width >= getWidth() &&
clipB.height >= getHeight()) {
waitingForRepaint = false;
repaintTimer.stop();
}
}
if (!backingStore || isBlitting() || getView() == null) {
super.paint(g);
lastPaintPosition = getViewLocation();
return;
}
// If the view is smaller than the viewport and we are not opaque
// (that is, we won't paint our background), we should set the
// clip. Otherwise, as the bounds of the view vary, we will
// blit garbage into the exposed areas.
Rectangle viewBounds = getView().getBounds();
if (!isOpaque()) {
g.clipRect(0, 0, viewBounds.width, viewBounds.height);
}
if (backingStoreImage == null) {
// Backing store is enabled but this is the first call to paint.
// Create the backing store, paint it and then copy to g.
// The backing store image will be created with the size of
// the viewport. We must make sure the clip region is the
// same size, otherwise when scrolling the backing image
// the region outside of the clipped region will not be painted,
// and result in empty areas.
backingStoreImage = createImage(width, height);
Rectangle clip = g.getClipBounds();
if (clip.width != width || clip.height != height) {
if (!isOpaque()) {
g.setClip(0, 0, Math.min(viewBounds.width, width),
Math.min(viewBounds.height, height));
}
else {
g.setClip(0, 0, width, height);
}
paintViaBackingStore(g, clip);
}
else {
paintViaBackingStore(g);
}
}
else {
if (!scrollUnderway || lastPaintPosition.equals(getViewLocation())) {
// No scrolling happened: repaint required area via backing store.
paintViaBackingStore(g);
} else {
// The image was scrolled. Manipulate the backing store and flush it to g.
Point blitFrom = new Point();
Point blitTo = new Point();
Dimension blitSize = new Dimension();
Rectangle blitPaint = new Rectangle();
Point newLocation = getViewLocation();
int dx = newLocation.x - lastPaintPosition.x;
int dy = newLocation.y - lastPaintPosition.y;
boolean canBlit = computeBlit(dx, dy, blitFrom, blitTo, blitSize, blitPaint);
if (!canBlit) {
// The image was either moved diagonally or
// moved by more than the image size: paint normally.
paintViaBackingStore(g);
} else {
int bdx = blitTo.x - blitFrom.x;
int bdy = blitTo.y - blitFrom.y;
// Move the relevant part of the backing store.
Rectangle clip = g.getClipBounds();
// We don't want to inherit the clip region when copying
// bits, if it is inherited it will result in not moving
// all of the image resulting in garbage appearing on
// the screen.
g.setClip(0, 0, width, height);
Graphics bsg = getBackingStoreGraphics(g);
try {
bsg.copyArea(blitFrom.x, blitFrom.y, blitSize.width, blitSize.height, bdx, bdy);
g.setClip(clip.x, clip.y, clip.width, clip.height);
// Paint the rest of the view; the part that has just been exposed.
Rectangle r = viewBounds.intersection(blitPaint);
bsg.setClip(r);
super.paint(bsg);
// Copy whole of the backing store to g.
g.drawImage(backingStoreImage, 0, 0, this);
} finally {
bsg.dispose();
}
}
}
}
lastPaintPosition = getViewLocation();
scrollUnderway = false;
}
/** {@collect.stats}
* Sets the bounds of this viewport. If the viewport's width
* or height has changed, fire a <code>StateChanged</code> event.
*
* @param x left edge of the origin
* @param y top edge of the origin
* @param w width in pixels
* @param h height in pixels
*
* @see JComponent#reshape(int, int, int, int)
*/
public void reshape(int x, int y, int w, int h) {
boolean sizeChanged = (getWidth() != w) || (getHeight() != h);
if (sizeChanged) {
backingStoreImage = null;
}
super.reshape(x, y, w, h);
if (sizeChanged) {
fireStateChanged();
}
}
/** {@collect.stats}
* Used to control the method of scrolling the viewport contents.
* You may want to change this mode to get maximum performance for your
* use case.
*
* @param mode one of the following values:
* <ul>
* <li> JViewport.BLIT_SCROLL_MODE
* <li> JViewport.BACKINGSTORE_SCROLL_MODE
* <li> JViewport.SIMPLE_SCROLL_MODE
* </ul>
*
* @see #BLIT_SCROLL_MODE
* @see #BACKINGSTORE_SCROLL_MODE
* @see #SIMPLE_SCROLL_MODE
*
* @beaninfo
* bound: false
* description: Method of moving contents for incremental scrolls.
* enum: BLIT_SCROLL_MODE JViewport.BLIT_SCROLL_MODE
* BACKINGSTORE_SCROLL_MODE JViewport.BACKINGSTORE_SCROLL_MODE
* SIMPLE_SCROLL_MODE JViewport.SIMPLE_SCROLL_MODE
*
* @since 1.3
*/
public void setScrollMode(int mode) {
scrollMode = mode;
if (mode == BACKINGSTORE_SCROLL_MODE) {
backingStore = true;
} else {
backingStore = false;
}
}
/** {@collect.stats}
* Returns the current scrolling mode.
*
* @return the <code>scrollMode</code> property
* @see #setScrollMode
* @since 1.3
*/
public int getScrollMode() {
return scrollMode;
}
/** {@collect.stats}
* Returns <code>true</code> if this viewport is maintaining
* an offscreen image of its contents.
*
* @return <code>true</code> if <code>scrollMode</code> is
* <code>BACKINGSTORE_SCROLL_MODE</code>
*
* @deprecated As of Java 2 platform v1.3, replaced by
* <code>getScrollMode()</code>.
*/
@Deprecated
public boolean isBackingStoreEnabled() {
return scrollMode == BACKINGSTORE_SCROLL_MODE;
}
/** {@collect.stats}
* If true if this viewport will maintain an offscreen
* image of its contents. The image is used to reduce the cost
* of small one dimensional changes to the <code>viewPosition</code>.
* Rather than repainting the entire viewport we use
* <code>Graphics.copyArea</code> to effect some of the scroll.
*
* @param enabled if true, maintain an offscreen backing store
*
* @deprecated As of Java 2 platform v1.3, replaced by
* <code>setScrollMode()</code>.
*/
@Deprecated
public void setBackingStoreEnabled(boolean enabled) {
if (enabled) {
setScrollMode(BACKINGSTORE_SCROLL_MODE);
} else {
setScrollMode(BLIT_SCROLL_MODE);
}
}
private final boolean isBlitting() {
Component view = getView();
return (scrollMode == BLIT_SCROLL_MODE) &&
(view instanceof JComponent) && ((JComponent)view).isOpaque();
}
/** {@collect.stats}
* Returns the <code>JViewport</code>'s one child or <code>null</code>.
*
* @return the viewports child, or <code>null</code> if none exists
*
* @see #setView
*/
public Component getView() {
return (getComponentCount() > 0) ? getComponent(0) : null;
}
/** {@collect.stats}
* Sets the <code>JViewport</code>'s one lightweight child
* (<code>view</code>), which can be <code>null</code>.
*
* @param view the viewport's new lightweight child
*
* @see #getView
*/
public void setView(Component view) {
/* Remove the viewport's existing children, if any.
* Note that removeAll() isn't used here because it
* doesn't call remove() (which JViewport overrides).
*/
int n = getComponentCount();
for(int i = n - 1; i >= 0; i--) {
remove(getComponent(i));
}
isViewSizeSet = false;
if (view != null) {
super.addImpl(view, null, -1);
viewListener = createViewListener();
view.addComponentListener(viewListener);
}
if (hasHadValidView) {
// Only fire a change if a view has been installed.
fireStateChanged();
}
else if (view != null) {
hasHadValidView = true;
}
revalidate();
repaint();
}
/** {@collect.stats}
* If the view's size hasn't been explicitly set, return the
* preferred size, otherwise return the view's current size.
* If there is no view, return 0,0.
*
* @return a <code>Dimension</code> object specifying the size of the view
*/
public Dimension getViewSize() {
Component view = getView();
if (view == null) {
return new Dimension(0,0);
}
else if (isViewSizeSet) {
return view.getSize();
}
else {
return view.getPreferredSize();
}
}
/** {@collect.stats}
* Sets the size of the view. A state changed event will be fired.
*
* @param newSize a <code>Dimension</code> object specifying the new
* size of the view
*/
public void setViewSize(Dimension newSize) {
Component view = getView();
if (view != null) {
Dimension oldSize = view.getSize();
if (!newSize.equals(oldSize)) {
// scrollUnderway will be true if this is invoked as the
// result of a validate and setViewPosition was previously
// invoked.
scrollUnderway = false;
view.setSize(newSize);
isViewSizeSet = true;
fireStateChanged();
}
}
}
/** {@collect.stats}
* Returns the view coordinates that appear in the upper left
* hand corner of the viewport, or 0,0 if there's no view.
*
* @return a <code>Point</code> object giving the upper left coordinates
*/
public Point getViewPosition() {
Component view = getView();
if (view != null) {
Point p = view.getLocation();
p.x = -p.x;
p.y = -p.y;
return p;
}
else {
return new Point(0,0);
}
}
/** {@collect.stats}
* Sets the view coordinates that appear in the upper left
* hand corner of the viewport, does nothing if there's no view.
*
* @param p a <code>Point</code> object giving the upper left coordinates
*/
public void setViewPosition(Point p)
{
Component view = getView();
if (view == null) {
return;
}
int oldX, oldY, x = p.x, y = p.y;
/* Collect the old x,y values for the views location
* and do the song and dance to avoid allocating
* a Rectangle object if we don't have to.
*/
if (view instanceof JComponent) {
JComponent c = (JComponent)view;
oldX = c.getX();
oldY = c.getY();
}
else {
Rectangle r = view.getBounds();
oldX = r.x;
oldY = r.y;
}
/* The view scrolls in the opposite direction to mouse
* movement.
*/
int newX = -x;
int newY = -y;
if ((oldX != newX) || (oldY != newY)) {
if (!waitingForRepaint && isBlitting() && canUseWindowBlitter()) {
RepaintManager rm = RepaintManager.currentManager(this);
// The cast to JComponent will work, if view is not
// a JComponent, isBlitting will return false.
JComponent jview = (JComponent)view;
Rectangle dirty = rm.getDirtyRegion(jview);
if (dirty == null || !dirty.contains(jview.getVisibleRect())) {
rm.beginPaint();
try {
Graphics g = JComponent.safelyGetGraphics(this);
flushViewDirtyRegion(g, dirty);
view.setLocation(newX, newY);
g.setClip(0,0,getWidth(), Math.min(getHeight(),
jview.getHeight()));
// Repaint the complete component if the blit succeeded
// and needsRepaintAfterBlit returns true.
repaintAll = (windowBlitPaint(g) &&
needsRepaintAfterBlit());
g.dispose();
rm.markCompletelyClean((JComponent)getParent());
rm.markCompletelyClean(this);
rm.markCompletelyClean(jview);
} finally {
rm.endPaint();
}
}
else {
// The visible region is dirty, no point in doing copyArea
view.setLocation(newX, newY);
repaintAll = false;
}
}
else {
scrollUnderway = true;
// This calls setBounds(), and then repaint().
view.setLocation(newX, newY);
repaintAll = false;
}
fireStateChanged();
}
}
/** {@collect.stats}
* Returns a rectangle whose origin is <code>getViewPosition</code>
* and size is <code>getExtentSize</code>.
* This is the visible part of the view, in view coordinates.
*
* @return a <code>Rectangle</code> giving the visible part of
* the view using view coordinates.
*/
public Rectangle getViewRect() {
return new Rectangle(getViewPosition(), getExtentSize());
}
/** {@collect.stats}
* Computes the parameters for a blit where the backing store image
* currently contains <code>oldLoc</code> in the upper left hand corner
* and we're scrolling to <code>newLoc</code>.
* The parameters are modified
* to return the values required for the blit.
*
* @param dx the horizontal delta
* @param dy the vertical delta
* @param blitFrom the <code>Point</code> we're blitting from
* @param blitTo the <code>Point</code> we're blitting to
* @param blitSize the <code>Dimension</code> of the area to blit
* @param blitPaint the area to blit
* @return true if the parameters are modified and we're ready to blit;
* false otherwise
*/
protected boolean computeBlit(
int dx,
int dy,
Point blitFrom,
Point blitTo,
Dimension blitSize,
Rectangle blitPaint)
{
int dxAbs = Math.abs(dx);
int dyAbs = Math.abs(dy);
Dimension extentSize = getExtentSize();
if ((dx == 0) && (dy != 0) && (dyAbs < extentSize.height)) {
if (dy < 0) {
blitFrom.y = -dy;
blitTo.y = 0;
blitPaint.y = extentSize.height + dy;
}
else {
blitFrom.y = 0;
blitTo.y = dy;
blitPaint.y = 0;
}
blitPaint.x = blitFrom.x = blitTo.x = 0;
blitSize.width = extentSize.width;
blitSize.height = extentSize.height - dyAbs;
blitPaint.width = extentSize.width;
blitPaint.height = dyAbs;
return true;
}
else if ((dy == 0) && (dx != 0) && (dxAbs < extentSize.width)) {
if (dx < 0) {
blitFrom.x = -dx;
blitTo.x = 0;
blitPaint.x = extentSize.width + dx;
}
else {
blitFrom.x = 0;
blitTo.x = dx;
blitPaint.x = 0;
}
blitPaint.y = blitFrom.y = blitTo.y = 0;
blitSize.width = extentSize.width - dxAbs;
blitSize.height = extentSize.height;
blitPaint.width = dxAbs;
blitPaint.height = extentSize.height;
return true;
}
else {
return false;
}
}
/** {@collect.stats}
* Returns the size of the visible part of the view in view coordinates.
*
* @return a <code>Dimension</code> object giving the size of the view
*/
public Dimension getExtentSize() {
return getSize();
}
/** {@collect.stats}
* Converts a size in pixel coordinates to view coordinates.
* Subclasses of viewport that support "logical coordinates"
* will override this method.
*
* @param size a <code>Dimension</code> object using pixel coordinates
* @return a <code>Dimension</code> object converted to view coordinates
*/
public Dimension toViewCoordinates(Dimension size) {
return new Dimension(size);
}
/** {@collect.stats}
* Converts a point in pixel coordinates to view coordinates.
* Subclasses of viewport that support "logical coordinates"
* will override this method.
*
* @param p a <code>Point</code> object using pixel coordinates
* @return a <code>Point</code> object converted to view coordinates
*/
public Point toViewCoordinates(Point p) {
return new Point(p);
}
/** {@collect.stats}
* Sets the size of the visible part of the view using view coordinates.
*
* @param newExtent a <code>Dimension</code> object specifying
* the size of the view
*/
public void setExtentSize(Dimension newExtent) {
Dimension oldExtent = getExtentSize();
if (!newExtent.equals(oldExtent)) {
setSize(newExtent);
fireStateChanged();
}
}
/** {@collect.stats}
* A listener for the view.
* <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 ViewListener extends ComponentAdapter implements Serializable
{
public void componentResized(ComponentEvent e) {
fireStateChanged();
revalidate();
}
}
/** {@collect.stats}
* Creates a listener for the view.
* @return a <code>ViewListener</code>
*/
protected ViewListener createViewListener() {
return new ViewListener();
}
/** {@collect.stats}
* Subclassers can override this to install a different
* layout manager (or <code>null</code>) in the constructor. Returns
* the <code>LayoutManager</code> to install on the <code>JViewport</code>.
*
* @return a <code>LayoutManager</code>
*/
protected LayoutManager createLayoutManager() {
return ViewportLayout.SHARED_INSTANCE;
}
/** {@collect.stats}
* Adds a <code>ChangeListener</code> to the list that is
* notified each time the view's
* size, position, or the viewport's extent size has changed.
*
* @param l the <code>ChangeListener</code> to add
* @see #removeChangeListener
* @see #setViewPosition
* @see #setViewSize
* @see #setExtentSize
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a <code>ChangeListener</code> from the list that's notified each
* time the views size, position, or the viewports extent size
* has changed.
*
* @param l the <code>ChangeListener</code> to remove
* @see #addChangeListener
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this JViewport with addChangeListener().
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Notifies all <code>ChangeListeners</code> when the views
* size, position, or the viewports extent size has changed.
*
* @see #addChangeListener
* @see #removeChangeListener
* @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}
* Always repaint in the parents coordinate system to make sure
* only one paint is performed by the <code>RepaintManager</code>.
*
* @param tm maximum time in milliseconds before update
* @param x the <code>x</code> coordinate (pixels over from left)
* @param y the <code>y</code> coordinate (pixels down from top)
* @param w the width
* @param h the height
* @see java.awt.Component#update(java.awt.Graphics)
*/
public void repaint(long tm, int x, int y, int w, int h) {
Container parent = getParent();
if(parent != null)
parent.repaint(tm,x+getX(),y+getY(),w,h);
else
super.repaint(tm,x,y,w,h);
}
/** {@collect.stats}
* Returns a string representation of this <code>JViewport</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>JViewport</code>
*/
protected String paramString() {
String isViewSizeSetString = (isViewSizeSet ?
"true" : "false");
String lastPaintPositionString = (lastPaintPosition != null ?
lastPaintPosition.toString() : "");
String scrollUnderwayString = (scrollUnderway ?
"true" : "false");
return super.paramString() +
",isViewSizeSet=" + isViewSizeSetString +
",lastPaintPosition=" + lastPaintPositionString +
",scrollUnderway=" + scrollUnderwayString;
}
//
// Following is used when doBlit is true.
//
/** {@collect.stats}
* Notifies listeners of a property change. This is subclassed to update
* the <code>windowBlit</code> property.
* (The <code>putClientProperty</code> property is final).
*
* @param propertyName a string containing the property name
* @param oldValue the old value of the property
* @param newValue the new value of the property
*/
protected void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
super.firePropertyChange(propertyName, oldValue, newValue);
if (propertyName.equals(EnableWindowBlit)) {
if (newValue != null) {
setScrollMode(BLIT_SCROLL_MODE);
} else {
setScrollMode(SIMPLE_SCROLL_MODE);
}
}
}
/** {@collect.stats}
* Returns true if the component needs to be completely repainted after
* a blit and a paint is received.
*/
private boolean needsRepaintAfterBlit() {
// Find the first heavy weight ancestor. isObscured and
// canDetermineObscurity are only appropriate for heavy weights.
Component heavyParent = getParent();
while (heavyParent != null && heavyParent.isLightweight()) {
heavyParent = heavyParent.getParent();
}
if (heavyParent != null) {
ComponentPeer peer = heavyParent.getPeer();
if (peer != null && peer.canDetermineObscurity() &&
!peer.isObscured()) {
// The peer says we aren't obscured, therefore we can assume
// that we won't later be messaged to paint a portion that
// we tried to blit that wasn't valid.
// It is certainly possible that when we blited we were
// obscured, and by the time this is invoked we aren't, but the
// chances of that happening are pretty slim.
return false;
}
}
return true;
}
private Timer createRepaintTimer() {
Timer timer = new Timer(300, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// waitingForRepaint will be false if a paint came down
// with the complete clip rect, in which case we don't
// have to cause a repaint.
if (waitingForRepaint) {
repaint();
}
}
});
timer.setRepeats(false);
return timer;
}
/** {@collect.stats}
* If the repaint manager has a dirty region for the view, the view is
* asked to paint.
*
* @param g the <code>Graphics</code> context within which to paint
*/
private void flushViewDirtyRegion(Graphics g, Rectangle dirty) {
JComponent view = (JComponent) getView();
if(dirty != null && dirty.width > 0 && dirty.height > 0) {
dirty.x += view.getX();
dirty.y += view.getY();
Rectangle clip = g.getClipBounds();
if (clip == null) {
// Only happens in 1.2
g.setClip(0, 0, getWidth(), getHeight());
}
g.clipRect(dirty.x, dirty.y, dirty.width, dirty.height);
clip = g.getClipBounds();
// Only paint the dirty region if it is visible.
if (clip.width > 0 && clip.height > 0) {
paintView(g);
}
}
}
/** {@collect.stats}
* Used when blitting.
*
* @param g the <code>Graphics</code> context within which to paint
* @return true if blitting succeeded; otherwise false
*/
private boolean windowBlitPaint(Graphics g) {
int width = getWidth();
int height = getHeight();
if ((width == 0) || (height == 0)) {
return false;
}
boolean retValue;
RepaintManager rm = RepaintManager.currentManager(this);
JComponent view = (JComponent) getView();
if (lastPaintPosition == null ||
lastPaintPosition.equals(getViewLocation())) {
paintView(g);
retValue = false;
} else {
// The image was scrolled. Manipulate the backing store and flush
// it to g.
Point blitFrom = new Point();
Point blitTo = new Point();
Dimension blitSize = new Dimension();
Rectangle blitPaint = new Rectangle();
Point newLocation = getViewLocation();
int dx = newLocation.x - lastPaintPosition.x;
int dy = newLocation.y - lastPaintPosition.y;
boolean canBlit = computeBlit(dx, dy, blitFrom, blitTo, blitSize,
blitPaint);
if (!canBlit) {
paintView(g);
retValue = false;
} else {
// Prepare the rest of the view; the part that has just been
// exposed.
Rectangle r = view.getBounds().intersection(blitPaint);
r.x -= view.getX();
r.y -= view.getY();
blitDoubleBuffered(view, g, r.x, r.y, r.width, r.height,
blitFrom.x, blitFrom.y, blitTo.x, blitTo.y,
blitSize.width, blitSize.height);
retValue = true;
}
}
lastPaintPosition = getViewLocation();
return retValue;
}
//
// NOTE: the code below uses paintForceDoubleBuffered for historical
// reasons. If we're going to allow a blit we've already accounted for
// everything that paintImmediately and _paintImmediately does, for that
// reason we call into paintForceDoubleBuffered to diregard whether or
// not setDoubleBuffered(true) was invoked on the view.
//
private void blitDoubleBuffered(JComponent view, Graphics g,
int clipX, int clipY, int clipW, int clipH,
int blitFromX, int blitFromY, int blitToX, int blitToY,
int blitW, int blitH) {
// NOTE:
// blitFrom/blitTo are in JViewport coordinates system
// not the views coordinate space.
// clip* are in the views coordinate space.
RepaintManager rm = RepaintManager.currentManager(this);
int bdx = blitToX - blitFromX;
int bdy = blitToY - blitFromY;
// Shift the scrolled region
rm.copyArea(this, g, blitFromX, blitFromY, blitW, blitH, bdx, bdy,
false);
// Paint the newly exposed region.
int x = view.getX();
int y = view.getY();
g.translate(x, y);
g.setClip(clipX, clipY, clipW, clipH);
view.paintForceDoubleBuffered(g);
g.translate(-x, -y);
}
/** {@collect.stats}
* Called to paint the view, usually when <code>blitPaint</code>
* can not blit.
*
* @param g the <code>Graphics</code> context within which to paint
*/
private void paintView(Graphics g) {
Rectangle clip = g.getClipBounds();
JComponent view = (JComponent)getView();
if (view.getWidth() >= getWidth()) {
// Graphics is relative to JViewport, need to map to view's
// coordinates space.
int x = view.getX();
int y = view.getY();
g.translate(x, y);
g.setClip(clip.x - x, clip.y - y, clip.width, clip.height);
view.paintForceDoubleBuffered(g);
g.translate(-x, -y);
g.setClip(clip.x, clip.y, clip.width, clip.height);
}
else {
// To avoid any problems that may result from the viewport being
// bigger than the view we start painting from the viewport.
try {
inBlitPaint = true;
paintForceDoubleBuffered(g);
} finally {
inBlitPaint = false;
}
}
}
/** {@collect.stats}
* Returns true if the viewport is not obscured by one of its ancestors,
* or its ancestors children and if the viewport is showing. Blitting
* when the view isn't showing will work,
* or rather <code>copyArea</code> will work,
* but will not produce the expected behavior.
*/
private boolean canUseWindowBlitter() {
if (!isShowing() || (!(getParent() instanceof JComponent) &&
!(getView() instanceof JComponent))) {
return false;
}
if (isPainting()) {
// We're in the process of painting, don't blit. If we were
// to blit we would draw on top of what we're already drawing,
// so bail.
return false;
}
Rectangle dirtyRegion = RepaintManager.currentManager(this).
getDirtyRegion((JComponent)getParent());
if (dirtyRegion != null && dirtyRegion.width > 0 &&
dirtyRegion.height > 0) {
// Part of the scrollpane needs to be repainted too, don't blit.
return false;
}
Rectangle clip = new Rectangle(0,0,getWidth(),getHeight());
Rectangle oldClip = new Rectangle();
Rectangle tmp2 = null;
Container parent;
Component lastParent = null;
int x, y, w, h;
for(parent = this; parent != null && isLightweightComponent(parent); parent = parent.getParent()) {
x = parent.getX();
y = parent.getY();
w = parent.getWidth();
h = parent.getHeight();
oldClip.setBounds(clip);
SwingUtilities.computeIntersection(0, 0, w, h, clip);
if(!clip.equals(oldClip))
return false;
if(lastParent != null && parent instanceof JComponent &&
!((JComponent)parent).isOptimizedDrawingEnabled()) {
Component comps[] = parent.getComponents();
int index = 0;
for(int i = comps.length - 1 ;i >= 0; i--) {
if(comps[i] == lastParent) {
index = i - 1;
break;
}
}
while(index >= 0) {
tmp2 = comps[index].getBounds(tmp2);
if(tmp2.intersects(clip))
return false;
index--;
}
}
clip.x += x;
clip.y += y;
lastParent = parent;
}
if (parent == null) {
// No Window parent.
return false;
}
return true;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JViewport.
* For viewports, the AccessibleContext takes the form of an
* AccessibleJViewport.
* A new AccessibleJViewport instance is created if necessary.
*
* @return an AccessibleJViewport that serves as the
* AccessibleContext of this JViewport
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJViewport();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JViewport</code> class. It provides an implementation of the
* Java Accessibility API appropriate to viewport 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 AccessibleJViewport extends AccessibleJComponent {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of
* the object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.VIEWPORT;
}
} // inner class AccessibleJViewport
}
|
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.util.ArrayList;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** {@collect.stats}
* <code>RowFilter</code> is used to filter out entries from the
* model so that they are not shown in the view. For example, a
* <code>RowFilter</code> associated with a <code>JTable</code> might
* only allow rows that contain a column with a specific string. The
* meaning of <em>entry</em> depends on the component type.
* For example, when a filter is
* associated with a <code>JTable</code>, an entry corresponds to a
* row; when associated with a <code>JTree</code>, an entry corresponds
* to a node.
* <p>
* Subclasses must override the <code>include</code> method to
* indicate whether the entry should be shown in the
* view. The <code>Entry</code> argument can be used to obtain the values in
* each of the columns in that entry. The following example shows an
* <code>include</code> method that allows only entries containing one or
* more values starting with the string "a":
* <pre>
* RowFilter<Object,Object> startsWithAFilter = new RowFilter<Object,Object>() {
* public boolean include(Entry<? extends Object, ? extends Object> entry) {
* for (int i = entry.getValueCount() - 1; i >= 0; i--) {
* if (entry.getStringValue(i).startsWith("a")) {
* // The value starts with "a", include it
* return true;
* }
* }
* // None of the columns start with "a"; return false so that this
* // entry is not shown
* return false;
* }
* };
* </pre>
* <code>RowFilter</code> has two formal type parameters that allow
* you to create a <code>RowFilter</code> for a specific model. For
* example, the following assumes a specific model that is wrapping
* objects of type <code>Person</code>. Only <code>Person</code>s
* with an age over 20 will be shown:
* <pre>
* RowFilter<PersonModel,Integer> ageFilter = new RowFilter<PersonModel,Integer>() {
* public boolean include(Entry<? extends PersonModel, ? extends Integer> entry) {
* PersonModel personModel = entry.getModel();
* Person person = personModel.getPerson(entry.getIdentifier());
* if (person.getAge() > 20) {
* // Returning true indicates this row should be shown.
* return true;
* }
* // Age is <= 20, don't show it.
* return false;
* }
* };
* PersonModel model = createPersonModel();
* TableRowSorter<PersonModel> sorter = new TableRowSorter<PersonModel>(model);
* sorter.setRowFilter(ageFilter);
* </pre>
*
* @param <M> the type of the model; for example <code>PersonModel</code>
* @param <I> the type of the identifier; when using
* <code>TableRowSorter</code> this will be <code>Integer</code>
* @see javax.swing.table.TableRowSorter
* @since 1.6
*/
public abstract class RowFilter<M,I> {
/** {@collect.stats}
* Enumeration of the possible comparison values supported by
* some of the default <code>RowFilter</code>s.
*
* @see RowFilter
* @since 1.6
*/
public enum ComparisonType {
/** {@collect.stats}
* Indicates that entries with a value before the supplied
* value should be included.
*/
BEFORE,
/** {@collect.stats}
* Indicates that entries with a value after the supplied
* value should be included.
*/
AFTER,
/** {@collect.stats}
* Indicates that entries with a value equal to the supplied
* value should be included.
*/
EQUAL,
/** {@collect.stats}
* Indicates that entries with a value not equal to the supplied
* value should be included.
*/
NOT_EQUAL
}
/** {@collect.stats}
* Throws an IllegalArgumentException if any of the values in
* columns are < 0.
*/
private static void checkIndices(int[] columns) {
for (int i = columns.length - 1; i >= 0; i--) {
if (columns[i] < 0) {
throw new IllegalArgumentException("Index must be >= 0");
}
}
}
/** {@collect.stats}
* Returns a <code>RowFilter</code> that uses a regular
* expression to determine which entries to include. Only entries
* with at least one matching value are included. For
* example, the following creates a <code>RowFilter</code> that
* includes entries with at least one value starting with
* "a":
* <pre>
* RowFilter.regexFilter("^a");
* </pre>
* <p>
* The returned filter uses {@link java.util.regex.Matcher#find}
* to test for inclusion. To test for exact matches use the
* characters '^' and '$' to match the beginning and end of the
* string respectively. For example, "^foo$" includes only rows whose
* string is exactly "foo" and not, for example, "food". See
* {@link java.util.regex.Pattern} for a complete description of
* the supported regular-expression constructs.
*
* @param regex the regular expression to filter on
* @param indices the indices of the values to check. If not supplied all
* values are evaluated
* @return a <code>RowFilter</code> implementing the specified criteria
* @throws NullPointerException if <code>regex</code> is
* <code>null</code>
* @throws IllegalArgumentException if any of the <code>indices</code>
* are < 0
* @throws PatternSyntaxException if <code>regex</code> is
* not a valid regular expression.
* @see java.util.regex.Pattern
*/
public static <M,I> RowFilter<M,I> regexFilter(String regex,
int... indices) {
return (RowFilter<M,I>)new RegexFilter(Pattern.compile(regex),
indices);
}
/** {@collect.stats}
* Returns a <code>RowFilter</code> that includes entries that
* have at least one <code>Date</code> value meeting the specified
* criteria. For example, the following <code>RowFilter</code> includes
* only entries with at least one date value after the current date:
* <pre>
* RowFilter.dateFilter(ComparisonType.AFTER, new Date());
* </pre>
*
* @param type the type of comparison to perform
* @param date the date to compare against
* @param indices the indices of the values to check. If not supplied all
* values are evaluated
* @return a <code>RowFilter</code> implementing the specified criteria
* @throws NullPointerException if <code>date</code> is
* <code>null</code>
* @throws IllegalArgumentException if any of the <code>indices</code>
* are < 0 or <code>type</code> is
* <code>null</code>
* @see java.util.Calendar
* @see java.util.Date
*/
public static <M,I> RowFilter<M,I> dateFilter(ComparisonType type,
Date date, int... indices) {
return (RowFilter<M,I>)new DateFilter(type, date.getTime(), indices);
}
/** {@collect.stats}
* Returns a <code>RowFilter</code> that includes entries that
* have at least one <code>Number</code> value meeting the
* specified criteria. For example, the following
* filter will only include entries with at
* least one number value equal to 10:
* <pre>
* RowFilter.numberFilter(ComparisonType.EQUAL, 10);
* </pre>
*
* @param type the type of comparison to perform
* @param indices the indices of the values to check. If not supplied all
* values are evaluated
* @return a <code>RowFilter</code> implementing the specified criteria
* @throws IllegalArgumentException if any of the <code>indices</code>
* are < 0, <code>type</code> is <code>null</code>
* or <code>number</code> is <code>null</code>
*/
public static <M,I> RowFilter<M,I> numberFilter(ComparisonType type,
Number number, int... indices) {
return (RowFilter<M,I>)new NumberFilter(type, number, indices);
}
/** {@collect.stats}
* Returns a <code>RowFilter</code> that includes entries if any
* of the supplied filters includes the entry.
* <p>
* The following example creates a <code>RowFilter</code> that will
* include any entries containing the string "foo" or the string
* "bar":
* <pre>
* List<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
* filters.add(RowFilter.regexFilter("foo"));
* filters.add(RowFilter.regexFilter("bar"));
* RowFilter<Object,Object> fooBarFilter = RowFilter.orFilter(filters);
* </pre>
*
* @param filters the <code>RowFilter</code>s to test
* @throws IllegalArgumentException if any of the filters
* are <code>null</code>
* @throws NullPointerException if <code>filters</code> is null
* @return a <code>RowFilter</code> implementing the specified criteria
* @see java.util.Arrays#asList
*/
public static <M,I> RowFilter<M,I> orFilter(
Iterable<? extends RowFilter<? super M, ? super I>> filters) {
return new OrFilter<M,I>(filters);
}
/** {@collect.stats}
* Returns a <code>RowFilter</code> that includes entries if all
* of the supplied filters include the entry.
* <p>
* The following example creates a <code>RowFilter</code> that will
* include any entries containing the string "foo" and the string
* "bar":
* <pre>
* List<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
* filters.add(RowFilter.regexFilter("foo"));
* filters.add(RowFilter.regexFilter("bar"));
* RowFilter<Object,Object> fooBarFilter = RowFilter.andFilter(filters);
* </pre>
*
* @param filters the <code>RowFilter</code>s to test
* @return a <code>RowFilter</code> implementing the specified criteria
* @throws IllegalArgumentException if any of the filters
* are <code>null</code>
* @throws NullPointerException if <code>filters</code> is null
* @see java.util.Arrays#asList
*/
public static <M,I> RowFilter<M,I> andFilter(
Iterable<? extends RowFilter<? super M, ? super I>> filters) {
return new AndFilter<M,I>(filters);
}
/** {@collect.stats}
* Returns a <code>RowFilter</code> that includes entries if the
* supplied filter does not include the entry.
*
* @param filter the <code>RowFilter</code> to negate
* @return a <code>RowFilter</code> implementing the specified criteria
* @throws IllegalArgumentException if <code>filter</code> is
* <code>null</code>
*/
public static <M,I> RowFilter<M,I> notFilter(RowFilter<M,I> filter) {
return new NotFilter<M,I>(filter);
}
/** {@collect.stats}
* Returns true if the specified entry should be shown;
* returns false if the entry should be hidden.
* <p>
* The <code>entry</code> argument is valid only for the duration of
* the invocation. Using <code>entry</code> after the call returns
* results in undefined behavior.
*
* @param entry a non-<code>null</code> object that wraps the underlying
* object from the model
* @return true if the entry should be shown
*/
public abstract boolean include(Entry<? extends M, ? extends I> entry);
//
// WARNING:
// Because of the method signature of dateFilter/numberFilter/regexFilter
// we can NEVER add a method to RowFilter that returns M,I. If we were
// to do so it would be possible to get a ClassCastException during normal
// usage.
//
/** {@collect.stats}
* An <code>Entry</code> object is passed to instances of
* <code>RowFilter</code>, allowing the filter to get the value of the
* entry's data, and thus to determine whether the entry should be shown.
* An <code>Entry</code> object contains information about the model
* as well as methods for getting the underlying values from the model.
*
* @param <M> the type of the model; for example <code>PersonModel</code>
* @param <I> the type of the identifier; when using
* <code>TableRowSorter</code> this will be <code>Integer</code>
* @see javax.swing.RowFilter
* @see javax.swing.DefaultRowSorter#setRowFilter(javax.swing.RowFilter)
* @since 1.6
*/
public static abstract class Entry<M, I> {
/** {@collect.stats}
* Creates an <code>Entry</code>.
*/
public Entry() {
}
/** {@collect.stats}
* Returns the underlying model.
*
* @return the model containing the data that this entry represents
*/
public abstract M getModel();
/** {@collect.stats}
* Returns the number of values in the entry. For
* example, when used with a table this corresponds to the
* number of columns.
*
* @return number of values in the object being filtered
*/
public abstract int getValueCount();
/** {@collect.stats}
* Returns the value at the specified index. This may return
* <code>null</code>. When used with a table, index
* corresponds to the column number in the model.
*
* @param index the index of the value to get
* @return value at the specified index
* @throws <code>IndexOutOfBoundsException</code> if index < 0 or
* >= getValueCount
*/
public abstract Object getValue(int index);
/** {@collect.stats}
* Returns the string value at the specified index. If
* filtering is being done based on <code>String</code> values
* this method is preferred to that of <code>getValue</code>
* as <code>getValue(index).toString()</code> may return a
* different result than <code>getStringValue(index)</code>.
* <p>
* This implementation calls <code>getValue(index).toString()</code>
* after checking for <code>null</code>. Subclasses that provide
* different string conversion should override this method if
* necessary.
*
* @param index the index of the value to get
* @return {@code non-null} string at the specified index
* @throws <code>IndexOutOfBoundsException</code> if index < 0 ||
* >= getValueCount
*/
public String getStringValue(int index) {
Object value = getValue(index);
return (value == null) ? "" : value.toString();
}
/** {@collect.stats}
* Returns the identifer (in the model) of the entry.
* For a table this corresponds to the index of the row in the model,
* expressed as an <code>Integer</code>.
*
* @return a model-based (not view-based) identifier for
* this entry
*/
public abstract I getIdentifier();
}
private static abstract class GeneralFilter extends RowFilter<Object,Object> {
private int[] columns;
GeneralFilter(int[] columns) {
checkIndices(columns);
this.columns = columns;
}
public boolean include(Entry<? extends Object,? extends Object> value){
int count = value.getValueCount();
if (columns.length > 0) {
for (int i = columns.length - 1; i >= 0; i--) {
int index = columns[i];
if (index < count) {
if (include(value, index)) {
return true;
}
}
}
}
else {
while (--count >= 0) {
if (include(value, count)) {
return true;
}
}
}
return false;
}
protected abstract boolean include(
Entry<? extends Object,? extends Object> value, int index);
}
private static class RegexFilter extends GeneralFilter {
private Matcher matcher;
RegexFilter(Pattern regex, int[] columns) {
super(columns);
if (regex == null) {
throw new IllegalArgumentException("Pattern must be non-null");
}
matcher = regex.matcher("");
}
protected boolean include(
Entry<? extends Object,? extends Object> value, int index) {
matcher.reset(value.getStringValue(index));
return matcher.find();
}
}
private static class DateFilter extends GeneralFilter {
private long date;
private ComparisonType type;
DateFilter(ComparisonType type, long date, int[] columns) {
super(columns);
if (type == null) {
throw new IllegalArgumentException("type must be non-null");
}
this.type = type;
this.date = date;
}
protected boolean include(
Entry<? extends Object,? extends Object> value, int index) {
Object v = value.getValue(index);
if (v instanceof Date) {
long vDate = ((Date)v).getTime();
switch(type) {
case BEFORE:
return (vDate < date);
case AFTER:
return (vDate > date);
case EQUAL:
return (vDate == date);
case NOT_EQUAL:
return (vDate != date);
default:
break;
}
}
return false;
}
}
private static class NumberFilter extends GeneralFilter {
private boolean isComparable;
private Number number;
private ComparisonType type;
NumberFilter(ComparisonType type, Number number, int[] columns) {
super(columns);
if (type == null || number == null) {
throw new IllegalArgumentException(
"type and number must be non-null");
}
this.type = type;
this.number = number;
isComparable = (number instanceof Comparable);
}
@SuppressWarnings("unchecked")
protected boolean include(
Entry<? extends Object,? extends Object> value, int index) {
Object v = value.getValue(index);
if (v instanceof Number) {
boolean compared = true;
int compareResult;
Class vClass = v.getClass();
if (number.getClass() == vClass && isComparable) {
compareResult = ((Comparable)number).compareTo(v);
}
else {
compareResult = longCompare((Number)v);
}
switch(type) {
case BEFORE:
return (compareResult > 0);
case AFTER:
return (compareResult < 0);
case EQUAL:
return (compareResult == 0);
case NOT_EQUAL:
return (compareResult != 0);
default:
break;
}
}
return false;
}
private int longCompare(Number o) {
long diff = number.longValue() - o.longValue();
if (diff < 0) {
return -1;
}
else if (diff > 0) {
return 1;
}
return 0;
}
}
private static class OrFilter<M,I> extends RowFilter<M,I> {
List<RowFilter<? super M,? super I>> filters;
OrFilter(Iterable<? extends RowFilter<? super M, ? super I>> filters) {
this.filters = new ArrayList<RowFilter<? super M,? super I>>();
for (RowFilter<? super M, ? super I> filter : filters) {
if (filter == null) {
throw new IllegalArgumentException(
"Filter must be non-null");
}
this.filters.add(filter);
}
}
public boolean include(Entry<? extends M, ? extends I> value) {
for (RowFilter<? super M,? super I> filter : filters) {
if (filter.include(value)) {
return true;
}
}
return false;
}
}
private static class AndFilter<M,I> extends OrFilter<M,I> {
AndFilter(Iterable<? extends RowFilter<? super M,? super I>> filters) {
super(filters);
}
public boolean include(Entry<? extends M, ? extends I> value) {
for (RowFilter<? super M,? super I> filter : filters) {
if (!filter.include(value)) {
return false;
}
}
return true;
}
}
private static class NotFilter<M,I> extends RowFilter<M,I> {
private RowFilter<M,I> filter;
NotFilter(RowFilter<M,I> filter) {
if (filter == null) {
throw new IllegalArgumentException(
"filter must be non-null");
}
this.filter = filter;
}
public boolean include(Entry<? extends M, ? extends I> value) {
return !filter.include(value);
}
}
}
|
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.Component;
import java.awt.Container;
import java.awt.ComponentOrientation;
import java.util.Comparator;
import java.io.*;
/** {@collect.stats}
* A SortingFocusTraversalPolicy which sorts Components based on their size,
* position, and orientation. Based on their size and position, Components are
* roughly categorized into rows and columns. For a Container with horizontal
* orientation, columns run left-to-right or right-to-left, and rows run top-
* to-bottom. For a Container with vertical orientation, columns run top-to-
* bottom and rows run left-to-right or right-to-left. See
* <code>ComponentOrientation</code> for more information. All columns in a
* row are fully traversed before proceeding to the next row.
*
* @author David Mendenhall
*
* @see java.awt.ComponentOrientation
* @since 1.4
*/
public class LayoutFocusTraversalPolicy extends SortingFocusTraversalPolicy
implements Serializable
{
// Delegate most of our fitness test to Default so that we only have to
// code the algorithm once.
private static final SwingDefaultFocusTraversalPolicy fitnessTestPolicy =
new SwingDefaultFocusTraversalPolicy();
/** {@collect.stats}
* Constructs a LayoutFocusTraversalPolicy.
*/
public LayoutFocusTraversalPolicy() {
super(new LayoutComparator());
}
/** {@collect.stats}
* Constructs a LayoutFocusTraversalPolicy with the passed in
* <code>Comparator</code>.
*/
LayoutFocusTraversalPolicy(Comparator c) {
super(c);
}
/** {@collect.stats}
* Returns the Component that should receive the focus after aComponent.
* aContainer must be a focus cycle root of aComponent.
* <p>
* By default, LayoutFocusTraversalPolicy implicitly transfers focus down-
* cycle. That is, during normal focus traversal, the Component
* traversed after a focus cycle root will be the focus-cycle-root's
* default Component to focus. This behavior can be disabled using the
* <code>setImplicitDownCycleTraversal</code> method.
* <p>
* If aContainer is <a href="../../java/awt/doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus
* traversal policy provider</a>, the focus is always transferred down-cycle.
*
* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider
* @param aComponent a (possibly indirect) child of aContainer, or
* aContainer itself
* @return the Component that should receive the focus after aComponent, or
* null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is not a focus cycle
* root of aComponent or a focus traversal policy provider, or if either aContainer or
* aComponent is null
*/
public Component getComponentAfter(Container aContainer,
Component aComponent) {
if (aContainer == null || aComponent == null) {
throw new IllegalArgumentException("aContainer and aComponent cannot be null");
}
Comparator comparator = getComparator();
if (comparator instanceof LayoutComparator) {
((LayoutComparator)comparator).
setComponentOrientation(aContainer.
getComponentOrientation());
}
return super.getComponentAfter(aContainer, aComponent);
}
/** {@collect.stats}
* Returns the Component that should receive the focus before aComponent.
* aContainer must be a focus cycle root of aComponent.
* <p>
* By default, LayoutFocusTraversalPolicy implicitly transfers focus down-
* cycle. That is, during normal focus traversal, the Component
* traversed after a focus cycle root will be the focus-cycle-root's
* default Component to focus. This behavior can be disabled using the
* <code>setImplicitDownCycleTraversal</code> method.
* <p>
* If aContainer is <a href="../../java/awt/doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus
* traversal policy provider</a>, the focus is always transferred down-cycle.
*
* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider
* @param aComponent a (possibly indirect) child of aContainer, or
* aContainer itself
* @return the Component that should receive the focus before aComponent,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is not a focus cycle
* root of aComponent or a focus traversal policy provider, or if either aContainer or
* aComponent is null
*/
public Component getComponentBefore(Container aContainer,
Component aComponent) {
if (aContainer == null || aComponent == null) {
throw new IllegalArgumentException("aContainer and aComponent cannot be null");
}
Comparator comparator = getComparator();
if (comparator instanceof LayoutComparator) {
((LayoutComparator)comparator).
setComponentOrientation(aContainer.
getComponentOrientation());
}
return super.getComponentBefore(aContainer, aComponent);
}
/** {@collect.stats}
* Returns the first Component in the traversal cycle. This method is used
* to determine the next Component to focus when traversal wraps in the
* forward direction.
*
* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider whose
* first Component is to be returned
* @return the first Component in the traversal cycle of aContainer,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is null
*/
public Component getFirstComponent(Container aContainer) {
if (aContainer == null) {
throw new IllegalArgumentException("aContainer cannot be null");
}
Comparator comparator = getComparator();
if (comparator instanceof LayoutComparator) {
((LayoutComparator)comparator).
setComponentOrientation(aContainer.
getComponentOrientation());
}
return super.getFirstComponent(aContainer);
}
/** {@collect.stats}
* Returns the last Component in the traversal cycle. This method is used
* to determine the next Component to focus when traversal wraps in the
* reverse direction.
*
* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider whose
* last Component is to be returned
* @return the last Component in the traversal cycle of aContainer,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is null
*/
public Component getLastComponent(Container aContainer) {
if (aContainer == null) {
throw new IllegalArgumentException("aContainer cannot be null");
}
Comparator comparator = getComparator();
if (comparator instanceof LayoutComparator) {
((LayoutComparator)comparator).
setComponentOrientation(aContainer.
getComponentOrientation());
}
return super.getLastComponent(aContainer);
}
/** {@collect.stats}
* Determines whether the specified <code>Component</code>
* is an acceptable choice as the new focus owner.
* This method performs the following sequence of operations:
* <ol>
* <li>Checks whether <code>aComponent</code> is visible, displayable,
* enabled, and focusable. If any of these properties is
* <code>false</code>, this method returns <code>false</code>.
* <li>If <code>aComponent</code> is an instance of <code>JTable</code>,
* returns <code>true</code>.
* <li>If <code>aComponent</code> is an instance of <code>JComboBox</code>,
* then returns the value of
* <code>aComponent.getUI().isFocusTraversable(aComponent)</code>.
* <li>If <code>aComponent</code> is a <code>JComponent</code>
* with a <code>JComponent.WHEN_FOCUSED</code>
* <code>InputMap</code> that is neither <code>null</code>
* nor empty, returns <code>true</code>.
* <li>Returns the value of
* <code>DefaultFocusTraversalPolicy.accept(aComponent)</code>.
* </ol>
*
* @param aComponent the <code>Component</code> whose fitness
* as a focus owner is to be tested
* @see java.awt.Component#isVisible
* @see java.awt.Component#isDisplayable
* @see java.awt.Component#isEnabled
* @see java.awt.Component#isFocusable
* @see javax.swing.plaf.ComboBoxUI#isFocusTraversable
* @see javax.swing.JComponent#getInputMap
* @see java.awt.DefaultFocusTraversalPolicy#accept
* @return <code>true</code> if <code>aComponent</code> is a valid choice
* for a focus owner;
* otherwise <code>false</code>
*/
protected boolean accept(Component aComponent) {
if (!super.accept(aComponent)) {
return false;
} else if (aComponent instanceof JTable) {
// JTable only has ancestor focus bindings, we thus force it
// to be focusable by returning true here.
return true;
} else if (aComponent instanceof JComboBox) {
JComboBox box = (JComboBox)aComponent;
return box.getUI().isFocusTraversable(box);
} else if (aComponent instanceof JComponent) {
JComponent jComponent = (JComponent)aComponent;
InputMap inputMap = jComponent.getInputMap(JComponent.WHEN_FOCUSED,
false);
while (inputMap != null && inputMap.size() == 0) {
inputMap = inputMap.getParent();
}
if (inputMap != null) {
return true;
}
// Delegate to the fitnessTestPolicy, this will test for the
// case where the developer has overriden isFocusTraversable to
// return true.
}
return fitnessTestPolicy.accept(aComponent);
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(getComparator());
out.writeBoolean(getImplicitDownCycleTraversal());
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
setComparator((Comparator)in.readObject());
setImplicitDownCycleTraversal(in.readBoolean());
}
}
// Create our own subclass and change accept to public so that we can call
// accept.
class SwingDefaultFocusTraversalPolicy
extends java.awt.DefaultFocusTraversalPolicy
{
public boolean accept(Component aComponent) {
return super.accept(aComponent);
}
}
|
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;
/** {@collect.stats}
* An enumeration for keys used as client properties within the Swing
* implementation.
* <p>
* This enum holds only a small subset of the keys currently used within Swing,
* but we may move more of them here in the future.
* <p>
* Adding an item to, and using, this class instead of {@code String} for
* client properties protects against conflicts with developer-set client
* properties. Using this class also avoids a problem with {@code StringBuilder}
* and {@code StringBuffer} keys, whereby the keys are not recognized upon
* deserialization.
* <p>
* When a client property value associated with one of these keys does not
* implement {@code Serializable}, the result during serialization depends
* on how the key is defined here. Historically, client properties with values
* not implementing {@code Serializable} have simply been dropped and left out
* of the serialized representation. To define keys with such behavior in this
* enum, provide a value of {@code false} for the {@code reportValueNotSerializable}
* property. When migrating existing properties to this enum, one may wish to
* consider using this by default, to preserve backward compatibility.
* <p>
* To instead have a {@code NotSerializableException} thrown when a
* {@code non-Serializable} property is encountered, provide the value of
* {@code true} for the {@code reportValueNotSerializable} property. This
* is useful when the property represents something that the developer
* needs to know about when it cannot be serialized.
*
* @author Shannon Hickey
*/
enum ClientPropertyKey {
/** {@collect.stats}
* Key used by JComponent for storing InputVerifier.
*/
JComponent_INPUT_VERIFIER(true),
/** {@collect.stats}
* Key used by JComponent for storing TransferHandler.
*/
JComponent_TRANSFER_HANDLER(true),
/** {@collect.stats}
* Key used by JComponent for storing AncestorNotifier.
*/
JComponent_ANCESTOR_NOTIFIER(true),
/** {@collect.stats}
* Key used by PopupFactory to force heavy weight popups for a
* component.
*/
PopupFactory_FORCE_HEAVYWEIGHT_POPUP(true);
/** {@collect.stats}
* Whether or not a {@code NotSerializableException} should be thrown
* during serialization, when the value associated with this key does
* not implement {@code Serializable}.
*/
private final boolean reportValueNotSerializable;
/** {@collect.stats}
* Constructs a key with the {@code reportValueNotSerializable} property
* set to {@code false}.
*/
private ClientPropertyKey() {
this(false);
}
/** {@collect.stats}
* Constructs a key with the {@code reportValueNotSerializable} property
* set to the given value.
*/
private ClientPropertyKey(boolean reportValueNotSerializable) {
this.reportValueNotSerializable = reportValueNotSerializable;
}
/** {@collect.stats}
* Returns whether or not a {@code NotSerializableException} should be thrown
* during serialization, when the value associated with this key does
* not implement {@code Serializable}.
*/
public boolean getReportValueNotSerializable() {
return reportValueNotSerializable;
}
}
|
Java
|
/*
* Copyright (c) 2001, 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;
import java.awt.Component;
/** {@collect.stats}
* An instance of the <code>Spring</code> class holds three properties that
* characterize its behavior: the <em>minimum</em>, <em>preferred</em>, and
* <em>maximum</em> values. Each of these properties may be involved in
* defining its fourth, <em>value</em>, property based on a series of rules.
* <p>
* An instance of the <code>Spring</code> class can be visualized as a
* mechanical spring that provides a corrective force as the spring is compressed
* or stretched away from its preferred value. This force is modelled
* as linear function of the distance from the preferred value, but with
* two different constants -- one for the compressional force and one for the
* tensional one. Those constants are specified by the minimum and maximum
* values of the spring such that a spring at its minimum value produces an
* equal and opposite force to that which is created when it is at its
* maximum value. The difference between the <em>preferred</em> and
* <em>minimum</em> values, therefore, represents the ease with which the
* spring can be compressed and the difference between its <em>maximum</em>
* and <em>preferred</em> values, indicates the ease with which the
* <code>Spring</code> can be extended.
* See the {@link #sum} method for details.
*
* <p>
* By defining simple arithmetic operations on <code>Spring</code>s,
* the behavior of a collection of <code>Spring</code>s
* can be reduced to that of an ordinary (non-compound) <code>Spring</code>. We define
* the "+", "-", <em>max</em>, and <em>min</em> operators on
* <code>Spring</code>s so that, in each case, the result is a <code>Spring</code>
* whose characteristics bear a useful mathematical relationship to its constituent
* springs.
*
* <p>
* A <code>Spring</code> can be treated as a pair of intervals
* with a single common point: the preferred value.
* The following rules define some of the
* arithmetic operators that can be applied to intervals
* (<code>[a, b]</code> refers to the interval
* from <code>a</code>
* to <code>b</code>,
* where <code>a <= b</code>).
* <p>
* <pre>
* [a1, b1] + [a2, b2] = [a1 + a2, b1 + b2]
*
* -[a, b] = [-b, -a]
*
* max([a1, b1], [a2, b2]) = [max(a1, a2), max(b1, b2)]
* </pre>
* <p>
*
* If we denote <code>Spring</code>s as <code>[a, b, c]</code>,
* where <code>a <= b <= c</code>, we can define the same
* arithmetic operators on <code>Spring</code>s:
* <p>
* <pre>
* [a1, b1, c1] + [a2, b2, c2] = [a1 + a2, b1 + b2, c1 + c2]
*
* -[a, b, c] = [-c, -b, -a]
*
* max([a1, b1, c1], [a2, b2, c2]) = [max(a1, a2), max(b1, b2), max(c1, c2)]
* </pre>
* <p>
* With both intervals and <code>Spring</code>s we can define "-" and <em>min</em>
* in terms of negation:
* <p>
* <pre>
* X - Y = X + (-Y)
*
* min(X, Y) = -max(-X, -Y)
* </pre>
* <p>
* For the static methods in this class that embody the arithmetic
* operators, we do not actually perform the operation in question as
* that would snapshot the values of the properties of the method's arguments
* at the time the static method is called. Instead, the static methods
* create a new <code>Spring</code> instance containing references to
* the method's arguments so that the characteristics of the new spring track the
* potentially changing characteristics of the springs from which it
* was made. This is a little like the idea of a <em>lazy value</em>
* in a functional language.
* <p>
* If you are implementing a <code>SpringLayout</code> you
* can find further information and examples in
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/layout/spring.html">How to Use SpringLayout</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 SpringLayout
* @see SpringLayout.Constraints
*
* @author Philip Milne
* @since 1.4
*/
public abstract class Spring {
/** {@collect.stats}
* An integer value signifying that a property value has not yet been calculated.
*/
public static final int UNSET = Integer.MIN_VALUE;
/** {@collect.stats}
* Used by factory methods to create a <code>Spring</code>.
*
* @see #constant(int)
* @see #constant(int, int, int)
* @see #max
* @see #minus
* @see #sum
* @see SpringLayout.Constraints
*/
protected Spring() {}
/** {@collect.stats}
* Returns the <em>minimum</em> value of this <code>Spring</code>.
*
* @return the <code>minimumValue</code> property of this <code>Spring</code>
*/
public abstract int getMinimumValue();
/** {@collect.stats}
* Returns the <em>preferred</em> value of this <code>Spring</code>.
*
* @return the <code>preferredValue</code> of this <code>Spring</code>
*/
public abstract int getPreferredValue();
/** {@collect.stats}
* Returns the <em>maximum</em> value of this <code>Spring</code>.
*
* @return the <code>maximumValue</code> property of this <code>Spring</code>
*/
public abstract int getMaximumValue();
/** {@collect.stats}
* Returns the current <em>value</em> of this <code>Spring</code>.
*
* @return the <code>value</code> property of this <code>Spring</code>
*
* @see #setValue
*/
public abstract int getValue();
/** {@collect.stats}
* Sets the current <em>value</em> of this <code>Spring</code> to <code>value</code>.
*
* @param value the new setting of the <code>value</code> property
*
* @see #getValue
*/
public abstract void setValue(int value);
private double range(boolean contract) {
return contract ? (getPreferredValue() - getMinimumValue()) :
(getMaximumValue() - getPreferredValue());
}
/*pp*/ double getStrain() {
double delta = (getValue() - getPreferredValue());
return delta/range(getValue() < getPreferredValue());
}
/*pp*/ void setStrain(double strain) {
setValue(getPreferredValue() + (int)(strain * range(strain < 0)));
}
/*pp*/ boolean isCyclic(SpringLayout l) {
return false;
}
/*pp*/ static abstract class AbstractSpring extends Spring {
protected int size = UNSET;
public int getValue() {
return size != UNSET ? size : getPreferredValue();
}
public final void setValue(int size) {
if (this.size == size) {
return;
}
if (size == UNSET) {
clear();
} else {
setNonClearValue(size);
}
}
protected void clear() {
size = UNSET;
}
protected void setNonClearValue(int size) {
this.size = size;
}
}
private static class StaticSpring extends AbstractSpring {
protected int min;
protected int pref;
protected int max;
public StaticSpring(int pref) {
this(pref, pref, pref);
}
public StaticSpring(int min, int pref, int max) {
this.min = min;
this.pref = pref;
this.max = max;
}
public String toString() {
return "StaticSpring [" + min + ", " + pref + ", " + max + "]";
}
public int getMinimumValue() {
return min;
}
public int getPreferredValue() {
return pref;
}
public int getMaximumValue() {
return max;
}
}
private static class NegativeSpring extends Spring {
private Spring s;
public NegativeSpring(Spring s) {
this.s = s;
}
// Note the use of max value rather than minimum value here.
// See the opening preamble on arithmetic with springs.
public int getMinimumValue() {
return -s.getMaximumValue();
}
public int getPreferredValue() {
return -s.getPreferredValue();
}
public int getMaximumValue() {
return -s.getMinimumValue();
}
public int getValue() {
return -s.getValue();
}
public void setValue(int size) {
// No need to check for UNSET as
// Integer.MIN_VALUE == -Integer.MIN_VALUE.
s.setValue(-size);
}
/*pp*/ boolean isCyclic(SpringLayout l) {
return s.isCyclic(l);
}
}
private static class ScaleSpring extends Spring {
private Spring s;
private float factor;
private ScaleSpring(Spring s, float factor) {
this.s = s;
this.factor = factor;
}
public int getMinimumValue() {
return Math.round((factor < 0 ? s.getMaximumValue() : s.getMinimumValue()) * factor);
}
public int getPreferredValue() {
return Math.round(s.getPreferredValue() * factor);
}
public int getMaximumValue() {
return Math.round((factor < 0 ? s.getMinimumValue() : s.getMaximumValue()) * factor);
}
public int getValue() {
return Math.round(s.getValue() * factor);
}
public void setValue(int value) {
if (value == UNSET) {
s.setValue(UNSET);
} else {
s.setValue(Math.round(value / factor));
}
}
/*pp*/ boolean isCyclic(SpringLayout l) {
return s.isCyclic(l);
}
}
/*pp*/ static class WidthSpring extends AbstractSpring {
/*pp*/ Component c;
public WidthSpring(Component c) {
this.c = c;
}
public int getMinimumValue() {
return c.getMinimumSize().width;
}
public int getPreferredValue() {
return c.getPreferredSize().width;
}
public int getMaximumValue() {
// We will be doing arithmetic with the results of this call,
// so if a returned value is Integer.MAX_VALUE we will get
// arithmetic overflow. Truncate such values.
return Math.min(Short.MAX_VALUE, c.getMaximumSize().width);
}
}
/*pp*/ static class HeightSpring extends AbstractSpring {
/*pp*/ Component c;
public HeightSpring(Component c) {
this.c = c;
}
public int getMinimumValue() {
return c.getMinimumSize().height;
}
public int getPreferredValue() {
return c.getPreferredSize().height;
}
public int getMaximumValue() {
return Math.min(Short.MAX_VALUE, c.getMaximumSize().height);
}
}
/*pp*/ static abstract class SpringMap extends Spring {
private Spring s;
public SpringMap(Spring s) {
this.s = s;
}
protected abstract int map(int i);
protected abstract int inv(int i);
public int getMinimumValue() {
return map(s.getMinimumValue());
}
public int getPreferredValue() {
return map(s.getPreferredValue());
}
public int getMaximumValue() {
return Math.min(Short.MAX_VALUE, map(s.getMaximumValue()));
}
public int getValue() {
return map(s.getValue());
}
public void setValue(int value) {
if (value == UNSET) {
s.setValue(UNSET);
} else {
s.setValue(inv(value));
}
}
/*pp*/ boolean isCyclic(SpringLayout l) {
return s.isCyclic(l);
}
}
// Use the instance variables of the StaticSpring superclass to
// cache values that have already been calculated.
/*pp*/ static abstract class CompoundSpring extends StaticSpring {
protected Spring s1;
protected Spring s2;
public CompoundSpring(Spring s1, Spring s2) {
super(UNSET);
this.s1 = s1;
this.s2 = s2;
}
public String toString() {
return "CompoundSpring of " + s1 + " and " + s2;
}
protected void clear() {
super.clear();
min = pref = max = UNSET;
s1.setValue(UNSET);
s2.setValue(UNSET);
}
protected abstract int op(int x, int y);
public int getMinimumValue() {
if (min == UNSET) {
min = op(s1.getMinimumValue(), s2.getMinimumValue());
}
return min;
}
public int getPreferredValue() {
if (pref == UNSET) {
pref = op(s1.getPreferredValue(), s2.getPreferredValue());
}
return pref;
}
public int getMaximumValue() {
if (max == UNSET) {
max = op(s1.getMaximumValue(), s2.getMaximumValue());
}
return max;
}
public int getValue() {
if (size == UNSET) {
size = op(s1.getValue(), s2.getValue());
}
return size;
}
/*pp*/ boolean isCyclic(SpringLayout l) {
return l.isCyclic(s1) || l.isCyclic(s2);
}
};
private static class SumSpring extends CompoundSpring {
public SumSpring(Spring s1, Spring s2) {
super(s1, s2);
}
protected int op(int x, int y) {
return x + y;
}
protected void setNonClearValue(int size) {
super.setNonClearValue(size);
s1.setStrain(this.getStrain());
s2.setValue(size - s1.getValue());
}
}
private static class MaxSpring extends CompoundSpring {
public MaxSpring(Spring s1, Spring s2) {
super(s1, s2);
}
protected int op(int x, int y) {
return Math.max(x, y);
}
protected void setNonClearValue(int size) {
super.setNonClearValue(size);
s1.setValue(size);
s2.setValue(size);
}
}
/** {@collect.stats}
* Returns a strut -- a spring whose <em>minimum</em>, <em>preferred</em>, and
* <em>maximum</em> values each have the value <code>pref</code>.
*
* @param pref the <em>minimum</em>, <em>preferred</em>, and
* <em>maximum</em> values of the new spring
* @return a spring whose <em>minimum</em>, <em>preferred</em>, and
* <em>maximum</em> values each have the value <code>pref</code>
*
* @see Spring
*/
public static Spring constant(int pref) {
return constant(pref, pref, pref);
}
/** {@collect.stats}
* Returns a spring whose <em>minimum</em>, <em>preferred</em>, and
* <em>maximum</em> values have the values: <code>min</code>, <code>pref</code>,
* and <code>max</code> respectively.
*
* @param min the <em>minimum</em> value of the new spring
* @param pref the <em>preferred</em> value of the new spring
* @param max the <em>maximum</em> value of the new spring
* @return a spring whose <em>minimum</em>, <em>preferred</em>, and
* <em>maximum</em> values have the values: <code>min</code>, <code>pref</code>,
* and <code>max</code> respectively
*
* @see Spring
*/
public static Spring constant(int min, int pref, int max) {
return new StaticSpring(min, pref, max);
}
/** {@collect.stats}
* Returns <code>-s</code>: a spring running in the opposite direction to <code>s</code>.
*
* @return <code>-s</code>: a spring running in the opposite direction to <code>s</code>
*
* @see Spring
*/
public static Spring minus(Spring s) {
return new NegativeSpring(s);
}
/** {@collect.stats}
* Returns <code>s1+s2</code>: a spring representing <code>s1</code> and <code>s2</code>
* in series. In a sum, <code>s3</code>, of two springs, <code>s1</code> and <code>s2</code>,
* the <em>strains</em> of <code>s1</code>, <code>s2</code>, and <code>s3</code> are maintained
* at the same level (to within the precision implied by their integer <em>value</em>s).
* The strain of a spring in compression is:
* <pre>
* value - pref
* ------------
* pref - min
* </pre>
* and the strain of a spring in tension is:
* <pre>
* value - pref
* ------------
* max - pref
* </pre>
* When <code>setValue</code> is called on the sum spring, <code>s3</code>, the strain
* in <code>s3</code> is calculated using one of the formulas above. Once the strain of
* the sum is known, the <em>value</em>s of <code>s1</code> and <code>s2</code> are
* then set so that they are have a strain equal to that of the sum. The formulas are
* evaluated so as to take rounding errors into account and ensure that the sum of
* the <em>value</em>s of <code>s1</code> and <code>s2</code> is exactly equal to
* the <em>value</em> of <code>s3</code>.
*
* @return <code>s1+s2</code>: a spring representing <code>s1</code> and <code>s2</code> in series
*
* @see Spring
*/
public static Spring sum(Spring s1, Spring s2) {
return new SumSpring(s1, s2);
}
/** {@collect.stats}
* Returns <code>max(s1, s2)</code>: a spring whose value is always greater than (or equal to)
* the values of both <code>s1</code> and <code>s2</code>.
*
* @return <code>max(s1, s2)</code>: a spring whose value is always greater than (or equal to)
* the values of both <code>s1</code> and <code>s2</code>
* @see Spring
*/
public static Spring max(Spring s1, Spring s2) {
return new MaxSpring(s1, s2);
}
// Remove these, they're not used often and can be created using minus -
// as per these implementations.
/*pp*/ static Spring difference(Spring s1, Spring s2) {
return sum(s1, minus(s2));
}
/*
public static Spring min(Spring s1, Spring s2) {
return minus(max(minus(s1), minus(s2)));
}
*/
/** {@collect.stats}
* Returns a spring whose <em>minimum</em>, <em>preferred</em>, <em>maximum</em>
* and <em>value</em> properties are each multiples of the properties of the
* argument spring, <code>s</code>. Minimum and maximum properties are
* swapped when <code>factor</code> is negative (in accordance with the
* rules of interval arithmetic).
* <p>
* When factor is, for example, 0.5f the result represents 'the mid-point'
* of its input - an operation that is useful for centering components in
* a container.
*
* @param s the spring to scale
* @param factor amount to scale by.
* @return a spring whose properties are those of the input spring <code>s</code>
* multiplied by <code>factor</code>
* @throws NullPointerException if <code>s</code> is null
* @since 1.5
*/
public static Spring scale(Spring s, float factor) {
checkArg(s);
return new ScaleSpring(s, factor);
}
/** {@collect.stats}
* Returns a spring whose <em>minimum</em>, <em>preferred</em>, <em>maximum</em>
* and <em>value</em> properties are defined by the widths of the <em>minimumSize</em>,
* <em>preferredSize</em>, <em>maximumSize</em> and <em>size</em> properties
* of the supplied component. The returned spring is a 'wrapper' implementation
* whose methods call the appropriate size methods of the supplied component.
* The minimum, preferred, maximum and value properties of the returned spring
* therefore report the current state of the appropriate properties in the
* component and track them as they change.
*
* @param c Component used for calculating size
* @return a spring whose properties are defined by the horizontal component
* of the component's size methods.
* @throws NullPointerException if <code>c</code> is null
* @since 1.5
*/
public static Spring width(Component c) {
checkArg(c);
return new WidthSpring(c);
}
/** {@collect.stats}
* Returns a spring whose <em>minimum</em>, <em>preferred</em>, <em>maximum</em>
* and <em>value</em> properties are defined by the heights of the <em>minimumSize</em>,
* <em>preferredSize</em>, <em>maximumSize</em> and <em>size</em> properties
* of the supplied component. The returned spring is a 'wrapper' implementation
* whose methods call the appropriate size methods of the supplied component.
* The minimum, preferred, maximum and value properties of the returned spring
* therefore report the current state of the appropriate properties in the
* component and track them as they change.
*
* @param c Component used for calculating size
* @return a spring whose properties are defined by the vertical component
* of the component's size methods.
* @throws NullPointerException if <code>c</code> is null
* @since 1.5
*/
public static Spring height(Component c) {
checkArg(c);
return new HeightSpring(c);
}
/** {@collect.stats}
* If <code>s</code> is null, this throws an NullPointerException.
*/
private static void checkArg(Object s) {
if (s == null) {
throw new NullPointerException("Argument must not be null");
}
}
}
|
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 javax.swing.SortOrder;
import javax.swing.event.*;
import java.util.*;
/** {@collect.stats}
* <code>RowSorter</code> provides the basis for sorting and filtering.
* Beyond creating and installing a <code>RowSorter</code>, you very rarely
* need to interact with one directly. Refer to
* {@link javax.swing.table.TableRowSorter TableRowSorter} for a concrete
* implementation of <code>RowSorter</code> for <code>JTable</code>.
* <p>
* <code>RowSorter</code>'s primary role is to provide a mapping between
* two coordinate systems: that of the view (for example a
* <code>JTable</code>) and that of the underlying data source, typically a
* model.
* <p>
* The view invokes the following methods on the <code>RowSorter</code>:
* <ul>
* <li><code>toggleSortOrder</code> — The view invokes this when the
* appropriate user gesture has occurred to trigger a sort. For example,
* the user clicked a column header in a table.
* <li>One of the model change methods — The view invokes a model
* change method when the underlying model
* has changed. There may be order dependencies in how the events are
* delivered, so a <code>RowSorter</code> should not update its mapping
* until one of these methods is invoked.
* </ul>
* Because the view makes extensive use of the
* <code>convertRowIndexToModel</code>,
* <code>convertRowIndexToView</code> and <code>getViewRowCount</code> methods,
* these methods need to be fast.
* <p>
* <code>RowSorter</code> provides notification of changes by way of
* <code>RowSorterListener</code>. Two types of notification are sent:
* <ul>
* <li><code>RowSorterEvent.Type.SORT_ORDER_CHANGED</code> — notifies
* listeners that the sort order has changed. This is typically followed
* by a notification that the sort has changed.
* <li><code>RowSorterEvent.Type.SORTED</code> — notifies listeners that
* the mapping maintained by the <code>RowSorter</code> has changed in
* some way.
* </ul>
* <code>RowSorter</code> implementations typically don't have a one-to-one
* mapping with the underlying model, but they can.
* For example, if a database does the sorting,
* <code>toggleSortOrder</code> might call through to the database
* (on a background thread), and override the mapping methods to return the
* argument that is passed in.
* <p>
* Concrete implementations of <code>RowSorter</code>
* need to reference a model such as <code>TableModel</code> or
* <code>ListModel</code>. The view classes, such as
* <code>JTable</code> and <code>JList</code>, will also have a
* reference to the model. To avoid ordering dependencies,
* <code>RowSorter</code> implementations should not install a
* listener on the model. Instead the view class will call into the
* <code>RowSorter</code> when the model changes. For
* example, if a row is updated in a <code>TableModel</code>
* <code>JTable</code> invokes <code>rowsUpdated</code>.
* When the model changes, the view may call into any of the following methods:
* <code>modelStructureChanged</code>, <code>allRowsChanged</code>,
* <code>rowsInserted</code>, <code>rowsDeleted</code> and
* <code>rowsUpdated</code>.
*
* @param <M> the type of the underlying model
* @see javax.swing.table.TableRowSorter
* @since 1.6
*/
public abstract class RowSorter<M> {
private EventListenerList listenerList = new EventListenerList();
/** {@collect.stats}
* Creates a <code>RowSorter</code>.
*/
public RowSorter() {
}
/** {@collect.stats}
* Returns the underlying model.
*
* @return the underlying model
*/
public abstract M getModel();
/** {@collect.stats}
* Reverses the sort order of the specified column. It is up to
* subclasses to provide the exact behavior when invoked. Typically
* this will reverse the sort order from ascending to descending (or
* descending to ascending) if the specified column is already the
* primary sorted column; otherwise, makes the specified column
* the primary sorted column, with an ascending sort order. If
* the specified column is not sortable, this method has no
* effect.
* <p>
* If this results in changing the sort order and sorting, the
* appropriate <code>RowSorterListener</code> notification will be
* sent.
*
* @param column the column to toggle the sort ordering of, in
* terms of the underlying model
* @throws IndexOutOfBoundsException if column is outside the range of
* the underlying model
*/
public abstract void toggleSortOrder(int column);
/** {@collect.stats}
* Returns the location of <code>index</code> in terms of the
* underlying model. That is, for the row <code>index</code> in
* the coordinates of the view this returns the row index in terms
* of the underlying model.
*
* @param index the row index in terms of the underlying view
* @return row index in terms of the view
* @throws IndexOutOfBoundsException if <code>index</code> is outside the
* range of the view
*/
public abstract int convertRowIndexToModel(int index);
/** {@collect.stats}
* Returns the location of <code>index</code> in terms of the
* view. That is, for the row <code>index</code> in the
* coordinates of the underlying model this returns the row index
* in terms of the view.
*
* @param index the row index in terms of the underlying model
* @return row index in terms of the view, or -1 if index has been
* filtered out of the view
* @throws IndexOutOfBoundsException if <code>index</code> is outside
* the range of the model
*/
public abstract int convertRowIndexToView(int index);
/** {@collect.stats}
* Sets the current sort keys.
*
* @param keys the new <code>SortKeys</code>; <code>null</code>
* is a shorthand for specifying an empty list,
* indicating that the view should be unsorted
*/
public abstract void setSortKeys(List<? extends SortKey> keys);
/** {@collect.stats}
* Returns the current sort keys. This must return a {@code
* non-null List} and may return an unmodifiable {@code List}. If
* you need to change the sort keys, make a copy of the returned
* {@code List}, mutate the copy and invoke {@code setSortKeys}
* with the new list.
*
* @return the current sort order
*/
public abstract List<? extends SortKey> getSortKeys();
/** {@collect.stats}
* Returns the number of rows in the view. If the contents have
* been filtered this might differ from the row count of the
* underlying model.
*
* @return number of rows in the view
* @see #getModelRowCount
*/
public abstract int getViewRowCount();
/** {@collect.stats}
* Returns the number of rows in the underlying model.
*
* @return number of rows in the underlying model
* @see #getViewRowCount
*/
public abstract int getModelRowCount();
/** {@collect.stats}
* Invoked when the underlying model structure has completely
* changed. For example, if the number of columns in a
* <code>TableModel</code> changed, this method would be invoked.
* <p>
* You normally do not call this method. This method is public
* to allow view classes to call it.
*/
public abstract void modelStructureChanged();
/** {@collect.stats}
* Invoked when the contents of the underlying model have
* completely changed. The structure of the table is the same,
* only the contents have changed. This is typically sent when it
* is too expensive to characterize the change in terms of the
* other methods.
* <p>
* You normally do not call this method. This method is public
* to allow view classes to call it.
*/
public abstract void allRowsChanged();
/** {@collect.stats}
* Invoked when rows have been inserted into the underlying model
* in the specified range (inclusive).
* <p>
* The arguments give the indices of the effected range.
* The first argument is in terms of the model before the change, and
* must be less than or equal to the size of the model before the change.
* The second argument is in terms of the model after the change and must
* be less than the size of the model after the change. For example,
* if you have a 5-row model and add 3 items to the end of the model
* the indices are 5, 7.
* <p>
* You normally do not call this method. This method is public
* to allow view classes to call it.
*
* @param firstRow the first row
* @param endRow the last row
* @throws IndexOutOfBoundsException if either argument is invalid, or
* <code>firstRow</code> > <code>endRow</code>
*/
public abstract void rowsInserted(int firstRow, int endRow);
/** {@collect.stats}
* Invoked when rows have been deleted from the underlying model
* in the specified range (inclusive).
* <p>
* The arguments give the indices of the effected range and
* are in terms of the model <b>before</b> the change.
* For example, if you have a 5-row model and delete 3 items from the end
* of the model the indices are 2, 4.
* <p>
* You normally do not call this method. This method is public
* to allow view classes to call it.
*
* @param firstRow the first row
* @param endRow the last row
* @throws IndexOutOfBoundsException if either argument is outside
* the range of the model before the change, or
* <code>firstRow</code> > <code>endRow</code>
*/
public abstract void rowsDeleted(int firstRow, int endRow);
/** {@collect.stats}
* Invoked when rows have been changed in the underlying model
* between the specified range (inclusive).
* <p>
* You normally do not call this method. This method is public
* to allow view classes to call it.
*
* @param firstRow the first row, in terms of the underlying model
* @param endRow the last row, in terms of the underlying model
* @throws IndexOutOfBoundsException if either argument is outside
* the range of the underlying model, or
* <code>firstRow</code> > <code>endRow</code>
*/
public abstract void rowsUpdated(int firstRow, int endRow);
/** {@collect.stats}
* Invoked when the column in the rows have been updated in
* the underlying model between the specified range.
* <p>
* You normally do not call this method. This method is public
* to allow view classes to call it.
*
* @param firstRow the first row, in terms of the underlying model
* @param endRow the last row, in terms of the underlying model
* @param column the column that has changed, in terms of the underlying
* model
* @throws IndexOutOfBoundsException if either argument is outside
* the range of the underlying model after the change,
* <code>firstRow</code> > <code>endRow</code>, or
* <code>column</code> is outside the range of the underlying
* model
*/
public abstract void rowsUpdated(int firstRow, int endRow, int column);
/** {@collect.stats}
* Adds a <code>RowSorterListener</code> to receive notification
* about this <code>RowSorter</code>. If the same
* listener is added more than once it will receive multiple
* notifications. If <code>l</code> is <code>null</code> nothing
* is done.
*
* @param l the <code>RowSorterListener</code>
*/
public void addRowSorterListener(RowSorterListener l) {
listenerList.add(RowSorterListener.class, l);
}
/** {@collect.stats}
* Removes a <code>RowSorterListener</code>. If
* <code>l</code> is <code>null</code> nothing is done.
*
* @param l the <code>RowSorterListener</code>
*/
public void removeRowSorterListener(RowSorterListener l) {
listenerList.remove(RowSorterListener.class, l);
}
/** {@collect.stats}
* Notifies listener that the sort order has changed.
*/
protected void fireSortOrderChanged() {
fireRowSorterChanged(new RowSorterEvent(this));
}
/** {@collect.stats}
* Notifies listener that the mapping has changed.
*
* @param lastRowIndexToModel the mapping from model indices to
* view indices prior to the sort, may be <code>null</code>
*/
protected void fireRowSorterChanged(int[] lastRowIndexToModel) {
fireRowSorterChanged(new RowSorterEvent(this,
RowSorterEvent.Type.SORTED, lastRowIndexToModel));
}
void fireRowSorterChanged(RowSorterEvent event) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == RowSorterListener.class) {
((RowSorterListener)listeners[i + 1]).
sorterChanged(event);
}
}
}
/** {@collect.stats}
* SortKey describes the sort order for a particular column. The
* column index is in terms of the underlying model, which may differ
* from that of the view.
*
* @since 1.6
*/
public static class SortKey {
private int column;
private SortOrder sortOrder;
/** {@collect.stats}
* Creates a <code>SortKey</code> for the specified column with
* the specified sort order.
*
* @param column index of the column, in terms of the model
* @param sortOrder the sorter order
* @throws IllegalArgumentException if <code>sortOrder</code> is
* <code>null</code>
*/
public SortKey(int column, SortOrder sortOrder) {
if (sortOrder == null) {
throw new IllegalArgumentException(
"sort order must be non-null");
}
this.column = column;
this.sortOrder = sortOrder;
}
/** {@collect.stats}
* Returns the index of the column.
*
* @return index of column
*/
public final int getColumn() {
return column;
}
/** {@collect.stats}
* Returns the sort order of the column.
*
* @return the sort order of the column
*/
public final SortOrder getSortOrder() {
return sortOrder;
}
/** {@collect.stats}
* Returns the hash code for this <code>SortKey</code>.
*
* @return hash code
*/
public int hashCode() {
int result = 17;
result = 37 * result + column;
result = 37 * result + sortOrder.hashCode();
return result;
}
/** {@collect.stats}
* Returns true if this object equals the specified object.
* If the specified object is a <code>SortKey</code> and
* references the same column and sort order, the two objects
* are equal.
*
* @param o the object to compare to
* @return true if <code>o</code> is equal to this <code>SortKey</code>
*/
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof SortKey) {
return (((SortKey)o).column == column &&
((SortKey)o).sortOrder == sortOrder);
}
return false;
}
}
}
|
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;
import java.io.PrintStream;
/** {@collect.stats}
* A layout manager that allows multiple components to be laid out either
* vertically or horizontally. The components will not wrap so, for
* example, a vertical arrangement of components will stay vertically
* arranged when the frame is resized.
* <TABLE ALIGN="RIGHT" BORDER="0" SUMMARY="layout">
* <TR>
* <TD ALIGN="CENTER">
* <P ALIGN="CENTER"><IMG SRC="doc-files/BoxLayout-1.gif"
* alt="The following text describes this graphic."
* WIDTH="191" HEIGHT="201" ALIGN="BOTTOM" BORDER="0">
* </TD>
* </TR>
* </TABLE>
* <p>
* Nesting multiple panels with different combinations of horizontal and
* vertical gives an effect similar to GridBagLayout, without the
* complexity. The diagram shows two panels arranged horizontally, each
* of which contains 3 components arranged vertically.
*
* <p> The BoxLayout manager is constructed with an axis parameter that
* specifies the type of layout that will be done. There are four choices:
*
* <blockquote><b><tt>X_AXIS</tt></b> - Components are laid out horizontally
* from left to right.</blockquote>
*
* <blockquote><b><tt>Y_AXIS</tt></b> - Components are laid out vertically
* from top to bottom.</blockquote>
*
* <blockquote><b><tt>LINE_AXIS</tt></b> - Components are laid out the way
* words are laid out in a line, based on the container's
* <tt>ComponentOrientation</tt> property. If the container's
* <tt>ComponentOrientation</tt> is horizontal then components are laid out
* horizontally, otherwise they are laid out vertically. For horizontal
* orientations, if the container's <tt>ComponentOrientation</tt> is left to
* right then components are laid out left to right, otherwise they are laid
* out right to left. For vertical orientations components are always laid out
* from top to bottom.</blockquote>
*
* <blockquote><b><tt>PAGE_AXIS</tt></b> - Components are laid out the way
* text lines are laid out on a page, based on the container's
* <tt>ComponentOrientation</tt> property. If the container's
* <tt>ComponentOrientation</tt> is horizontal then components are laid out
* vertically, otherwise they are laid out horizontally. For horizontal
* orientations, if the container's <tt>ComponentOrientation</tt> is left to
* right then components are laid out left to right, otherwise they are laid
* out right to left. For vertical orientations components are always
* laid out from top to bottom.</blockquote>
* <p>
* For all directions, components are arranged in the same order as they were
* added to the container.
* <p>
* BoxLayout attempts to arrange components
* at their preferred widths (for horizontal layout)
* or heights (for vertical layout).
* For a horizontal layout,
* if not all the components are the same height,
* BoxLayout attempts to make all the components
* as high as the highest component.
* If that's not possible for a particular component,
* then BoxLayout aligns that component vertically,
* according to the component's Y alignment.
* By default, a component has a Y alignment of 0.5,
* which means that the vertical center of the component
* should have the same Y coordinate as
* the vertical centers of other components with 0.5 Y alignment.
* <p>
* Similarly, for a vertical layout,
* BoxLayout attempts to make all components in the column
* as wide as the widest component.
* If that fails, it aligns them horizontally
* according to their X alignments. For <code>PAGE_AXIS</code> layout,
* horizontal alignment is done based on the leading edge of the component.
* In other words, an X alignment value of 0.0 means the left edge of a
* component if the container's <code>ComponentOrientation</code> is left to
* right and it means the right edge of the component otherwise.
* <p>
* Instead of using BoxLayout directly, many programs use the Box class.
* The Box class is a lightweight container that uses a BoxLayout.
* It also provides handy methods to help you use BoxLayout well.
* Adding components to multiple nested boxes is a powerful way to get
* the arrangement you want.
* <p>
* For further information and examples see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html">How to Use BoxLayout</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 Box
* @see java.awt.ComponentOrientation
* @see JComponent#getAlignmentX
* @see JComponent#getAlignmentY
*
* @author Timothy Prinzing
*/
public class BoxLayout implements LayoutManager2, Serializable {
/** {@collect.stats}
* Specifies that components should be laid out left to right.
*/
public static final int X_AXIS = 0;
/** {@collect.stats}
* Specifies that components should be laid out top to bottom.
*/
public static final int Y_AXIS = 1;
/** {@collect.stats}
* Specifies that components should be laid out in the direction of
* a line of text as determined by the target container's
* <code>ComponentOrientation</code> property.
*/
public static final int LINE_AXIS = 2;
/** {@collect.stats}
* Specifies that components should be laid out in the direction that
* lines flow across a page as determined by the target container's
* <code>ComponentOrientation</code> property.
*/
public static final int PAGE_AXIS = 3;
/** {@collect.stats}
* Creates a layout manager that will lay out components along the
* given axis.
*
* @param target the container that needs to be laid out
* @param axis the axis to lay out components along. Can be one of:
* <code>BoxLayout.X_AXIS</code>,
* <code>BoxLayout.Y_AXIS</code>,
* <code>BoxLayout.LINE_AXIS</code> or
* <code>BoxLayout.PAGE_AXIS</code>
*
* @exception AWTError if the value of <code>axis</code> is invalid
*/
public BoxLayout(Container target, int axis) {
if (axis != X_AXIS && axis != Y_AXIS &&
axis != LINE_AXIS && axis != PAGE_AXIS) {
throw new AWTError("Invalid axis");
}
this.axis = axis;
this.target = target;
}
/** {@collect.stats}
* Constructs a BoxLayout that
* produces debugging messages.
*
* @param target the container that needs to be laid out
* @param axis the axis to lay out components along. Can be one of:
* <code>BoxLayout.X_AXIS</code>,
* <code>BoxLayout.Y_AXIS</code>,
* <code>BoxLayout.LINE_AXIS</code> or
* <code>BoxLayout.PAGE_AXIS</code>
*
* @param dbg the stream to which debugging messages should be sent,
* null if none
*/
BoxLayout(Container target, int axis, PrintStream dbg) {
this(target, axis);
this.dbg = dbg;
}
/** {@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}
* Returns the axis that was used to lay out components.
* Returns one of:
* <code>BoxLayout.X_AXIS</code>,
* <code>BoxLayout.Y_AXIS</code>,
* <code>BoxLayout.LINE_AXIS</code> or
* <code>BoxLayout.PAGE_AXIS</code>
*
* @return the axis that was used to lay out components
*
* @since 1.6
*/
public final int getAxis() {
return this.axis;
}
/** {@collect.stats}
* Indicates that a child has changed its layout related information,
* and thus any cached calculations should be flushed.
* <p>
* This method is called by AWT when the invalidate method is called
* on the Container. Since the invalidate method may be called
* asynchronously to the event thread, this method may be called
* asynchronously.
*
* @param target the affected container
*
* @exception AWTError if the target isn't the container specified to the
* BoxLayout constructor
*/
public synchronized void invalidateLayout(Container target) {
checkContainer(target);
xChildren = null;
yChildren = null;
xTotal = null;
yTotal = null;
}
/** {@collect.stats}
* Not used by this class.
*
* @param name the name of the component
* @param comp the component
*/
public void addLayoutComponent(String name, Component comp) {
invalidateLayout(comp.getParent());
}
/** {@collect.stats}
* Not used by this class.
*
* @param comp the component
*/
public void removeLayoutComponent(Component comp) {
invalidateLayout(comp.getParent());
}
/** {@collect.stats}
* Not used by this class.
*
* @param comp the component
* @param constraints constraints
*/
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.
*
* @param target the container that needs to be laid out
* @return the dimensions >= 0 && <= Integer.MAX_VALUE
* @exception AWTError if the target isn't the container specified to the
* BoxLayout constructor
* @see Container
* @see #minimumLayoutSize
* @see #maximumLayoutSize
*/
public Dimension preferredLayoutSize(Container target) {
Dimension size;
synchronized(this) {
checkContainer(target);
checkRequests();
size = new Dimension(xTotal.preferred, yTotal.preferred);
}
Insets insets = target.getInsets();
size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);
size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);
return size;
}
/** {@collect.stats}
* Returns the minimum dimensions needed to lay out the components
* contained in the specified target container.
*
* @param target the container that needs to be laid out
* @return the dimensions >= 0 && <= Integer.MAX_VALUE
* @exception AWTError if the target isn't the container specified to the
* BoxLayout constructor
* @see #preferredLayoutSize
* @see #maximumLayoutSize
*/
public Dimension minimumLayoutSize(Container target) {
Dimension size;
synchronized(this) {
checkContainer(target);
checkRequests();
size = new Dimension(xTotal.minimum, yTotal.minimum);
}
Insets insets = target.getInsets();
size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);
size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);
return size;
}
/** {@collect.stats}
* Returns the maximum dimensions the target container can use
* to lay out the components it contains.
*
* @param target the container that needs to be laid out
* @return the dimenions >= 0 && <= Integer.MAX_VALUE
* @exception AWTError if the target isn't the container specified to the
* BoxLayout constructor
* @see #preferredLayoutSize
* @see #minimumLayoutSize
*/
public Dimension maximumLayoutSize(Container target) {
Dimension size;
synchronized(this) {
checkContainer(target);
checkRequests();
size = new Dimension(xTotal.maximum, yTotal.maximum);
}
Insets insets = target.getInsets();
size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);
size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);
return size;
}
/** {@collect.stats}
* Returns the alignment along the X axis for the container.
* If the box is horizontal, the default
* alignment will be returned. Otherwise, the alignment needed
* to place the children along the X axis will be returned.
*
* @param target the container
* @return the alignment >= 0.0f && <= 1.0f
* @exception AWTError if the target isn't the container specified to the
* BoxLayout constructor
*/
public synchronized float getLayoutAlignmentX(Container target) {
checkContainer(target);
checkRequests();
return xTotal.alignment;
}
/** {@collect.stats}
* Returns the alignment along the Y axis for the container.
* If the box is vertical, the default
* alignment will be returned. Otherwise, the alignment needed
* to place the children along the Y axis will be returned.
*
* @param target the container
* @return the alignment >= 0.0f && <= 1.0f
* @exception AWTError if the target isn't the container specified to the
* BoxLayout constructor
*/
public synchronized float getLayoutAlignmentY(Container target) {
checkContainer(target);
checkRequests();
return yTotal.alignment;
}
/** {@collect.stats}
* Called by the AWT <!-- XXX CHECK! --> 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
* BoxLayout constructor
*/
public void layoutContainer(Container target) {
checkContainer(target);
int nChildren = target.getComponentCount();
int[] xOffsets = new int[nChildren];
int[] xSpans = new int[nChildren];
int[] yOffsets = new int[nChildren];
int[] ySpans = new int[nChildren];
Dimension alloc = target.getSize();
Insets in = target.getInsets();
alloc.width -= in.left + in.right;
alloc.height -= in.top + in.bottom;
// Resolve axis to an absolute value (either X_AXIS or Y_AXIS)
ComponentOrientation o = target.getComponentOrientation();
int absoluteAxis = resolveAxis( axis, o );
boolean ltr = (absoluteAxis != axis) ? o.isLeftToRight() : true;
// determine the child placements
synchronized(this) {
checkRequests();
if (absoluteAxis == X_AXIS) {
SizeRequirements.calculateTiledPositions(alloc.width, xTotal,
xChildren, xOffsets,
xSpans, ltr);
SizeRequirements.calculateAlignedPositions(alloc.height, yTotal,
yChildren, yOffsets,
ySpans);
} else {
SizeRequirements.calculateAlignedPositions(alloc.width, xTotal,
xChildren, xOffsets,
xSpans, ltr);
SizeRequirements.calculateTiledPositions(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((int) Math.min((long) in.left + (long) xOffsets[i], Integer.MAX_VALUE),
(int) Math.min((long) in.top + (long) yOffsets[i], Integer.MAX_VALUE),
xSpans[i], ySpans[i]);
}
if (dbg != null) {
for (int i = 0; i < nChildren; i++) {
Component c = target.getComponent(i);
dbg.println(c.toString());
dbg.println("X: " + xChildren[i]);
dbg.println("Y: " + yChildren[i]);
}
}
}
void checkContainer(Container target) {
if (this.target != target) {
throw new AWTError("BoxLayout 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);
if (!c.isVisible()) {
xChildren[i] = new SizeRequirements(0,0,0, c.getAlignmentX());
yChildren[i] = new SizeRequirements(0,0,0, c.getAlignmentY());
continue;
}
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());
}
// Resolve axis to an absolute value (either X_AXIS or Y_AXIS)
int absoluteAxis = resolveAxis(axis,target.getComponentOrientation());
if (absoluteAxis == X_AXIS) {
xTotal = SizeRequirements.getTiledSizeRequirements(xChildren);
yTotal = SizeRequirements.getAlignedSizeRequirements(yChildren);
} else {
xTotal = SizeRequirements.getAlignedSizeRequirements(xChildren);
yTotal = SizeRequirements.getTiledSizeRequirements(yChildren);
}
}
}
/** {@collect.stats}
* Given one of the 4 axis values, resolve it to an absolute axis.
* The relative axis values, PAGE_AXIS and LINE_AXIS are converted
* to their absolute couterpart given the target's ComponentOrientation
* value. The absolute axes, X_AXIS and Y_AXIS are returned unmodified.
*
* @param axis the axis to resolve
* @param o the ComponentOrientation to resolve against
* @return the resolved axis
*/
private int resolveAxis( int axis, ComponentOrientation o ) {
int absoluteAxis;
if( axis == LINE_AXIS ) {
absoluteAxis = o.isHorizontal() ? X_AXIS : Y_AXIS;
} else if( axis == PAGE_AXIS ) {
absoluteAxis = o.isHorizontal() ? Y_AXIS : X_AXIS;
} else {
absoluteAxis = axis;
}
return absoluteAxis;
}
private int axis;
private Container target;
private transient SizeRequirements[] xChildren;
private transient SizeRequirements[] yChildren;
private transient SizeRequirements xTotal;
private transient SizeRequirements yTotal;
private transient PrintStream dbg;
}
|
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.*;
/** {@collect.stats}
* The <code>Action</code> interface provides a useful extension to the
* <code>ActionListener</code>
* interface in cases where the same functionality may be accessed by
* several controls.
* <p>
* In addition to the <code>actionPerformed</code> method defined by the
* <code>ActionListener</code> interface, this interface allows the
* application to define, in a single place:
* <ul>
* <li>One or more text strings that describe the function. These strings
* can be used, for example, to display the flyover text for a button
* or to set the text in a menu item.
* <li>One or more icons that depict the function. These icons can be used
* for the images in a menu control, or for composite entries in a more
* sophisticated user interface.
* <li>The enabled/disabled state of the functionality. Instead of having
* to separately disable the menu item and the toolbar button, the
* application can disable the function that implements this interface.
* All components which are registered as listeners for the state change
* then know to disable event generation for that item and to modify the
* display accordingly.
* </ul>
* <p>
* This interface can be added to an existing class or used to create an
* adapter (typically, by subclassing <code>AbstractAction</code>).
* The <code>Action</code> object
* can then be added to multiple <code>Action</code>-aware containers
* and connected to <code>Action</code>-capable
* components. The GUI controls can then be activated or
* deactivated all at once by invoking the <code>Action</code> object's
* <code>setEnabled</code> method.
* <p>
* Note that <code>Action</code> implementations tend to be more expensive
* in terms of storage than a typical <code>ActionListener</code>,
* which does not offer the benefits of centralized control of
* functionality and broadcast of property changes. For this reason,
* you should take care to only use <code>Action</code>s where their benefits
* are desired, and use simple <code>ActionListener</code>s elsewhere.
* <p>
*
* <h4><a name="buttonActions"></a>Swing Components Supporting <code>Action</code></h4>
* <p>
* Many of Swing's components have an <code>Action</code> property. When
* an <code>Action</code> is set on a component, the following things
* happen:
* <ul>
* <li>The <code>Action</code> is added as an <code>ActionListener</code> to
* the component.
* <li>The component configures some of its properties to match the
* <code>Action</code>.
* <li>The component installs a <code>PropertyChangeListener</code> on the
* <code>Action</code> so that the component can change its properties
* to reflect changes in the <code>Action</code>'s properties.
* </ul>
* <p>
* The following table describes the properties used by
* <code>Swing</code> components that support <code>Actions</code>.
* In the table, <em>button</em> refers to any
* <code>AbstractButton</code> subclass, which includes not only
* <code>JButton</code> but also classes such as
* <code>JMenuItem</code>. Unless otherwise stated, a
* <code>null</code> property value in an <code>Action</code> (or a
* <code>Action</code> that is <code>null</code>) results in the
* button's corresponding property being set to <code>null</code>.
* <p>
* <table border="1" cellpadding="1" cellspacing="0"
* summary="Supported Action properties"
* valign="top" >
* <tr valign="top" align="left">
* <th bgcolor="#CCCCFF" align="left">Component Property
* <th bgcolor="#CCCCFF" align="left">Components
* <th bgcolor="#CCCCFF" align="left">Action Key
* <th bgcolor="#CCCCFF" align="left">Notes
* <tr valign="top" align="left">
* <td><b><code>enabled</code></b>
* <td>All
* <td>The <code>isEnabled</code> method
* <td>
* <tr valign="top" align="left">
* <td><b><code>toolTipText</code></b>
* <td>All
* <td><code>SHORT_DESCRIPTION</code>
* <td>
* <tr valign="top" align="left">
* <td><b><code>actionCommand</code></b>
* <td>All
* <td><code>ACTION_COMMAND_KEY</code>
* <td>
* <tr valign="top" align="left">
* <td><b><code>mnemonic</code></b>
* <td>All buttons
* <td><code>MNEMONIC_KEY</code>
* <td>A <code>null</code> value or <code>Action</code> results in the
* button's <code>mnemonic</code> property being set to
* <code>'\0'</code>.
* <tr valign="top" align="left">
* <td><b><code>text</code></b>
* <td>All buttons
* <td><code>NAME</code>
* <td>If you do not want the text of the button to mirror that
* of the <code>Action</code>, set the property
* <code>hideActionText</code> to <code>true</code>. If
* <code>hideActionText</code> is <code>true</code>, setting the
* <code>Action</code> changes the text of the button to
* <code>null</code> and any changes to <code>NAME</code>
* are ignored. <code>hideActionText</code> is useful for
* tool bar buttons that typically only show an <code>Icon</code>.
* <code>JToolBar.add(Action)</code> sets the property to
* <code>true</code> if the <code>Action</code> has a
* non-<code>null</code> value for <code>LARGE_ICON_KEY</code> or
* <code>SMALL_ICON</code>.
* <tr valign="top" align="left">
* <td><b><code>displayedMnemonicIndex</code></b>
* <td>All buttons
* <td><code>DISPLAYED_MNEMONIC_INDEX_KEY</code>
* <td>If the value of <code>DISPLAYED_MNEMONIC_INDEX_KEY</code> is
* beyond the bounds of the text, it is ignored. When
* <code>setAction</code> is called, if the value from the
* <code>Action</code> is <code>null</code>, the displayed
* mnemonic index is not updated. In any subsequent changes to
* <code>DISPLAYED_MNEMONIC_INDEX_KEY</code>, <code>null</code>
* is treated as -1.
* <tr valign="top" align="left">
* <td><b><code>icon</code></b>
* <td>All buttons except of <code>JCheckBox</code>,
* <code>JToggleButton</code> and <code>JRadioButton</code>.
* <td>either <code>LARGE_ICON_KEY</code> or
* <code>SMALL_ICON</code>
* <td>The <code>JMenuItem</code> subclasses only use
* <code>SMALL_ICON</code>. All other buttons will use
* <code>LARGE_ICON_KEY</code>; if the value is <code>null</code> they
* use <code>SMALL_ICON</code>.
* <tr valign="top" align="left">
* <td><b><code>accelerator</code></b>
* <td>All <code>JMenuItem</code> subclasses, with the exception of
* <code>JMenu</code>.
* <td><code>ACCELERATOR_KEY</code>
* <td>
* <tr valign="top" align="left">
* <td><b><code>selected</code></b>
* <td><code>JToggleButton</code>, <code>JCheckBox</code>,
* <code>JRadioButton</code>, <code>JCheckBoxMenuItem</code> and
* <code>JRadioButtonMenuItem</code>
* <td><code>SELECTED_KEY</code>
* <td>Components that honor this property only use
* the value if it is {@code non-null}. For example, if
* you set an {@code Action} that has a {@code null}
* value for {@code SELECTED_KEY} on a {@code JToggleButton}, the
* {@code JToggleButton} will not update it's selected state in
* any way. Similarly, any time the {@code JToggleButton}'s
* selected state changes it will only set the value back on
* the {@code Action} if the {@code Action} has a {@code non-null}
* value for {@code SELECTED_KEY}.
* <br>
* Components that honor this property keep their selected state
* in sync with this property. When the same {@code Action} is used
* with multiple components, all the components keep their selected
* state in sync with this property. Mutually exclusive
* buttons, such as {@code JToggleButton}s in a {@code ButtonGroup},
* force only one of the buttons to be selected. As such, do not
* use the same {@code Action} that defines a value for the
* {@code SELECTED_KEY} property with multiple mutually
* exclusive buttons.
* </table>
* <p>
* <code>JPopupMenu</code>, <code>JToolBar</code> and <code>JMenu</code>
* all provide convenience methods for creating a component and setting the
* <code>Action</code> on the corresponding component. Refer to each of
* these classes for more information.
* <p>
* <code>Action</code> uses <code>PropertyChangeListener</code> to
* inform listeners the <code>Action</code> has changed. The beans
* specification indicates that a <code>null</code> property name can
* be used to indicate multiple values have changed. By default Swing
* components that take an <code>Action</code> do not handle such a
* change. To indicate that Swing should treat <code>null</code>
* according to the beans specification set the system property
* <code>swing.actions.reconfigureOnNull</code> to the <code>String</code>
* value <code>true</code>.
*
* @author Georges Saab
* @see AbstractAction
*/
public interface Action extends ActionListener {
/** {@collect.stats}
* Useful constants that can be used as the storage-retrieval key
* when setting or getting one of this object's properties (text
* or icon).
*/
/** {@collect.stats}
* Not currently used.
*/
public static final String DEFAULT = "Default";
/** {@collect.stats}
* The key used for storing the <code>String</code> name
* for the action, used for a menu or button.
*/
public static final String NAME = "Name";
/** {@collect.stats}
* The key used for storing a short <code>String</code>
* description for the action, used for tooltip text.
*/
public static final String SHORT_DESCRIPTION = "ShortDescription";
/** {@collect.stats}
* The key used for storing a longer <code>String</code>
* description for the action, could be used for context-sensitive help.
*/
public static final String LONG_DESCRIPTION = "LongDescription";
/** {@collect.stats}
* The key used for storing a small <code>Icon</code>, such
* as <code>ImageIcon</code>. This is typically used with
* menus such as <code>JMenuItem</code>.
* <p>
* If the same <code>Action</code> is used with menus and buttons you'll
* typically specify both a <code>SMALL_ICON</code> and a
* <code>LARGE_ICON_KEY</code>. The menu will use the
* <code>SMALL_ICON</code> and the button will use the
* <code>LARGE_ICON_KEY</code>.
*/
public static final String SMALL_ICON = "SmallIcon";
/** {@collect.stats}
* The key used to determine the command <code>String</code> for the
* <code>ActionEvent</code> that will be created when an
* <code>Action</code> is going to be notified as the result of
* residing in a <code>Keymap</code> associated with a
* <code>JComponent</code>.
*/
public static final String ACTION_COMMAND_KEY = "ActionCommandKey";
/** {@collect.stats}
* The key used for storing a <code>KeyStroke</code> to be used as the
* accelerator for the action.
*
* @since 1.3
*/
public static final String ACCELERATOR_KEY="AcceleratorKey";
/** {@collect.stats}
* The key used for storing an <code>Integer</code> that corresponds to
* one of the <code>KeyEvent</code> key codes. The value is
* commonly used to specify a mnemonic. For example:
* <code>myAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A)</code>
* sets the mnemonic of <code>myAction</code> to 'a'.
*
* @since 1.3
*/
public static final String MNEMONIC_KEY="MnemonicKey";
/** {@collect.stats}
* The key used for storing a <code>Boolean</code> that corresponds
* to the selected state. This is typically used only for components
* that have a meaningful selection state. For example,
* <code>JRadioButton</code> and <code>JCheckBox</code> make use of
* this but instances of <code>JMenu</code> don't.
* <p>
* This property differs from the others in that it is both read
* by the component and set by the component. For example,
* if an <code>Action</code> is attached to a <code>JCheckBox</code>
* the selected state of the <code>JCheckBox</code> will be set from
* that of the <code>Action</code>. If the user clicks on the
* <code>JCheckBox</code> the selected state of the <code>JCheckBox</code>
* <b>and</b> the <code>Action</code> will <b>both</b> be updated.
* <p>
* Note: the value of this field is prefixed with 'Swing' to
* avoid possible collisions with existing <code>Actions</code>.
*
* @since 1.6
*/
public static final String SELECTED_KEY = "SwingSelectedKey";
/** {@collect.stats}
* The key used for storing an <code>Integer</code> that corresponds
* to the index in the text (identified by the <code>NAME</code>
* property) that the decoration for a mnemonic should be rendered at. If
* the value of this property is greater than or equal to the length of
* the text, it will treated as -1.
* <p>
* Note: the value of this field is prefixed with 'Swing' to
* avoid possible collisions with existing <code>Actions</code>.
*
* @see AbstractButton#setDisplayedMnemonicIndex
* @since 1.6
*/
public static final String DISPLAYED_MNEMONIC_INDEX_KEY =
"SwingDisplayedMnemonicIndexKey";
/** {@collect.stats}
* The key used for storing an <code>Icon</code>. This is typically
* used by buttons, such as <code>JButton</code> and
* <code>JToggleButton</code>.
* <p>
* If the same <code>Action</code> is used with menus and buttons you'll
* typically specify both a <code>SMALL_ICON</code> and a
* <code>LARGE_ICON_KEY</code>. The menu will use the
* <code>SMALL_ICON</code> and the button the <code>LARGE_ICON_KEY</code>.
* <p>
* Note: the value of this field is prefixed with 'Swing' to
* avoid possible collisions with existing <code>Actions</code>.
*
* @since 1.6
*/
public static final String LARGE_ICON_KEY = "SwingLargeIconKey";
/** {@collect.stats}
* Gets one of this object's properties
* using the associated key.
* @see #putValue
*/
public Object getValue(String key);
/** {@collect.stats}
* Sets one of this object's properties
* using the associated key. If the value has
* changed, a <code>PropertyChangeEvent</code> is sent
* to listeners.
*
* @param key a <code>String</code> containing the key
* @param value an <code>Object</code> value
*/
public void putValue(String key, Object value);
/** {@collect.stats}
* Sets the enabled state of the <code>Action</code>. When enabled,
* any component associated with this object is active and
* able to fire this object's <code>actionPerformed</code> method.
* If the value has changed, a <code>PropertyChangeEvent</code> is sent
* to listeners.
*
* @param b true to enable this <code>Action</code>, false to disable it
*/
public void setEnabled(boolean b);
/** {@collect.stats}
* Returns the enabled state of the <code>Action</code>. When enabled,
* any component associated with this object is active and
* able to fire this object's <code>actionPerformed</code> method.
*
* @return true if this <code>Action</code> is enabled
*/
public boolean isEnabled();
/** {@collect.stats}
* Adds a <code>PropertyChange</code> listener. Containers and attached
* components use these methods to register interest in this
* <code>Action</code> object. When its enabled state or other property
* changes, the registered listeners are informed of the change.
*
* @param listener a <code>PropertyChangeListener</code> object
*/
public void addPropertyChangeListener(PropertyChangeListener listener);
/** {@collect.stats}
* Removes a <code>PropertyChange</code> listener.
*
* @param listener a <code>PropertyChangeListener</code> object
* @see #addPropertyChangeListener
*/
public void removePropertyChangeListener(PropertyChangeListener listener);
}
|
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.awt.image.*;
import java.net.URL;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.util.Locale;
import javax.accessibility.*;
import sun.awt.AppContext;
import java.lang.reflect.Field;
import java.security.*;
/** {@collect.stats}
* An implementation of the Icon interface that paints Icons
* from Images. Images that are created from a URL, filename or byte array
* are preloaded using MediaTracker to monitor the loaded state
* of the image.
*
* <p>
* For further information and examples of using image icons, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/icon.html">How to Use Icons</a>
* 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 Jeff Dinkins
* @author Lynn Monsanto
*/
public class ImageIcon implements Icon, Serializable, Accessible {
/* Keep references to the filename and location so that
* alternate persistence schemes have the option to archive
* images symbolically rather than including the image data
* in the archive.
*/
transient private String filename;
transient private URL location;
transient Image image;
transient int loadStatus = 0;
ImageObserver imageObserver;
String description = null;
// Fields for twisted backward compatibility only. DO NOT USE.
protected final static Component component;
protected final static MediaTracker tracker;
static {
component = AccessController.doPrivileged(new PrivilegedAction<Component>() {
public Component run() {
try {
final Component component = createNoPermsComponent();
// 6482575 - clear the appContext field so as not to leak it
Field appContextField =
Component.class.getDeclaredField("appContext");
appContextField.setAccessible(true);
appContextField.set(component, null);
return component;
} catch (Throwable e) {
// We don't care about component.
// So don't prevent class initialisation.
e.printStackTrace();
return null;
}
}
});
tracker = new MediaTracker(component);
}
private static Component createNoPermsComponent() {
// 7020198 - set acc field to no permissions and no subject
// Note, will have appContext set.
return AccessController.doPrivileged(
new PrivilegedAction<Component>() {
public Component run() {
return new Component() {
};
}
},
new AccessControlContext(new ProtectionDomain[]{
new ProtectionDomain(null, null)
})
);
}
/** {@collect.stats}
* Id used in loading images from MediaTracker.
*/
private static int mediaTrackerID;
private final static Object TRACKER_KEY = new StringBuilder("TRACKER_KEY");
int width = -1;
int height = -1;
/** {@collect.stats}
* Creates an ImageIcon from the specified file. The image will
* be preloaded by using MediaTracker to monitor the loading state
* of the image.
* @param filename the name of the file containing the image
* @param description a brief textual description of the image
* @see #ImageIcon(String)
*/
public ImageIcon(String filename, String description) {
image = Toolkit.getDefaultToolkit().getImage(filename);
if (image == null) {
return;
}
this.filename = filename;
this.description = description;
loadImage(image);
}
/** {@collect.stats}
* Creates an ImageIcon from the specified file. The image will
* be preloaded by using MediaTracker to monitor the loading state
* of the image. The specified String can be a file name or a
* file path. When specifying a path, use the Internet-standard
* forward-slash ("/") as a separator.
* (The string is converted to an URL, so the forward-slash works
* on all systems.)
* For example, specify:
* <pre>
* new ImageIcon("images/myImage.gif") </pre>
* The description is initialized to the <code>filename</code> string.
*
* @param filename a String specifying a filename or path
* @see #getDescription
*/
public ImageIcon (String filename) {
this(filename, filename);
}
/** {@collect.stats}
* Creates an ImageIcon from the specified URL. The image will
* be preloaded by using MediaTracker to monitor the loaded state
* of the image.
* @param location the URL for the image
* @param description a brief textual description of the image
* @see #ImageIcon(String)
*/
public ImageIcon(URL location, String description) {
image = Toolkit.getDefaultToolkit().getImage(location);
if (image == null) {
return;
}
this.location = location;
this.description = description;
loadImage(image);
}
/** {@collect.stats}
* Creates an ImageIcon from the specified URL. The image will
* be preloaded by using MediaTracker to monitor the loaded state
* of the image.
* The icon's description is initialized to be
* a string representation of the URL.
* @param location the URL for the image
* @see #getDescription
*/
public ImageIcon (URL location) {
this(location, location.toExternalForm());
}
/** {@collect.stats}
* Creates an ImageIcon from the image.
* @param image the image
* @param description a brief textual description of the image
*/
public ImageIcon(Image image, String description) {
this(image);
this.description = description;
}
/** {@collect.stats}
* Creates an ImageIcon from an image object.
* If the image has a "comment" property that is a string,
* then the string is used as the description of this icon.
* @param image the image
* @see #getDescription
* @see java.awt.Image#getProperty
*/
public ImageIcon (Image image) {
this.image = image;
Object o = image.getProperty("comment", imageObserver);
if (o instanceof String) {
description = (String) o;
}
loadImage(image);
}
/** {@collect.stats}
* Creates an ImageIcon from an array of bytes which were
* read from an image file containing a supported image format,
* such as GIF, JPEG, or (as of 1.3) PNG.
* Normally this array is created
* by reading an image using Class.getResourceAsStream(), but
* the byte array may also be statically stored in a class.
*
* @param imageData an array of pixels in an image format supported
* by the AWT Toolkit, such as GIF, JPEG, or (as of 1.3) PNG
* @param description a brief textual description of the image
* @see java.awt.Toolkit#createImage
*/
public ImageIcon (byte[] imageData, String description) {
this.image = Toolkit.getDefaultToolkit().createImage(imageData);
if (image == null) {
return;
}
this.description = description;
loadImage(image);
}
/** {@collect.stats}
* Creates an ImageIcon from an array of bytes which were
* read from an image file containing a supported image format,
* such as GIF, JPEG, or (as of 1.3) PNG.
* Normally this array is created
* by reading an image using Class.getResourceAsStream(), but
* the byte array may also be statically stored in a class.
* If the resulting image has a "comment" property that is a string,
* then the string is used as the description of this icon.
*
* @param imageData an array of pixels in an image format supported by
* the AWT Toolkit, such as GIF, JPEG, or (as of 1.3) PNG
* @see java.awt.Toolkit#createImage
* @see #getDescription
* @see java.awt.Image#getProperty
*/
public ImageIcon (byte[] imageData) {
this.image = Toolkit.getDefaultToolkit().createImage(imageData);
if (image == null) {
return;
}
Object o = image.getProperty("comment", imageObserver);
if (o instanceof String) {
description = (String) o;
}
loadImage(image);
}
/** {@collect.stats}
* Creates an uninitialized image icon.
*/
public ImageIcon() {
}
/** {@collect.stats}
* Loads the image, returning only when the image is loaded.
* @param image the image
*/
protected void loadImage(Image image) {
MediaTracker mTracker = getTracker();
synchronized(mTracker) {
int id = getNextID();
mTracker.addImage(image, id);
try {
mTracker.waitForID(id, 0);
} catch (InterruptedException e) {
System.out.println("INTERRUPTED while loading Image");
}
loadStatus = mTracker.statusID(id, false);
mTracker.removeImage(image, id);
width = image.getWidth(imageObserver);
height = image.getHeight(imageObserver);
}
}
/** {@collect.stats}
* Returns an ID to use with the MediaTracker in loading an image.
*/
private int getNextID() {
synchronized(getTracker()) {
return ++mediaTrackerID;
}
}
/** {@collect.stats}
* Returns the MediaTracker for the current AppContext, creating a new
* MediaTracker if necessary.
*/
private MediaTracker getTracker() {
Object trackerObj;
AppContext ac = AppContext.getAppContext();
// Opt: Only synchronize if trackerObj comes back null?
// If null, synchronize, re-check for null, and put new tracker
synchronized (ac) {
trackerObj = ac.get(TRACKER_KEY);
if (trackerObj == null) {
Component comp = new Component() {
};
trackerObj = new MediaTracker(comp);
ac.put(TRACKER_KEY, trackerObj);
}
}
return (MediaTracker) trackerObj;
}
/** {@collect.stats}
* Returns the status of the image loading operation.
* @return the loading status as defined by java.awt.MediaTracker
* @see java.awt.MediaTracker#ABORTED
* @see java.awt.MediaTracker#ERRORED
* @see java.awt.MediaTracker#COMPLETE
*/
public int getImageLoadStatus() {
return loadStatus;
}
/** {@collect.stats}
* Returns this icon's <code>Image</code>.
* @return the <code>Image</code> object for this <code>ImageIcon</code>
*/
public Image getImage() {
return image;
}
/** {@collect.stats}
* Sets the image displayed by this icon.
* @param image the image
*/
public void setImage(Image image) {
this.image = image;
loadImage(image);
}
/** {@collect.stats}
* Gets the description of the image. This is meant to be a brief
* textual description of the object. For example, it might be
* presented to a blind user to give an indication of the purpose
* of the image.
* The description may be null.
*
* @return a brief textual description of the image
*/
public String getDescription() {
return description;
}
/** {@collect.stats}
* Sets the description of the image. This is meant to be a brief
* textual description of the object. For example, it might be
* presented to a blind user to give an indication of the purpose
* of the image.
* @param description a brief textual description of the image
*/
public void setDescription(String description) {
this.description = description;
}
/** {@collect.stats}
* Paints the icon.
* The top-left corner of the icon is drawn at
* the point (<code>x</code>, <code>y</code>)
* in the coordinate space of the graphics context <code>g</code>.
* If this icon has no image observer,
* this method uses the <code>c</code> component
* as the observer.
*
* @param c the component to be used as the observer
* if this icon has no image observer
* @param g the graphics context
* @param x the X coordinate of the icon's top-left corner
* @param y the Y coordinate of the icon's top-left corner
*/
public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
if(imageObserver == null) {
g.drawImage(image, x, y, c);
} else {
g.drawImage(image, x, y, imageObserver);
}
}
/** {@collect.stats}
* Gets the width of the icon.
*
* @return the width in pixels of this icon
*/
public int getIconWidth() {
return width;
}
/** {@collect.stats}
* Gets the height of the icon.
*
* @return the height in pixels of this icon
*/
public int getIconHeight() {
return height;
}
/** {@collect.stats}
* Sets the image observer for the image. Set this
* property if the ImageIcon contains an animated GIF, so
* the observer is notified to update its display.
* For example:
* <pre>
* icon = new ImageIcon(...)
* button.setIcon(icon);
* icon.setImageObserver(button);
* </pre>
*
* @param observer the image observer
*/
public void setImageObserver(ImageObserver observer) {
imageObserver = observer;
}
/** {@collect.stats}
* Returns the image observer for the image.
*
* @return the image observer, which may be null
*/
public ImageObserver getImageObserver() {
return imageObserver;
}
/** {@collect.stats}
* Returns a string representation of this image.
*
* @return a string representing this image
*/
public String toString() {
if (description != null) {
return description;
}
return super.toString();
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
int w = s.readInt();
int h = s.readInt();
int[] pixels = (int[])(s.readObject());
if (pixels != null) {
Toolkit tk = Toolkit.getDefaultToolkit();
ColorModel cm = ColorModel.getRGBdefault();
image = tk.createImage(new MemoryImageSource(w, h, cm, pixels, 0, w));
loadImage(image);
}
}
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
int w = getIconWidth();
int h = getIconHeight();
int[] pixels = image != null? new int[w * h] : null;
if (image != null) {
try {
PixelGrabber pg = new PixelGrabber(image, 0, 0, w, h, pixels, 0, w);
pg.grabPixels();
if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
throw new IOException("failed to load image contents");
}
}
catch (InterruptedException e) {
throw new IOException("image load interrupted");
}
}
s.writeInt(w);
s.writeInt(h);
s.writeObject(pixels);
}
/** {@collect.stats}
* --- Accessibility Support ---
*/
private AccessibleImageIcon accessibleContext = null;
/** {@collect.stats}
* Gets the AccessibleContext associated with this ImageIcon.
* For image icons, the AccessibleContext takes the form of an
* AccessibleImageIcon.
* A new AccessibleImageIcon instance is created if necessary.
*
* @return an AccessibleImageIcon that serves as the
* AccessibleContext of this ImageIcon
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this ImageIcon.
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleImageIcon();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>ImageIcon</code> class. It provides an implementation of the
* Java Accessibility API appropriate to image icon 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}.
* @since 1.3
*/
protected class AccessibleImageIcon extends AccessibleContext
implements AccessibleIcon, Serializable {
/*
* AccessibleContest implementation -----------------
*/
/** {@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.ICON;
}
/** {@collect.stats}
* Gets the state of this object.
*
* @return an instance of AccessibleStateSet containing the current
* state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
return null;
}
/** {@collect.stats}
* Gets the Accessible parent of this object. If the parent of this
* object implements Accessible, this method should simply return
* getParent().
*
* @return the Accessible parent of this object -- can be null if this
* object does not have an Accessible parent
*/
public Accessible getAccessibleParent() {
return null;
}
/** {@collect.stats}
* Gets the index of this object in its accessible parent.
*
* @return the index of this object in its parent; -1 if this
* object does not have an accessible parent.
* @see #getAccessibleParent
*/
public int getAccessibleIndexInParent() {
return -1;
}
/** {@collect.stats}
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
return 0;
}
/** {@collect.stats}
* Returns the nth Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
return null;
}
/** {@collect.stats}
* Returns the locale of this object.
*
* @return the locale of this object
*/
public Locale getLocale() throws IllegalComponentStateException {
return null;
}
/*
* AccessibleIcon implementation -----------------
*/
/** {@collect.stats}
* Gets the description of the icon. This is meant to be a brief
* textual description of the object. For example, it might be
* presented to a blind user to give an indication of the purpose
* of the icon.
*
* @return the description of the icon
*/
public String getAccessibleIconDescription() {
return ImageIcon.this.getDescription();
}
/** {@collect.stats}
* Sets the description of the icon. This is meant to be a brief
* textual description of the object. For example, it might be
* presented to a blind user to give an indication of the purpose
* of the icon.
*
* @param description the description of the icon
*/
public void setAccessibleIconDescription(String description) {
ImageIcon.this.setDescription(description);
}
/** {@collect.stats}
* Gets the height of the icon.
*
* @return the height of the icon
*/
public int getAccessibleIconHeight() {
return ImageIcon.this.height;
}
/** {@collect.stats}
* Gets the width of the icon.
*
* @return the width of the icon
*/
public int getAccessibleIconWidth() {
return ImageIcon.this.width;
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
}
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
}
} // AccessibleImageIcon
}
|
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.awt.event.*;
import java.beans.*;
import java.util.Hashtable;
import java.util.Enumeration;
import java.io.Serializable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.AccessController;
import javax.swing.event.SwingPropertyChangeSupport;
import sun.security.action.GetPropertyAction;
/** {@collect.stats}
* This class provides default implementations for the JFC <code>Action</code>
* interface. Standard behaviors like the get and set methods for
* <code>Action</code> object properties (icon, text, and enabled) are defined
* here. The developer need only subclass this abstract class and
* define the <code>actionPerformed</code> 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 Georges Saab
* @see Action
*/
public abstract class AbstractAction implements Action, Cloneable, Serializable
{
/** {@collect.stats}
* Whether or not actions should reconfigure all properties on null.
*/
private static Boolean RECONFIGURE_ON_NULL;
/** {@collect.stats}
* Specifies whether action is enabled; the default is true.
*/
protected boolean enabled = true;
/** {@collect.stats}
* Contains the array of key bindings.
*/
private transient ArrayTable arrayTable;
/** {@collect.stats}
* Whether or not to reconfigure all action properties from the
* specified event.
*/
static boolean shouldReconfigure(PropertyChangeEvent e) {
if (e.getPropertyName() == null) {
synchronized(AbstractAction.class) {
if (RECONFIGURE_ON_NULL == null) {
RECONFIGURE_ON_NULL = Boolean.valueOf(
AccessController.doPrivileged(new GetPropertyAction(
"swing.actions.reconfigureOnNull", "false")));
}
return RECONFIGURE_ON_NULL;
}
}
return false;
}
/** {@collect.stats}
* Sets the enabled state of a component from an Action.
*
* @param c the Component to set the enabled state on
* @param a the Action to set the enabled state from, may be null
*/
static void setEnabledFromAction(JComponent c, Action a) {
c.setEnabled((a != null) ? a.isEnabled() : true);
}
/** {@collect.stats}
* Sets the tooltip text of a component from an Action.
*
* @param c the Component to set the tooltip text on
* @param a the Action to set the tooltip text from, may be null
*/
static void setToolTipTextFromAction(JComponent c, Action a) {
c.setToolTipText(a != null ?
(String)a.getValue(Action.SHORT_DESCRIPTION) : null);
}
static boolean hasSelectedKey(Action a) {
return (a != null && a.getValue(Action.SELECTED_KEY) != null);
}
static boolean isSelected(Action a) {
return Boolean.TRUE.equals(a.getValue(Action.SELECTED_KEY));
}
/** {@collect.stats}
* Creates an {@code Action}.
*/
public AbstractAction() {
}
/** {@collect.stats}
* Creates an {@code Action} with the specified name.
*
* @param name the name ({@code Action.NAME}) for the action; a
* value of {@code null} is ignored
*/
public AbstractAction(String name) {
putValue(Action.NAME, name);
}
/** {@collect.stats}
* Creates an {@code Action} with the specified name and small icon.
*
* @param name the name ({@code Action.NAME}) for the action; a
* value of {@code null} is ignored
* @param icon the small icon ({@code Action.SMALL_ICON}) for the action; a
* value of {@code null} is ignored
*/
public AbstractAction(String name, Icon icon) {
this(name);
putValue(Action.SMALL_ICON, icon);
}
/** {@collect.stats}
* Gets the <code>Object</code> associated with the specified key.
*
* @param key a string containing the specified <code>key</code>
* @return the binding <code>Object</code> stored with this key; if there
* are no keys, it will return <code>null</code>
* @see Action#getValue
*/
public Object getValue(String key) {
if (key == "enabled") {
return enabled;
}
if (arrayTable == null) {
return null;
}
return arrayTable.get(key);
}
/** {@collect.stats}
* Sets the <code>Value</code> associated with the specified key.
*
* @param key the <code>String</code> that identifies the stored object
* @param newValue the <code>Object</code> to store using this key
* @see Action#putValue
*/
public void putValue(String key, Object newValue) {
Object oldValue = null;
if (key == "enabled") {
// Treat putValue("enabled") the same way as a call to setEnabled.
// If we don't do this it means the two may get out of sync, and a
// bogus property change notification would be sent.
//
// To avoid dependencies between putValue & setEnabled this
// directly changes enabled. If we instead called setEnabled
// to change enabled, it would be possible for stack
// overflow in the case where a developer implemented setEnabled
// in terms of putValue.
if (newValue == null || !(newValue instanceof Boolean)) {
newValue = false;
}
oldValue = enabled;
enabled = (Boolean)newValue;
} else {
if (arrayTable == null) {
arrayTable = new ArrayTable();
}
if (arrayTable.containsKey(key))
oldValue = arrayTable.get(key);
// Remove the entry for key if newValue is null
// else put in the newValue for key.
if (newValue == null) {
arrayTable.remove(key);
} else {
arrayTable.put(key,newValue);
}
}
firePropertyChange(key, oldValue, newValue);
}
/** {@collect.stats}
* Returns true if the action is enabled.
*
* @return true if the action is enabled, false otherwise
* @see Action#isEnabled
*/
public boolean isEnabled() {
return enabled;
}
/** {@collect.stats}
* Sets whether the {@code Action} is enabled. The default is {@code true}.
*
* @param newValue {@code true} to enable the action, {@code false} to
* disable it
* @see Action#setEnabled
*/
public void setEnabled(boolean newValue) {
boolean oldValue = this.enabled;
if (oldValue != newValue) {
this.enabled = newValue;
firePropertyChange("enabled",
Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
}
}
/** {@collect.stats}
* Returns an array of <code>Object</code>s which are keys for
* which values have been set for this <code>AbstractAction</code>,
* or <code>null</code> if no keys have values set.
* @return an array of key objects, or <code>null</code> if no
* keys have values set
* @since 1.3
*/
public Object[] getKeys() {
if (arrayTable == null) {
return null;
}
Object[] keys = new Object[arrayTable.size()];
arrayTable.getKeys(keys);
return keys;
}
/** {@collect.stats}
* If any <code>PropertyChangeListeners</code> have been registered, the
* <code>changeSupport</code> field describes them.
*/
protected SwingPropertyChangeSupport changeSupport;
/** {@collect.stats}
* Supports reporting bound property changes. This method can be called
* when a bound property has changed and it will send the appropriate
* <code>PropertyChangeEvent</code> to any registered
* <code>PropertyChangeListeners</code>.
*/
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
if (changeSupport == null ||
(oldValue != null && newValue != null && oldValue.equals(newValue))) {
return;
}
changeSupport.firePropertyChange(propertyName, oldValue, newValue);
}
/** {@collect.stats}
* Adds a <code>PropertyChangeListener</code> to the listener list.
* The listener is registered for all properties.
* <p>
* A <code>PropertyChangeEvent</code> will get fired in response to setting
* a bound property, e.g. <code>setFont</code>, <code>setBackground</code>,
* or <code>setForeground</code>.
* Note that if the current component is inheriting its foreground,
* background, or font from its container, then no event will be
* fired in response to a change in the inherited property.
*
* @param listener The <code>PropertyChangeListener</code> to be added
*
* @see Action#addPropertyChangeListener
*/
public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
if (changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
/** {@collect.stats}
* Removes a <code>PropertyChangeListener</code> from the listener list.
* This removes a <code>PropertyChangeListener</code> that was registered
* for all properties.
*
* @param listener the <code>PropertyChangeListener</code> to be removed
*
* @see Action#removePropertyChangeListener
*/
public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
if (changeSupport == null) {
return;
}
changeSupport.removePropertyChangeListener(listener);
}
/** {@collect.stats}
* Returns an array of all the <code>PropertyChangeListener</code>s added
* to this AbstractAction with addPropertyChangeListener().
*
* @return all of the <code>PropertyChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public synchronized PropertyChangeListener[] getPropertyChangeListeners() {
if (changeSupport == null) {
return new PropertyChangeListener[0];
}
return changeSupport.getPropertyChangeListeners();
}
/** {@collect.stats}
* Clones the abstract action. This gives the clone
* its own copy of the key/value list,
* which is not handled for you by <code>Object.clone()</code>.
**/
protected Object clone() throws CloneNotSupportedException {
AbstractAction newAction = (AbstractAction)super.clone();
synchronized(this) {
if (arrayTable != null) {
newAction.arrayTable = (ArrayTable)arrayTable.clone();
}
}
return newAction;
}
private void writeObject(ObjectOutputStream s) throws IOException {
// Store the default fields
s.defaultWriteObject();
// And the keys
ArrayTable.writeArrayTable(s, arrayTable);
}
private void readObject(ObjectInputStream s) throws ClassNotFoundException,
IOException {
s.defaultReadObject();
for (int counter = s.readInt() - 1; counter >= 0; counter--) {
putValue((String)s.readObject(), s.readObject());
}
}
}
|
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.LayoutManager;
import java.awt.Component;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.Insets;
import java.io.Serializable;
/** {@collect.stats}
* The default layout manager for <code>JViewport</code>.
* <code>ViewportLayout</code> defines
* a policy for layout that should be useful for most applications.
* The viewport makes its view the same size as the viewport,
* however it will not make the view smaller than its minimum size.
* As the viewport grows the view is kept bottom justified until
* the entire view is visible, subsequently the view is kept top
* justified.
* <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 ViewportLayout implements LayoutManager, Serializable
{
// Single instance used by JViewport.
static ViewportLayout SHARED_INSTANCE = new ViewportLayout();
/** {@collect.stats}
* Adds the specified component to the layout. Not used by this class.
* @param name the name of the component
* @param c the the component to be added
*/
public void addLayoutComponent(String name, Component c) { }
/** {@collect.stats}
* Removes the specified component from the layout. Not used by
* this class.
* @param c the component to remove
*/
public void removeLayoutComponent(Component c) { }
/** {@collect.stats}
* Returns the preferred dimensions for this layout given the components
* in the specified target container.
* @param parent the component which needs to be laid out
* @return a <code>Dimension</code> object containing the
* preferred dimensions
* @see #minimumLayoutSize
*/
public Dimension preferredLayoutSize(Container parent) {
Component view = ((JViewport)parent).getView();
if (view == null) {
return new Dimension(0, 0);
}
else if (view instanceof Scrollable) {
return ((Scrollable)view).getPreferredScrollableViewportSize();
}
else {
return view.getPreferredSize();
}
}
/** {@collect.stats}
* Returns the minimum dimensions needed to layout the components
* contained in the specified target container.
*
* @param parent the component which needs to be laid out
* @return a <code>Dimension</code> object containing the minimum
* dimensions
* @see #preferredLayoutSize
*/
public Dimension minimumLayoutSize(Container parent) {
return new Dimension(4, 4);
}
/** {@collect.stats}
* Called by the AWT when the specified container needs to be laid out.
*
* @param parent the container to lay out
*
* @exception AWTError if the target isn't the container specified to the
* <code>BoxLayout</code> constructor
*/
public void layoutContainer(Container parent)
{
JViewport vp = (JViewport)parent;
Component view = vp.getView();
Scrollable scrollableView = null;
if (view == null) {
return;
}
else if (view instanceof Scrollable) {
scrollableView = (Scrollable) view;
}
/* All of the dimensions below are in view coordinates, except
* vpSize which we're converting.
*/
Insets insets = vp.getInsets();
Dimension viewPrefSize = view.getPreferredSize();
Dimension vpSize = vp.getSize();
Dimension extentSize = vp.toViewCoordinates(vpSize);
Dimension viewSize = new Dimension(viewPrefSize);
if (scrollableView != null) {
if (scrollableView.getScrollableTracksViewportWidth()) {
viewSize.width = vpSize.width;
}
if (scrollableView.getScrollableTracksViewportHeight()) {
viewSize.height = vpSize.height;
}
}
Point viewPosition = vp.getViewPosition();
/* If the new viewport size would leave empty space to the
* right of the view, right justify the view or left justify
* the view when the width of the view is smaller than the
* container.
*/
if (scrollableView == null ||
vp.getParent() == null ||
vp.getParent().getComponentOrientation().isLeftToRight()) {
if ((viewPosition.x + extentSize.width) > viewSize.width) {
viewPosition.x = Math.max(0, viewSize.width - extentSize.width);
}
} else {
if (extentSize.width > viewSize.width) {
viewPosition.x = viewSize.width - extentSize.width;
} else {
viewPosition.x = Math.max(0, Math.min(viewSize.width - extentSize.width, viewPosition.x));
}
}
/* If the new viewport size would leave empty space below the
* view, bottom justify the view or top justify the view when
* the height of the view is smaller than the container.
*/
if ((viewPosition.y + extentSize.height) > viewSize.height) {
viewPosition.y = Math.max(0, viewSize.height - extentSize.height);
}
/* If we haven't been advised about how the viewports size
* should change wrt to the viewport, i.e. if the view isn't
* an instance of Scrollable, then adjust the views size as follows.
*
* If the origin of the view is showing and the viewport is
* bigger than the views preferred size, then make the view
* the same size as the viewport.
*/
if (scrollableView == null) {
if ((viewPosition.x == 0) && (vpSize.width > viewPrefSize.width)) {
viewSize.width = vpSize.width;
}
if ((viewPosition.y == 0) && (vpSize.height > viewPrefSize.height)) {
viewSize.height = vpSize.height;
}
}
vp.setViewPosition(viewPosition);
vp.setViewSize(viewSize);
}
}
|
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.beans.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.IOException;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
/** {@collect.stats}
* A component that combines a button or editable field and a drop-down list.
* The user can select a value from the drop-down list, which appears at the
* user's request. If you make the combo box editable, then the combo box
* includes an editable field into which the user can type a value.
* <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}.
*
* <p>
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html">How to Use Combo Boxes</a>
* in <a href="http://java.sun.com/Series/Tutorial/index.html"><em>The Java Tutorial</em></a>
* for further information.
* <p>
* @see ComboBoxModel
* @see DefaultComboBoxModel
*
* @beaninfo
* attribute: isContainer false
* description: A combination of a text field and a drop-down list.
*
* @author Arnaud Weber
* @author Mark Davidson
*/
public class JComboBox extends JComponent
implements ItemSelectable,ListDataListener,ActionListener, Accessible {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ComboBoxUI";
/** {@collect.stats}
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #getModel
* @see #setModel
*/
protected ComboBoxModel dataModel;
/** {@collect.stats}
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #getRenderer
* @see #setRenderer
*/
protected ListCellRenderer renderer;
/** {@collect.stats}
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #getEditor
* @see #setEditor
*/
protected ComboBoxEditor editor;
/** {@collect.stats}
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #getMaximumRowCount
* @see #setMaximumRowCount
*/
protected int maximumRowCount = 8;
/** {@collect.stats}
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #isEditable
* @see #setEditable
*/
protected boolean isEditable = false;
/** {@collect.stats}
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #setKeySelectionManager
* @see #getKeySelectionManager
*/
protected KeySelectionManager keySelectionManager = null;
/** {@collect.stats}
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #setActionCommand
* @see #getActionCommand
*/
protected String actionCommand = "comboBoxChanged";
/** {@collect.stats}
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #setLightWeightPopupEnabled
* @see #isLightWeightPopupEnabled
*/
protected boolean lightWeightPopupEnabled = JPopupMenu.getDefaultLightWeightPopupEnabled();
/** {@collect.stats}
* This protected field is implementation specific. Do not access directly
* or override.
*/
protected Object selectedItemReminder = null;
private Object prototypeDisplayValue;
// Flag to ensure that infinite loops do not occur with ActionEvents.
private boolean firingActionEvent = false;
// Flag to ensure the we don't get multiple ActionEvents on item selection.
private boolean selectingItem = false;
/** {@collect.stats}
* Creates a <code>JComboBox</code> that takes its items from an
* existing <code>ComboBoxModel</code>. Since the
* <code>ComboBoxModel</code> is provided, a combo box created using
* this constructor does not create a default combo box model and
* may impact how the insert, remove and add methods behave.
*
* @param aModel the <code>ComboBoxModel</code> that provides the
* displayed list of items
* @see DefaultComboBoxModel
*/
public JComboBox(ComboBoxModel aModel) {
super();
setModel(aModel);
init();
}
/** {@collect.stats}
* Creates a <code>JComboBox</code> that contains the elements
* in the specified array. By default the first item in the array
* (and therefore the data model) becomes selected.
*
* @param items an array of objects to insert into the combo box
* @see DefaultComboBoxModel
*/
public JComboBox(final Object items[]) {
super();
setModel(new DefaultComboBoxModel(items));
init();
}
/** {@collect.stats}
* Creates a <code>JComboBox</code> that contains the elements
* in the specified Vector. By default the first item in the vector
* (and therefore the data model) becomes selected.
*
* @param items an array of vectors to insert into the combo box
* @see DefaultComboBoxModel
*/
public JComboBox(Vector<?> items) {
super();
setModel(new DefaultComboBoxModel(items));
init();
}
/** {@collect.stats}
* Creates a <code>JComboBox</code> with a default data model.
* The default data model is an empty list of objects.
* Use <code>addItem</code> to add items. By default the first item
* in the data model becomes selected.
*
* @see DefaultComboBoxModel
*/
public JComboBox() {
super();
setModel(new DefaultComboBoxModel());
init();
}
private void init() {
installAncestorListener();
setUIProperty("opaque",true);
updateUI();
}
protected void installAncestorListener() {
addAncestorListener(new AncestorListener(){
public void ancestorAdded(AncestorEvent event){ hidePopup();}
public void ancestorRemoved(AncestorEvent event){ hidePopup();}
public void ancestorMoved(AncestorEvent event){
if (event.getSource() != JComboBox.this)
hidePopup();
}});
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the <code>ComboBoxUI</code> 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(ComboBoxUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((ComboBoxUI)UIManager.getUI(this));
ListCellRenderer renderer = getRenderer();
if (renderer instanceof Component) {
SwingUtilities.updateComponentTreeUI((Component)renderer);
}
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "ComboBoxUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return the ComboBoxUI object that renders this component
*/
public ComboBoxUI getUI() {
return(ComboBoxUI)ui;
}
/** {@collect.stats}
* Sets the data model that the <code>JComboBox</code> uses to obtain
* the list of items.
*
* @param aModel the <code>ComboBoxModel</code> that provides the
* displayed list of items
*
* @beaninfo
* bound: true
* description: Model that the combo box uses to get data to display.
*/
public void setModel(ComboBoxModel aModel) {
ComboBoxModel oldModel = dataModel;
if (oldModel != null) {
oldModel.removeListDataListener(this);
}
dataModel = aModel;
dataModel.addListDataListener(this);
// set the current selected item.
selectedItemReminder = dataModel.getSelectedItem();
firePropertyChange( "model", oldModel, dataModel);
}
/** {@collect.stats}
* Returns the data model currently used by the <code>JComboBox</code>.
*
* @return the <code>ComboBoxModel</code> that provides the displayed
* list of items
*/
public ComboBoxModel getModel() {
return dataModel;
}
/*
* Properties
*/
/** {@collect.stats}
* Sets the <code>lightWeightPopupEnabled</code> property, which
* provides a hint as to whether or not a lightweight
* <code>Component</code> should be used to contain the
* <code>JComboBox</code>, versus a heavyweight
* <code>Component</code> such as a <code>Panel</code>
* or a <code>Window</code>. The decision of lightweight
* versus heavyweight is ultimately up to the
* <code>JComboBox</code>. Lightweight windows are more
* efficient than heavyweight windows, but lightweight
* and heavyweight components do not mix well in a GUI.
* If your application mixes lightweight and heavyweight
* components, you should disable lightweight popups.
* The default value for the <code>lightWeightPopupEnabled</code>
* property is <code>true</code>, unless otherwise specified
* by the look and feel. Some look and feels always use
* heavyweight popups, no matter what the value of this property.
* <p>
* See the article <a href="http://java.sun.com/products/jfc/tsc/articles/mixing/index.html">Mixing Heavy and Light Components</a>
* on <a href="http://java.sun.com/products/jfc/tsc">
* <em>The Swing Connection</em></a>
* This method fires a property changed event.
*
* @param aFlag if <code>true</code>, lightweight popups are desired
*
* @beaninfo
* bound: true
* expert: true
* description: Set to <code>false</code> to require heavyweight popups.
*/
public void setLightWeightPopupEnabled(boolean aFlag) {
boolean oldFlag = lightWeightPopupEnabled;
lightWeightPopupEnabled = aFlag;
firePropertyChange("lightWeightPopupEnabled", oldFlag, lightWeightPopupEnabled);
}
/** {@collect.stats}
* Gets the value of the <code>lightWeightPopupEnabled</code>
* property.
*
* @return the value of the <code>lightWeightPopupEnabled</code>
* property
* @see #setLightWeightPopupEnabled
*/
public boolean isLightWeightPopupEnabled() {
return lightWeightPopupEnabled;
}
/** {@collect.stats}
* Determines whether the <code>JComboBox</code> field is editable.
* An editable <code>JComboBox</code> allows the user to type into the
* field or selected an item from the list to initialize the field,
* after which it can be edited. (The editing affects only the field,
* the list item remains intact.) A non editable <code>JComboBox</code>
* displays the selected item in the field,
* but the selection cannot be modified.
*
* @param aFlag a boolean value, where true indicates that the
* field is editable
*
* @beaninfo
* bound: true
* preferred: true
* description: If true, the user can type a new value in the combo box.
*/
public void setEditable(boolean aFlag) {
boolean oldFlag = isEditable;
isEditable = aFlag;
firePropertyChange( "editable", oldFlag, isEditable );
}
/** {@collect.stats}
* Returns true if the <code>JComboBox</code> is editable.
* By default, a combo box is not editable.
*
* @return true if the <code>JComboBox</code> is editable, else false
*/
public boolean isEditable() {
return isEditable;
}
/** {@collect.stats}
* Sets the maximum number of rows the <code>JComboBox</code> displays.
* If the number of objects in the model is greater than count,
* the combo box uses a scrollbar.
*
* @param count an integer specifying the maximum number of items to
* display in the list before using a scrollbar
* @beaninfo
* bound: true
* preferred: true
* description: The maximum number of rows the popup should have
*/
public void setMaximumRowCount(int count) {
int oldCount = maximumRowCount;
maximumRowCount = count;
firePropertyChange( "maximumRowCount", oldCount, maximumRowCount );
}
/** {@collect.stats}
* Returns the maximum number of items the combo box can display
* without a scrollbar
*
* @return an integer specifying the maximum number of items that are
* displayed in the list before using a scrollbar
*/
public int getMaximumRowCount() {
return maximumRowCount;
}
/** {@collect.stats}
* Sets the renderer that paints the list items and the item selected from the list in
* the JComboBox field. The renderer is used if the JComboBox is not
* editable. If it is editable, the editor is used to render and edit
* the selected item.
* <p>
* The default renderer displays a string or an icon.
* Other renderers can handle graphic images and composite items.
* <p>
* To display the selected item,
* <code>aRenderer.getListCellRendererComponent</code>
* is called, passing the list object and an index of -1.
*
* @param aRenderer the <code>ListCellRenderer</code> that
* displays the selected item
* @see #setEditor
* @beaninfo
* bound: true
* expert: true
* description: The renderer that paints the item selected in the list.
*/
public void setRenderer(ListCellRenderer aRenderer) {
ListCellRenderer oldRenderer = renderer;
renderer = aRenderer;
firePropertyChange( "renderer", oldRenderer, renderer );
invalidate();
}
/** {@collect.stats}
* Returns the renderer used to display the selected item in the
* <code>JComboBox</code> field.
*
* @return the <code>ListCellRenderer</code> that displays
* the selected item.
*/
public ListCellRenderer getRenderer() {
return renderer;
}
/** {@collect.stats}
* Sets the editor used to paint and edit the selected item in the
* <code>JComboBox</code> field. The editor is used only if the
* receiving <code>JComboBox</code> is editable. If not editable,
* the combo box uses the renderer to paint the selected item.
*
* @param anEditor the <code>ComboBoxEditor</code> that
* displays the selected item
* @see #setRenderer
* @beaninfo
* bound: true
* expert: true
* description: The editor that combo box uses to edit the current value
*/
public void setEditor(ComboBoxEditor anEditor) {
ComboBoxEditor oldEditor = editor;
if ( editor != null ) {
editor.removeActionListener(this);
}
editor = anEditor;
if ( editor != null ) {
editor.addActionListener(this);
}
firePropertyChange( "editor", oldEditor, editor );
}
/** {@collect.stats}
* Returns the editor used to paint and edit the selected item in the
* <code>JComboBox</code> field.
*
* @return the <code>ComboBoxEditor</code> that displays the selected item
*/
public ComboBoxEditor getEditor() {
return editor;
}
//
// Selection
//
/** {@collect.stats}
* Sets the selected item in the combo box display area to the object in
* the argument.
* If <code>anObject</code> is in the list, the display area shows
* <code>anObject</code> selected.
* <p>
* If <code>anObject</code> is <i>not</i> in the list and the combo box is
* uneditable, it will not change the current selection. For editable
* combo boxes, the selection will change to <code>anObject</code>.
* <p>
* If this constitutes a change in the selected item,
* <code>ItemListener</code>s added to the combo box will be notified with
* one or two <code>ItemEvent</code>s.
* If there is a current selected item, an <code>ItemEvent</code> will be
* fired and the state change will be <code>ItemEvent.DESELECTED</code>.
* If <code>anObject</code> is in the list and is not currently selected
* then an <code>ItemEvent</code> will be fired and the state change will
* be <code>ItemEvent.SELECTED</code>.
* <p>
* <code>ActionListener</code>s added to the combo box will be notified
* with an <code>ActionEvent</code> when this method is called.
*
* @param anObject the list object to select; use <code>null</code> to
clear the selection
* @beaninfo
* preferred: true
* description: Sets the selected item in the JComboBox.
*/
public void setSelectedItem(Object anObject) {
Object oldSelection = selectedItemReminder;
Object objectToSelect = anObject;
if (oldSelection == null || !oldSelection.equals(anObject)) {
if (anObject != null && !isEditable()) {
// For non editable combo boxes, an invalid selection
// will be rejected.
boolean found = false;
for (int i = 0; i < dataModel.getSize(); i++) {
Object element = dataModel.getElementAt(i);
if (anObject.equals(element)) {
found = true;
objectToSelect = element;
break;
}
}
if (!found) {
return;
}
}
// Must toggle the state of this flag since this method
// call may result in ListDataEvents being fired.
selectingItem = true;
dataModel.setSelectedItem(objectToSelect);
selectingItem = false;
if (selectedItemReminder != dataModel.getSelectedItem()) {
// in case a users implementation of ComboBoxModel
// doesn't fire a ListDataEvent when the selection
// changes.
selectedItemChanged();
}
}
fireActionEvent();
}
/** {@collect.stats}
* Returns the current selected item.
* <p>
* If the combo box is editable, then this value may not have been added
* to the combo box with <code>addItem</code>, <code>insertItemAt</code>
* or the data constructors.
*
* @return the current selected Object
* @see #setSelectedItem
*/
public Object getSelectedItem() {
return dataModel.getSelectedItem();
}
/** {@collect.stats}
* Selects the item at index <code>anIndex</code>.
*
* @param anIndex an integer specifying the list item to select,
* where 0 specifies the first item in the list and -1 indicates no selection
* @exception IllegalArgumentException if <code>anIndex</code> < -1 or
* <code>anIndex</code> is greater than or equal to size
* @beaninfo
* preferred: true
* description: The item at index is selected.
*/
public void setSelectedIndex(int anIndex) {
int size = dataModel.getSize();
if ( anIndex == -1 ) {
setSelectedItem( null );
} else if ( anIndex < -1 || anIndex >= size ) {
throw new IllegalArgumentException("setSelectedIndex: " + anIndex + " out of bounds");
} else {
setSelectedItem(dataModel.getElementAt(anIndex));
}
}
/** {@collect.stats}
* Returns the first item in the list that matches the given item.
* The result is not always defined if the <code>JComboBox</code>
* allows selected items that are not in the list.
* Returns -1 if there is no selected item or if the user specified
* an item which is not in the list.
* @return an integer specifying the currently selected list item,
* where 0 specifies
* the first item in the list;
* or -1 if no item is selected or if
* the currently selected item is not in the list
*/
public int getSelectedIndex() {
Object sObject = dataModel.getSelectedItem();
int i,c;
Object obj;
for ( i=0,c=dataModel.getSize();i<c;i++ ) {
obj = dataModel.getElementAt(i);
if ( obj != null && obj.equals(sObject) )
return i;
}
return -1;
}
/** {@collect.stats}
* Returns the "prototypical display" value - an Object used
* for the calculation of the display height and width.
*
* @return the value of the <code>prototypeDisplayValue</code> property
* @see #setPrototypeDisplayValue
* @since 1.4
*/
public Object getPrototypeDisplayValue() {
return prototypeDisplayValue;
}
/** {@collect.stats}
* Sets the prototype display value used to calculate the size of the display
* for the UI portion.
* <p>
* If a prototype display value is specified, the preferred size of
* the combo box is calculated by configuring the renderer with the
* prototype display value and obtaining its preferred size. Specifying
* the preferred display value is often useful when the combo box will be
* displaying large amounts of data. If no prototype display value has
* been specified, the renderer must be configured for each value from
* the model and its preferred size obtained, which can be
* relatively expensive.
*
* @param prototypeDisplayValue
* @see #getPrototypeDisplayValue
* @since 1.4
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The display prototype value, used to compute display width and height.
*/
public void setPrototypeDisplayValue(Object prototypeDisplayValue) {
Object oldValue = this.prototypeDisplayValue;
this.prototypeDisplayValue = prototypeDisplayValue;
firePropertyChange("prototypeDisplayValue", oldValue, prototypeDisplayValue);
}
/** {@collect.stats}
* Adds an item to the item list.
* This method works only if the <code>JComboBox</code> uses a
* mutable data model.
* <p>
* <strong>Warning:</strong>
* Focus and keyboard navigation problems may arise if you add duplicate
* String objects. A workaround is to add new objects instead of String
* objects and make sure that the toString() method is defined.
* For example:
* <pre>
* comboBox.addItem(makeObj("Item 1"));
* comboBox.addItem(makeObj("Item 1"));
* ...
* private Object makeObj(final String item) {
* return new Object() { public String toString() { return item; } };
* }
* </pre>
*
* @param anObject the Object to add to the list
* @see MutableComboBoxModel
*/
public void addItem(Object anObject) {
checkMutableComboBoxModel();
((MutableComboBoxModel)dataModel).addElement(anObject);
}
/** {@collect.stats}
* Inserts an item into the item list at a given index.
* This method works only if the <code>JComboBox</code> uses a
* mutable data model.
*
* @param anObject the <code>Object</code> to add to the list
* @param index an integer specifying the position at which
* to add the item
* @see MutableComboBoxModel
*/
public void insertItemAt(Object anObject, int index) {
checkMutableComboBoxModel();
((MutableComboBoxModel)dataModel).insertElementAt(anObject,index);
}
/** {@collect.stats}
* Removes an item from the item list.
* This method works only if the <code>JComboBox</code> uses a
* mutable data model.
*
* @param anObject the object to remove from the item list
* @see MutableComboBoxModel
*/
public void removeItem(Object anObject) {
checkMutableComboBoxModel();
((MutableComboBoxModel)dataModel).removeElement(anObject);
}
/** {@collect.stats}
* Removes the item at <code>anIndex</code>
* This method works only if the <code>JComboBox</code> uses a
* mutable data model.
*
* @param anIndex an int specifying the index of the item to remove,
* where 0
* indicates the first item in the list
* @see MutableComboBoxModel
*/
public void removeItemAt(int anIndex) {
checkMutableComboBoxModel();
((MutableComboBoxModel)dataModel).removeElementAt( anIndex );
}
/** {@collect.stats}
* Removes all items from the item list.
*/
public void removeAllItems() {
checkMutableComboBoxModel();
MutableComboBoxModel model = (MutableComboBoxModel)dataModel;
int size = model.getSize();
if ( model instanceof DefaultComboBoxModel ) {
((DefaultComboBoxModel)model).removeAllElements();
}
else {
for ( int i = 0; i < size; ++i ) {
Object element = model.getElementAt( 0 );
model.removeElement( element );
}
}
selectedItemReminder = null;
if (isEditable()) {
editor.setItem(null);
}
}
/** {@collect.stats}
* Checks that the <code>dataModel</code> is an instance of
* <code>MutableComboBoxModel</code>. If not, it throws an exception.
* @exception RuntimeException if <code>dataModel</code> is not an
* instance of <code>MutableComboBoxModel</code>.
*/
void checkMutableComboBoxModel() {
if ( !(dataModel instanceof MutableComboBoxModel) )
throw new RuntimeException("Cannot use this method with a non-Mutable data model.");
}
/** {@collect.stats}
* Causes the combo box to display its popup window.
* @see #setPopupVisible
*/
public void showPopup() {
setPopupVisible(true);
}
/** {@collect.stats}
* Causes the combo box to close its popup window.
* @see #setPopupVisible
*/
public void hidePopup() {
setPopupVisible(false);
}
/** {@collect.stats}
* Sets the visibility of the popup.
*/
public void setPopupVisible(boolean v) {
getUI().setPopupVisible(this, v);
}
/** {@collect.stats}
* Determines the visibility of the popup.
*
* @return true if the popup is visible, otherwise returns false
*/
public boolean isPopupVisible() {
return getUI().isPopupVisible(this);
}
/** {@collect.stats} Selection **/
/** {@collect.stats}
* Adds an <code>ItemListener</code>.
* <p>
* <code>aListener</code> will receive one or two <code>ItemEvent</code>s when
* the selected item changes.
*
* @param aListener the <code>ItemListener</code> that is to be notified
* @see #setSelectedItem
*/
public void addItemListener(ItemListener aListener) {
listenerList.add(ItemListener.class,aListener);
}
/** {@collect.stats} Removes an <code>ItemListener</code>.
*
* @param aListener the <code>ItemListener</code> to remove
*/
public void removeItemListener(ItemListener aListener) {
listenerList.remove(ItemListener.class,aListener);
}
/** {@collect.stats}
* Returns an array of all the <code>ItemListener</code>s added
* to this JComboBox with addItemListener().
*
* @return all of the <code>ItemListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ItemListener[] getItemListeners() {
return (ItemListener[])listenerList.getListeners(ItemListener.class);
}
/** {@collect.stats}
* Adds an <code>ActionListener</code>.
* <p>
* The <code>ActionListener</code> will receive an <code>ActionEvent</code>
* when a selection has been made. If the combo box is editable, then
* an <code>ActionEvent</code> will be fired when editing has stopped.
*
* @param l the <code>ActionListener</code> that is to be notified
* @see #setSelectedItem
*/
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class,l);
}
/** {@collect.stats} Removes an <code>ActionListener</code>.
*
* @param l the <code>ActionListener</code> to remove
*/
public 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 JComboBox 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 ActionListener[] getActionListeners() {
return (ActionListener[])listenerList.getListeners(
ActionListener.class);
}
/** {@collect.stats}
* Adds a <code>PopupMenu</code> listener which will listen to notification
* messages from the popup portion of the combo box.
* <p>
* For all standard look and feels shipped with Java, the popup list
* portion of combo box is implemented as a <code>JPopupMenu</code>.
* A custom look and feel may not implement it this way and will
* therefore not receive the notification.
*
* @param l the <code>PopupMenuListener</code> to add
* @since 1.4
*/
public void addPopupMenuListener(PopupMenuListener l) {
listenerList.add(PopupMenuListener.class,l);
}
/** {@collect.stats}
* Removes a <code>PopupMenuListener</code>.
*
* @param l the <code>PopupMenuListener</code> to remove
* @see #addPopupMenuListener
* @since 1.4
*/
public void removePopupMenuListener(PopupMenuListener l) {
listenerList.remove(PopupMenuListener.class,l);
}
/** {@collect.stats}
* Returns an array of all the <code>PopupMenuListener</code>s added
* to this JComboBox with addPopupMenuListener().
*
* @return all of the <code>PopupMenuListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public PopupMenuListener[] getPopupMenuListeners() {
return (PopupMenuListener[])listenerList.getListeners(
PopupMenuListener.class);
}
/** {@collect.stats}
* Notifies <code>PopupMenuListener</code>s that the popup portion of the
* combo box will become visible.
* <p>
* This method is public but should not be called by anything other than
* the UI delegate.
* @see #addPopupMenuListener
* @since 1.4
*/
public void firePopupMenuWillBecomeVisible() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e=null;
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener)listeners[i+1]).popupMenuWillBecomeVisible(e);
}
}
}
/** {@collect.stats}
* Notifies <code>PopupMenuListener</code>s that the popup portion of the
* combo box has become invisible.
* <p>
* This method is public but should not be called by anything other than
* the UI delegate.
* @see #addPopupMenuListener
* @since 1.4
*/
public void firePopupMenuWillBecomeInvisible() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e=null;
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener)listeners[i+1]).popupMenuWillBecomeInvisible(e);
}
}
}
/** {@collect.stats}
* Notifies <code>PopupMenuListener</code>s that the popup portion of the
* combo box has been canceled.
* <p>
* This method is public but should not be called by anything other than
* the UI delegate.
* @see #addPopupMenuListener
* @since 1.4
*/
public void firePopupMenuCanceled() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e=null;
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener)listeners[i+1]).popupMenuCanceled(e);
}
}
}
/** {@collect.stats}
* Sets the action command that should be included in the event
* sent to action listeners.
*
* @param aCommand a string containing the "command" that is sent
* to action listeners; the same listener can then
* do different things depending on the command it
* receives
*/
public void setActionCommand(String aCommand) {
actionCommand = aCommand;
}
/** {@collect.stats}
* Returns the action command that is included in the event sent to
* action listeners.
*
* @return the string containing the "command" that is sent
* to action listeners.
*/
public String getActionCommand() {
return actionCommand;
}
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 combobox'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 combobox'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>JComboBox</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 combobox 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}
* 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 combobox will be tied to
* that of the <code>Action</code>.
*
* @param a the combobox's action
* @since 1.3
* @see Action
* @see #setAction
*/
protected PropertyChangeListener createActionPropertyChangeListener(Action a) {
return new ComboBoxActionPropertyChangeListener(this, a);
}
/** {@collect.stats}
* Updates the combobox'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 combobox
* @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 (Action.SHORT_DESCRIPTION == propertyName) {
AbstractAction.setToolTipTextFromAction(this, action);
}
}
private void setActionCommandFromAction(Action a) {
setActionCommand((a != null) ?
(String)a.getValue(Action.ACTION_COMMAND_KEY) :
null);
}
private static class ComboBoxActionPropertyChangeListener
extends ActionPropertyChangeListener<JComboBox> {
ComboBoxActionPropertyChangeListener(JComboBox b, Action a) {
super(b, a);
}
protected void actionPropertyChanged(JComboBox cb,
Action action,
PropertyChangeEvent e) {
if (AbstractAction.shouldReconfigure(e)) {
cb.configurePropertiesFromAction(action);
} else {
cb.actionPropertyChanged(action, e.getPropertyName());
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
* @param e the event of interest
*
* @see EventListenerList
*/
protected void fireItemStateChanged(ItemEvent 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]==ItemListener.class ) {
// Lazily create the event:
// if (changeEvent == null)
// changeEvent = new ChangeEvent(this);
((ItemListener)listeners[i+1]).itemStateChanged(e);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @see EventListenerList
*/
protected void fireActionEvent() {
if (!firingActionEvent) {
// Set flag to ensure that an infinite loop is not created
firingActionEvent = true;
ActionEvent e = null;
// 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();
}
// 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,
getActionCommand(),
mostRecentEventTime, modifiers);
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
firingActionEvent = false;
}
}
/** {@collect.stats}
* This protected method is implementation specific. Do not access directly
* or override.
*/
protected void selectedItemChanged() {
if (selectedItemReminder != null ) {
fireItemStateChanged(new ItemEvent(this,ItemEvent.ITEM_STATE_CHANGED,
selectedItemReminder,
ItemEvent.DESELECTED));
}
// set the new selected item.
selectedItemReminder = dataModel.getSelectedItem();
if (selectedItemReminder != null ) {
fireItemStateChanged(new ItemEvent(this,ItemEvent.ITEM_STATE_CHANGED,
selectedItemReminder,
ItemEvent.SELECTED));
}
}
/** {@collect.stats}
* Returns an array containing the selected item.
* This method is implemented for compatibility with
* <code>ItemSelectable</code>.
*
* @return an array of <code>Objects</code> containing one
* element -- the selected item
*/
public Object[] getSelectedObjects() {
Object selectedObject = getSelectedItem();
if ( selectedObject == null )
return new Object[0];
else {
Object result[] = new Object[1];
result[0] = selectedObject;
return result;
}
}
/** {@collect.stats}
* This method is public as an implementation side effect.
* do not call or override.
*/
public void actionPerformed(ActionEvent e) {
Object newItem = getEditor().getItem();
setPopupVisible(false);
getModel().setSelectedItem(newItem);
String oldCommand = getActionCommand();
setActionCommand("comboBoxEdited");
fireActionEvent();
setActionCommand(oldCommand);
}
/** {@collect.stats}
* This method is public as an implementation side effect.
* do not call or override.
*/
public void contentsChanged(ListDataEvent e) {
Object oldSelection = selectedItemReminder;
Object newSelection = dataModel.getSelectedItem();
if (oldSelection == null || !oldSelection.equals(newSelection)) {
selectedItemChanged();
if (!selectingItem) {
fireActionEvent();
}
}
}
/** {@collect.stats}
* This method is public as an implementation side effect.
* do not call or override.
*/
public void intervalAdded(ListDataEvent e) {
if (selectedItemReminder != dataModel.getSelectedItem()) {
selectedItemChanged();
}
}
/** {@collect.stats}
* This method is public as an implementation side effect.
* do not call or override.
*/
public void intervalRemoved(ListDataEvent e) {
contentsChanged(e);
}
/** {@collect.stats}
* Selects the list item that corresponds to the specified keyboard
* character and returns true, if there is an item corresponding
* to that character. Otherwise, returns false.
*
* @param keyChar a char, typically this is a keyboard key
* typed by the user
*/
public boolean selectWithKeyChar(char keyChar) {
int index;
if ( keySelectionManager == null )
keySelectionManager = createDefaultKeySelectionManager();
index = keySelectionManager.selectionForKey(keyChar,getModel());
if ( index != -1 ) {
setSelectedIndex(index);
return true;
}
else
return false;
}
/** {@collect.stats}
* Enables the combo box so that items can be selected. When the
* combo box is disabled, items cannot be selected and values
* cannot be typed into its field (if it is editable).
*
* @param b a boolean value, where true enables the component and
* false disables it
* @beaninfo
* bound: true
* preferred: true
* description: Whether the combo box is enabled.
*/
public void setEnabled(boolean b) {
super.setEnabled(b);
firePropertyChange( "enabled", !isEnabled(), isEnabled() );
}
/** {@collect.stats}
* Initializes the editor with the specified item.
*
* @param anEditor the <code>ComboBoxEditor</code> that displays
* the list item in the
* combo box field and allows it to be edited
* @param anItem the object to display and edit in the field
*/
public void configureEditor(ComboBoxEditor anEditor, Object anItem) {
anEditor.setItem(anItem);
}
/** {@collect.stats}
* Handles <code>KeyEvent</code>s, looking for the Tab key.
* If the Tab key is found, the popup window is closed.
*
* @param e the <code>KeyEvent</code> containing the keyboard
* key that was pressed
*/
public void processKeyEvent(KeyEvent e) {
if ( e.getKeyCode() == KeyEvent.VK_TAB ) {
hidePopup();
}
super.processKeyEvent(e);
}
/** {@collect.stats}
* Sets the object that translates a keyboard character into a list
* selection. Typically, the first selection with a matching first
* character becomes the selected item.
*
* @beaninfo
* expert: true
* description: The objects that changes the selection when a key is pressed.
*/
public void setKeySelectionManager(KeySelectionManager aManager) {
keySelectionManager = aManager;
}
/** {@collect.stats}
* Returns the list's key-selection manager.
*
* @return the <code>KeySelectionManager</code> currently in use
*/
public KeySelectionManager getKeySelectionManager() {
return keySelectionManager;
}
/* Accessing the model */
/** {@collect.stats}
* Returns the number of items in the list.
*
* @return an integer equal to the number of items in the list
*/
public int getItemCount() {
return dataModel.getSize();
}
/** {@collect.stats}
* Returns the list item at the specified index. If <code>index</code>
* is out of range (less than zero or greater than or equal to size)
* it will return <code>null</code>.
*
* @param index an integer indicating the list position, where the first
* item starts at zero
* @return the <code>Object</code> at that list position; or
* <code>null</code> if out of range
*/
public Object getItemAt(int index) {
return dataModel.getElementAt(index);
}
/** {@collect.stats}
* Returns an instance of the default key-selection manager.
*
* @return the <code>KeySelectionManager</code> currently used by the list
* @see #setKeySelectionManager
*/
protected KeySelectionManager createDefaultKeySelectionManager() {
return new DefaultKeySelectionManager();
}
/** {@collect.stats}
* The interface that defines a <code>KeySelectionManager</code>.
* To qualify as a <code>KeySelectionManager</code>,
* the class needs to implement the method
* that identifies the list index given a character and the
* combo box data model.
*/
public interface KeySelectionManager {
/** {@collect.stats} Given <code>aKey</code> and the model, returns the row
* that should become selected. Return -1 if no match was
* found.
*
* @param aKey a char value, usually indicating a keyboard key that
* was pressed
* @param aModel a ComboBoxModel -- the component's data model, containing
* the list of selectable items
* @return an int equal to the selected row, where 0 is the
* first item and -1 is none.
*/
int selectionForKey(char aKey,ComboBoxModel aModel);
}
class DefaultKeySelectionManager implements KeySelectionManager, Serializable {
public int selectionForKey(char aKey,ComboBoxModel aModel) {
int i,c;
int currentSelection = -1;
Object selectedItem = aModel.getSelectedItem();
String v;
String pattern;
if ( selectedItem != null ) {
for ( i=0,c=aModel.getSize();i<c;i++ ) {
if ( selectedItem == aModel.getElementAt(i) ) {
currentSelection = i;
break;
}
}
}
pattern = ("" + aKey).toLowerCase();
aKey = pattern.charAt(0);
for ( i = ++currentSelection, c = aModel.getSize() ; i < c ; i++ ) {
Object elem = aModel.getElementAt(i);
if (elem != null && elem.toString() != null) {
v = elem.toString().toLowerCase();
if ( v.length() > 0 && v.charAt(0) == aKey )
return i;
}
}
for ( i = 0 ; i < currentSelection ; i ++ ) {
Object elem = aModel.getElementAt(i);
if (elem != null && elem.toString() != null) {
v = elem.toString().toLowerCase();
if ( v.length() > 0 && v.charAt(0) == aKey )
return i;
}
}
return -1;
}
}
/** {@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>JComboBox</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>JComboBox</code>
*/
protected String paramString() {
String selectedItemReminderString = (selectedItemReminder != null ?
selectedItemReminder.toString() :
"");
String isEditableString = (isEditable ? "true" : "false");
String lightWeightPopupEnabledString = (lightWeightPopupEnabled ?
"true" : "false");
return super.paramString() +
",isEditable=" + isEditableString +
",lightWeightPopupEnabled=" + lightWeightPopupEnabledString +
",maximumRowCount=" + maximumRowCount +
",selectedItemReminder=" + selectedItemReminderString;
}
///////////////////
// Accessibility support
///////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JComboBox.
* For combo boxes, the AccessibleContext takes the form of an
* AccessibleJComboBox.
* A new AccessibleJComboBox instance is created if necessary.
*
* @return an AccessibleJComboBox that serves as the
* AccessibleContext of this JComboBox
*/
public AccessibleContext getAccessibleContext() {
if ( accessibleContext == null ) {
accessibleContext = new AccessibleJComboBox();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JComboBox</code> class. It provides an implementation of the
* Java Accessibility API appropriate to Combo 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 AccessibleJComboBox extends AccessibleJComponent
implements AccessibleAction, AccessibleSelection {
private JList popupList; // combo box popup list
private Accessible previousSelectedAccessible = null;
/** {@collect.stats}
* Returns an AccessibleJComboBox instance
* @since 1.4
*/
public AccessibleJComboBox() {
// set the combo box editor's accessible name and description
JComboBox.this.addPropertyChangeListener(new AccessibleJComboBoxPropertyChangeListener());
setEditorNameAndDescription();
// Get the popup list
Accessible a = getUI().getAccessibleChild(JComboBox.this, 0);
if (a instanceof javax.swing.plaf.basic.ComboPopup) {
// Listen for changes to the popup menu selection.
popupList = ((javax.swing.plaf.basic.ComboPopup)a).getList();
popupList.addListSelectionListener(
new AccessibleJComboBoxListSelectionListener());
}
// Listen for popup menu show/hide events
JComboBox.this.addPopupMenuListener(
new AccessibleJComboBoxPopupMenuListener());
}
/*
* JComboBox PropertyChangeListener
*/
private class AccessibleJComboBoxPropertyChangeListener
implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName() == "editor") {
// set the combo box editor's accessible name
// and description
setEditorNameAndDescription();
}
}
}
/*
* Sets the combo box editor's accessible name and descripton
*/
private void setEditorNameAndDescription() {
ComboBoxEditor editor = JComboBox.this.getEditor();
if (editor != null) {
Component comp = editor.getEditorComponent();
if (comp instanceof Accessible) {
AccessibleContext ac = ((Accessible)comp).getAccessibleContext();
if (ac != null) { // may be null
ac.setAccessibleName(getAccessibleName());
ac.setAccessibleDescription(getAccessibleDescription());
}
}
}
}
/*
* Listener for combo box popup menu
* TIGER - 4669379 4894434
*/
private class AccessibleJComboBoxPopupMenuListener
implements PopupMenuListener {
/** {@collect.stats}
* This method is called before the popup menu becomes visible
*/
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// save the initial selection
if (popupList == null) {
return;
}
int selectedIndex = popupList.getSelectedIndex();
if (selectedIndex < 0) {
return;
}
previousSelectedAccessible =
popupList.getAccessibleContext().getAccessibleChild(selectedIndex);
}
/** {@collect.stats}
* This method is called before the popup menu becomes invisible
* Note that a JPopupMenu can become invisible any time
*/
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
// ignore
}
/** {@collect.stats}
* This method is called when the popup menu is canceled
*/
public void popupMenuCanceled(PopupMenuEvent e) {
// ignore
}
}
/*
* Handles changes to the popup list selection.
* TIGER - 4669379 4894434 4933143
*/
private class AccessibleJComboBoxListSelectionListener
implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
if (popupList == null) {
return;
}
// Get the selected popup list item.
int selectedIndex = popupList.getSelectedIndex();
if (selectedIndex < 0) {
return;
}
Accessible selectedAccessible =
popupList.getAccessibleContext().getAccessibleChild(selectedIndex);
if (selectedAccessible == null) {
return;
}
// Fire a FOCUSED lost PropertyChangeEvent for the
// previously selected list item.
PropertyChangeEvent pce = null;
if (previousSelectedAccessible != null) {
pce = new PropertyChangeEvent(previousSelectedAccessible,
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.FOCUSED, null);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, pce);
}
// Fire a FOCUSED gained PropertyChangeEvent for the
// currently selected list item.
pce = new PropertyChangeEvent(selectedAccessible,
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.FOCUSED);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, pce);
// Fire the ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY event
// for the combo box.
firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
previousSelectedAccessible, selectedAccessible);
// Save the previous selection.
previousSelectedAccessible = selectedAccessible;
}
}
/** {@collect.stats}
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
// Always delegate to the UI if it exists
if (ui != null) {
return ui.getAccessibleChildrenCount(JComboBox.this);
} else {
return super.getAccessibleChildrenCount();
}
}
/** {@collect.stats}
* Returns the nth Accessible child of the object.
* The child at index zero represents the popup.
* If the combo box is editable, the child at index one
* represents the editor.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
// Always delegate to the UI if it exists
if (ui != null) {
return ui.getAccessibleChild(JComboBox.this, i);
} else {
return super.getAccessibleChild(i);
}
}
/** {@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.COMBO_BOX;
}
/** {@collect.stats}
* Gets the state set of this object. The AccessibleStateSet of
* an object is composed of a set of unique AccessibleStates.
* A change in the AccessibleStateSet of an object will cause a
* PropertyChangeEvent to be fired for the ACCESSIBLE_STATE_PROPERTY
* property.
*
* @return an instance of AccessibleStateSet containing the
* current state set of the object
* @see AccessibleStateSet
* @see AccessibleState
* @see #addPropertyChangeListener
*
*/
public AccessibleStateSet getAccessibleStateSet() {
// TIGER - 4489748
AccessibleStateSet ass = super.getAccessibleStateSet();
if (ass == null) {
ass = new AccessibleStateSet();
}
if (JComboBox.this.isPopupVisible()) {
ass.add(AccessibleState.EXPANDED);
} else {
ass.add(AccessibleState.COLLAPSED);
}
return ass;
}
/** {@collect.stats}
* Get the AccessibleAction associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleAction interface on behalf of itself.
*
* @return this object
*/
public AccessibleAction getAccessibleAction() {
return this;
}
/** {@collect.stats}
* Return a description of the specified action of the object.
*
* @param i zero-based index of the actions
*/
public String getAccessibleActionDescription(int i) {
if (i == 0) {
return UIManager.getString("ComboBox.togglePopupText");
}
else {
return null;
}
}
/** {@collect.stats}
* Returns the number of Actions available in this object. The
* default behavior of a combo box is to have one action.
*
* @return 1, the 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.
*/
public boolean doAccessibleAction(int i) {
if (i == 0) {
setPopupVisible(!isPopupVisible());
return true;
}
else {
return false;
}
}
/** {@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 the number of Accessible children currently selected.
* If no children are selected, the return value will be 0.
*
* @return the number of items currently selected.
* @since 1.3
*/
public int getAccessibleSelectionCount() {
Object o = JComboBox.this.getSelectedItem();
if (o != null) {
return 1;
} else {
return 0;
}
}
/** {@collect.stats}
* Returns an Accessible representing the specified selected child
* in the popup. If there isn't a selection, or there are
* fewer children selected than the integer passed in, the return
* value will be null.
* <p>Note that the index represents the i-th selected child, which
* is different from the i-th child.
*
* @param i the zero-based index of selected children
* @return the i-th selected child
* @see #getAccessibleSelectionCount
* @since 1.3
*/
public Accessible getAccessibleSelection(int i) {
// Get the popup
Accessible a =
JComboBox.this.getUI().getAccessibleChild(JComboBox.this, 0);
if (a != null &&
a instanceof javax.swing.plaf.basic.ComboPopup) {
// get the popup list
JList list = ((javax.swing.plaf.basic.ComboPopup)a).getList();
// return the i-th selection in the popup list
AccessibleContext ac = list.getAccessibleContext();
if (ac != null) {
AccessibleSelection as = ac.getAccessibleSelection();
if (as != null) {
return as.getAccessibleSelection(i);
}
}
}
return null;
}
/** {@collect.stats}
* Determines if the current child of this object is selected.
*
* @return true if the current child of this object is selected;
* else false
* @param i the zero-based index of the child in this Accessible
* object.
* @see AccessibleContext#getAccessibleChild
* @since 1.3
*/
public boolean isAccessibleChildSelected(int i) {
return JComboBox.this.getSelectedIndex() == i;
}
/** {@collect.stats}
* Adds the specified Accessible child of the object to the object's
* selection. If the object supports multiple selections,
* the specified child is added to any existing selection, otherwise
* it replaces any existing selection in the object. If the
* specified child is already selected, this method has no effect.
*
* @param i the zero-based index of the child
* @see AccessibleContext#getAccessibleChild
* @since 1.3
*/
public void addAccessibleSelection(int i) {
// TIGER - 4856195
clearAccessibleSelection();
JComboBox.this.setSelectedIndex(i);
}
/** {@collect.stats}
* Removes the specified child of the object from the object's
* selection. If the specified item isn't currently selected, this
* method has no effect.
*
* @param i the zero-based index of the child
* @see AccessibleContext#getAccessibleChild
* @since 1.3
*/
public void removeAccessibleSelection(int i) {
if (JComboBox.this.getSelectedIndex() == i) {
clearAccessibleSelection();
}
}
/** {@collect.stats}
* Clears the selection in the object, so that no children in the
* object are selected.
* @since 1.3
*/
public void clearAccessibleSelection() {
JComboBox.this.setSelectedIndex(-1);
}
/** {@collect.stats}
* Causes every child of the object to be selected
* if the object supports multiple selections.
* @since 1.3
*/
public void selectAllAccessibleSelection() {
// do nothing since multiple selection is not supported
}
// public Accessible getAccessibleAt(Point p) {
// Accessible a = getAccessibleChild(1);
// if ( a != null ) {
// return a; // the editor
// }
// else {
// return getAccessibleChild(0); // the list
// }
// }
private EditorAccessibleContext editorAccessibleContext = null;
private class AccessibleEditor implements Accessible {
public AccessibleContext getAccessibleContext() {
if (editorAccessibleContext == null) {
Component c = JComboBox.this.getEditor().getEditorComponent();
if (c instanceof Accessible) {
editorAccessibleContext =
new EditorAccessibleContext((Accessible)c);
}
}
return editorAccessibleContext;
}
}
/*
* Wrapper class for the AccessibleContext implemented by the
* combo box editor. Delegates all method calls except
* getAccessibleIndexInParent to the editor. The
* getAccessibleIndexInParent method returns the selected
* index in the combo box.
*/
private class EditorAccessibleContext extends AccessibleContext {
private AccessibleContext ac;
private EditorAccessibleContext() {
}
/*
* @param a the AccessibleContext implemented by the
* combo box editor
*/
EditorAccessibleContext(Accessible a) {
this.ac = a.getAccessibleContext();
}
/** {@collect.stats}
* Gets the accessibleName property of this object. The accessibleName
* property of an object is a localized String that designates the purpose
* of the object. For example, the accessibleName property of a label
* or button might be the text of the label or button itself. In the
* case of an object that doesn't display its name, the accessibleName
* should still be set. For example, in the case of a text field used
* to enter the name of a city, the accessibleName for the en_US locale
* could be 'city.'
*
* @return the localized name of the object; null if this
* object does not have a name
*
* @see #setAccessibleName
*/
public String getAccessibleName() {
return ac.getAccessibleName();
}
/** {@collect.stats}
* Sets the localized accessible name of this object. Changing the
* name will cause a PropertyChangeEvent to be fired for the
* ACCESSIBLE_NAME_PROPERTY property.
*
* @param s the new localized name of the object.
*
* @see #getAccessibleName
* @see #addPropertyChangeListener
*
* @beaninfo
* preferred: true
* description: Sets the accessible name for the component.
*/
public void setAccessibleName(String s) {
ac.setAccessibleName(s);
}
/** {@collect.stats}
* Gets the accessibleDescription property of this object. The
* accessibleDescription property of this object is a short localized
* phrase describing the purpose of the object. For example, in the
* case of a 'Cancel' button, the accessibleDescription could be
* 'Ignore changes and close dialog box.'
*
* @return the localized description of the object; null if
* this object does not have a description
*
* @see #setAccessibleDescription
*/
public String getAccessibleDescription() {
return ac.getAccessibleDescription();
}
/** {@collect.stats}
* Sets the accessible description of this object. Changing the
* name will cause a PropertyChangeEvent to be fired for the
* ACCESSIBLE_DESCRIPTION_PROPERTY property.
*
* @param s the new localized description of the object
*
* @see #setAccessibleName
* @see #addPropertyChangeListener
*
* @beaninfo
* preferred: true
* description: Sets the accessible description for the component.
*/
public void setAccessibleDescription(String s) {
ac.setAccessibleDescription(s);
}
/** {@collect.stats}
* Gets the role of this object. The role of the object is the generic
* purpose or use of the class of this object. For example, the role
* of a push button is AccessibleRole.PUSH_BUTTON. The roles in
* AccessibleRole are provided so component developers can pick from
* a set of predefined roles. This enables assistive technologies to
* provide a consistent interface to various tweaked subclasses of
* components (e.g., use AccessibleRole.PUSH_BUTTON for all components
* that act like a push button) as well as distinguish between sublasses
* that behave differently (e.g., AccessibleRole.CHECK_BOX for check boxes
* and AccessibleRole.RADIO_BUTTON for radio buttons).
* <p>Note that the AccessibleRole class is also extensible, so
* custom component developers can define their own AccessibleRole's
* if the set of predefined roles is inadequate.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return ac.getAccessibleRole();
}
/** {@collect.stats}
* Gets the state set of this object. The AccessibleStateSet of an object
* is composed of a set of unique AccessibleStates. A change in the
* AccessibleStateSet of an object will cause a PropertyChangeEvent to
* be fired for the ACCESSIBLE_STATE_PROPERTY property.
*
* @return an instance of AccessibleStateSet containing the
* current state set of the object
* @see AccessibleStateSet
* @see AccessibleState
* @see #addPropertyChangeListener
*/
public AccessibleStateSet getAccessibleStateSet() {
return ac.getAccessibleStateSet();
}
/** {@collect.stats}
* Gets the Accessible parent of this object.
*
* @return the Accessible parent of this object; null if this
* object does not have an Accessible parent
*/
public Accessible getAccessibleParent() {
return ac.getAccessibleParent();
}
/** {@collect.stats}
* Sets the Accessible parent of this object. This is meant to be used
* only in the situations where the actual component's parent should
* not be treated as the component's accessible parent and is a method
* that should only be called by the parent of the accessible child.
*
* @param a - Accessible to be set as the parent
*/
public void setAccessibleParent(Accessible a) {
ac.setAccessibleParent(a);
}
/** {@collect.stats}
* Gets the 0-based index of this object in its accessible parent.
*
* @return the 0-based index of this object in its parent; -1 if this
* object does not have an accessible parent.
*
* @see #getAccessibleParent
* @see #getAccessibleChildrenCount
* @see #getAccessibleChild
*/
public int getAccessibleIndexInParent() {
return JComboBox.this.getSelectedIndex();
}
/** {@collect.stats}
* Returns the number of accessible children of the object.
*
* @return the number of accessible children of the object.
*/
public int getAccessibleChildrenCount() {
return ac.getAccessibleChildrenCount();
}
/** {@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) {
return ac.getAccessibleChild(i);
}
/** {@collect.stats}
* Gets the locale of the component. If the component does not have a
* locale, then the locale of its parent is returned.
*
* @return this component's locale. If this component does not have
* a locale, the locale of its parent is returned.
*
* @exception IllegalComponentStateException
* If the Component does not have its own locale and has not yet been
* added to a containment hierarchy such that the locale can be
* determined from the containing parent.
*/
public Locale getLocale() throws IllegalComponentStateException {
return ac.getLocale();
}
/** {@collect.stats}
* Adds a PropertyChangeListener to the listener list.
* The listener is registered for all Accessible properties and will
* be called when those properties change.
*
* @see #ACCESSIBLE_NAME_PROPERTY
* @see #ACCESSIBLE_DESCRIPTION_PROPERTY
* @see #ACCESSIBLE_STATE_PROPERTY
* @see #ACCESSIBLE_VALUE_PROPERTY
* @see #ACCESSIBLE_SELECTION_PROPERTY
* @see #ACCESSIBLE_TEXT_PROPERTY
* @see #ACCESSIBLE_VISIBLE_DATA_PROPERTY
*
* @param listener The PropertyChangeListener to be added
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
ac.addPropertyChangeListener(listener);
}
/** {@collect.stats}
* Removes a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param listener The PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
ac.removePropertyChangeListener(listener);
}
/** {@collect.stats}
* Gets the AccessibleAction associated with this object that supports
* one or more actions.
*
* @return AccessibleAction if supported by object; else return null
* @see AccessibleAction
*/
public AccessibleAction getAccessibleAction() {
return ac.getAccessibleAction();
}
/** {@collect.stats}
* Gets the AccessibleComponent associated with this object that has a
* graphical representation.
*
* @return AccessibleComponent if supported by object; else return null
* @see AccessibleComponent
*/
public AccessibleComponent getAccessibleComponent() {
return ac.getAccessibleComponent();
}
/** {@collect.stats}
* Gets the AccessibleSelection associated with this object which allows its
* Accessible children to be selected.
*
* @return AccessibleSelection if supported by object; else return null
* @see AccessibleSelection
*/
public AccessibleSelection getAccessibleSelection() {
return ac.getAccessibleSelection();
}
/** {@collect.stats}
* Gets the AccessibleText associated with this object presenting
* text on the display.
*
* @return AccessibleText if supported by object; else return null
* @see AccessibleText
*/
public AccessibleText getAccessibleText() {
return ac.getAccessibleText();
}
/** {@collect.stats}
* Gets the AccessibleEditableText associated with this object
* presenting editable text on the display.
*
* @return AccessibleEditableText if supported by object; else return null
* @see AccessibleEditableText
*/
public AccessibleEditableText getAccessibleEditableText() {
return ac.getAccessibleEditableText();
}
/** {@collect.stats}
* Gets the AccessibleValue associated with this object that supports a
* Numerical value.
*
* @return AccessibleValue if supported by object; else return null
* @see AccessibleValue
*/
public AccessibleValue getAccessibleValue() {
return ac.getAccessibleValue();
}
/** {@collect.stats}
* Gets the AccessibleIcons associated with an object that has
* one or more associated icons
*
* @return an array of AccessibleIcon if supported by object;
* otherwise return null
* @see AccessibleIcon
*/
public AccessibleIcon [] getAccessibleIcon() {
return ac.getAccessibleIcon();
}
/** {@collect.stats}
* Gets the AccessibleRelationSet associated with an object
*
* @return an AccessibleRelationSet if supported by object;
* otherwise return null
* @see AccessibleRelationSet
*/
public AccessibleRelationSet getAccessibleRelationSet() {
return ac.getAccessibleRelationSet();
}
/** {@collect.stats}
* Gets the AccessibleTable associated with an object
*
* @return an AccessibleTable if supported by object;
* otherwise return null
* @see AccessibleTable
*/
public AccessibleTable getAccessibleTable() {
return ac.getAccessibleTable();
}
/** {@collect.stats}
* Support for reporting bound property changes. If oldValue and
* newValue are not equal and the PropertyChangeEvent listener list
* is not empty, then fire a PropertyChange event to each listener.
* In general, this is for use by the Accessible objects themselves
* and should not be called by an application program.
* @param propertyName The programmatic name of the property that
* was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @see java.beans.PropertyChangeSupport
* @see #addPropertyChangeListener
* @see #removePropertyChangeListener
* @see #ACCESSIBLE_NAME_PROPERTY
* @see #ACCESSIBLE_DESCRIPTION_PROPERTY
* @see #ACCESSIBLE_STATE_PROPERTY
* @see #ACCESSIBLE_VALUE_PROPERTY
* @see #ACCESSIBLE_SELECTION_PROPERTY
* @see #ACCESSIBLE_TEXT_PROPERTY
* @see #ACCESSIBLE_VISIBLE_DATA_PROPERTY
*/
public void firePropertyChange(String propertyName,
Object oldValue,
Object newValue) {
ac.firePropertyChange(propertyName, oldValue, newValue);
}
}
} // innerclass AccessibleJComboBox
}
|
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.tree;
import javax.swing.tree.TreePath;
/** {@collect.stats}
* Defines the requirements for an object that translates paths in
* the tree into display rows.
*
* @author Scott Violet
*/
public interface RowMapper
{
/** {@collect.stats}
* Returns the rows that the TreePath instances in <code>path</code>
* are being displayed at. The receiver should return an array of
* the same length as that passed in, and if one of the TreePaths
* in <code>path</code> is not valid its entry in the array should
* be set to -1.
*/
int[] getRowsForPaths(TreePath[] path);
}
|
Java
|
/*
* Copyright (c) 1997, 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.tree;
import java.util.Enumeration;
/** {@collect.stats}
* Defines the requirements for an object that can be used as a
* tree node in a JTree.
* <p>
* Implementations of <code>TreeNode</code> that override <code>equals</code>
* will typically need to override <code>hashCode</code> as well. Refer
* to {@link javax.swing.tree.TreeModel} for more information.
*
* For further information and examples of using tree nodes,
* see <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Tree Nodes</a>
* in <em>The Java Tutorial.</em>
*
* @author Rob Davis
* @author Scott Violet
*/
public interface TreeNode
{
/** {@collect.stats}
* Returns the child <code>TreeNode</code> at index
* <code>childIndex</code>.
*/
TreeNode getChildAt(int childIndex);
/** {@collect.stats}
* Returns the number of children <code>TreeNode</code>s the receiver
* contains.
*/
int getChildCount();
/** {@collect.stats}
* Returns the parent <code>TreeNode</code> of the receiver.
*/
TreeNode getParent();
/** {@collect.stats}
* Returns the index of <code>node</code> in the receivers children.
* If the receiver does not contain <code>node</code>, -1 will be
* returned.
*/
int getIndex(TreeNode node);
/** {@collect.stats}
* Returns true if the receiver allows children.
*/
boolean getAllowsChildren();
/** {@collect.stats}
* Returns true if the receiver is a leaf.
*/
boolean isLeaf();
/** {@collect.stats}
* Returns the children of the receiver as an <code>Enumeration</code>.
*/
Enumeration children();
}
|
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.tree;
import javax.swing.event.TreeModelEvent;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.util.Enumeration;
/** {@collect.stats}
* <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 abstract class AbstractLayoutCache implements RowMapper {
/** {@collect.stats} Object responsible for getting the size of a node. */
protected NodeDimensions nodeDimensions;
/** {@collect.stats} Model providing information. */
protected TreeModel treeModel;
/** {@collect.stats} Selection model. */
protected TreeSelectionModel treeSelectionModel;
/** {@collect.stats}
* True if the root node is displayed, false if its children are
* the highest visible nodes.
*/
protected boolean rootVisible;
/** {@collect.stats}
* Height to use for each row. If this is <= 0 the renderer will be
* used to determine the height for each row.
*/
protected int rowHeight;
/** {@collect.stats}
* Sets the renderer that is responsible for drawing nodes in the tree
* and which is threfore responsible for calculating the dimensions of
* individual nodes.
*
* @param nd a <code>NodeDimensions</code> object
*/
public void setNodeDimensions(NodeDimensions nd) {
this.nodeDimensions = nd;
}
/** {@collect.stats}
* Returns the object that renders nodes in the tree, and which is
* responsible for calculating the dimensions of individual nodes.
*
* @return the <code>NodeDimensions</code> object
*/
public NodeDimensions getNodeDimensions() {
return nodeDimensions;
}
/** {@collect.stats}
* Sets the <code>TreeModel</code> that will provide the data.
*
* @param newModel the <code>TreeModel</code> that is to
* provide the data
*/
public void setModel(TreeModel newModel) {
treeModel = newModel;
}
/** {@collect.stats}
* Returns the <code>TreeModel</code> that is providing the data.
*
* @return the <code>TreeModel</code> that is providing the data
*/
public TreeModel getModel() {
return treeModel;
}
/** {@collect.stats}
* Determines whether or not the root node from
* the <code>TreeModel</code> is visible.
*
* @param rootVisible true if the root node of the tree is to be displayed
* @see #rootVisible
* @beaninfo
* bound: true
* description: Whether or not the root node
* from the TreeModel is visible.
*/
public void setRootVisible(boolean rootVisible) {
this.rootVisible = rootVisible;
}
/** {@collect.stats}
* Returns true if the root node of the tree is displayed.
*
* @return true if the root node of the tree is displayed
* @see #rootVisible
*/
public boolean isRootVisible() {
return rootVisible;
}
/** {@collect.stats}
* Sets the height of each cell. If the specified value
* is less than or equal to zero the current cell renderer is
* queried for each row's height.
*
* @param rowHeight the height of each cell, in pixels
* @beaninfo
* bound: true
* description: The height of each cell.
*/
public void setRowHeight(int rowHeight) {
this.rowHeight = rowHeight;
}
/** {@collect.stats}
* Returns the height of each row. If the returned value is less than
* or equal to 0 the height for each row is determined by the
* renderer.
*/
public int getRowHeight() {
return rowHeight;
}
/** {@collect.stats}
* Sets the <code>TreeSelectionModel</code> used to manage the
* selection to new LSM.
*
* @param newLSM the new <code>TreeSelectionModel</code>
*/
public void setSelectionModel(TreeSelectionModel newLSM) {
if(treeSelectionModel != null)
treeSelectionModel.setRowMapper(null);
treeSelectionModel = newLSM;
if(treeSelectionModel != null)
treeSelectionModel.setRowMapper(this);
}
/** {@collect.stats}
* Returns the model used to maintain the selection.
*
* @return the <code>treeSelectionModel</code>
*/
public TreeSelectionModel getSelectionModel() {
return treeSelectionModel;
}
/** {@collect.stats}
* Returns the preferred height.
*
* @return the preferred height
*/
public int getPreferredHeight() {
// Get the height
int rowCount = getRowCount();
if(rowCount > 0) {
Rectangle bounds = getBounds(getPathForRow(rowCount - 1),
null);
if(bounds != null)
return bounds.y + bounds.height;
}
return 0;
}
/** {@collect.stats}
* Returns the preferred width for the passed in region.
* The region is defined by the path closest to
* <code>(bounds.x, bounds.y)</code> and
* ends at <code>bounds.height + bounds.y</code>.
* If <code>bounds</code> is <code>null</code>,
* the preferred width for all the nodes
* will be returned (and this may be a VERY expensive
* computation).
*
* @param bounds the region being queried
* @return the preferred width for the passed in region
*/
public int getPreferredWidth(Rectangle bounds) {
int rowCount = getRowCount();
if(rowCount > 0) {
// Get the width
TreePath firstPath;
int endY;
if(bounds == null) {
firstPath = getPathForRow(0);
endY = Integer.MAX_VALUE;
}
else {
firstPath = getPathClosestTo(bounds.x, bounds.y);
endY = bounds.height + bounds.y;
}
Enumeration paths = getVisiblePathsFrom(firstPath);
if(paths != null && paths.hasMoreElements()) {
Rectangle pBounds = getBounds((TreePath)paths.nextElement(),
null);
int width;
if(pBounds != null) {
width = pBounds.x + pBounds.width;
if (pBounds.y >= endY) {
return width;
}
}
else
width = 0;
while (pBounds != null && paths.hasMoreElements()) {
pBounds = getBounds((TreePath)paths.nextElement(),
pBounds);
if (pBounds != null && pBounds.y < endY) {
width = Math.max(width, pBounds.x + pBounds.width);
}
else {
pBounds = null;
}
}
return width;
}
}
return 0;
}
//
// Abstract methods that must be implemented to be concrete.
//
/** {@collect.stats}
* Returns true if the value identified by row is currently expanded.
*/
public abstract boolean isExpanded(TreePath path);
/** {@collect.stats}
* Returns a rectangle giving the bounds needed to draw path.
*
* @param path a <code>TreePath</code> specifying a node
* @param placeIn a <code>Rectangle</code> object giving the
* available space
* @return a <code>Rectangle</code> object specifying the space to be used
*/
public abstract Rectangle getBounds(TreePath path, Rectangle placeIn);
/** {@collect.stats}
* Returns the path for passed in row. If row is not visible
* <code>null</code> is returned.
*
* @param row the row being queried
* @return the <code>TreePath</code> for the given row
*/
public abstract TreePath getPathForRow(int row);
/** {@collect.stats}
* Returns the row that the last item identified in path is visible
* at. Will return -1 if any of the elements in path are not
* currently visible.
*
* @param path the <code>TreePath</code> being queried
* @return the row where the last item in path is visible or -1
* if any elements in path aren't currently visible
*/
public abstract int getRowForPath(TreePath path);
/** {@collect.stats}
* Returns the path to the node that is closest to x,y. If
* there is nothing currently visible this will return <code>null</code>,
* otherwise it'll always return a valid path.
* If you need to test if the
* returned object is exactly at x, y you should get the bounds for
* the returned path and test x, y against that.
*
* @param x the horizontal component of the desired location
* @param y the vertical component of the desired location
* @return the <code>TreePath</code> closest to the specified point
*/
public abstract TreePath getPathClosestTo(int x, int y);
/** {@collect.stats}
* Returns an <code>Enumerator</code> that increments over the visible
* paths starting at the passed in location. The ordering of the
* enumeration is based on how the paths are displayed.
* The first element of the returned enumeration will be path,
* unless it isn't visible,
* in which case <code>null</code> will be returned.
*
* @param path the starting location for the enumeration
* @return the <code>Enumerator</code> starting at the desired location
*/
public abstract Enumeration<TreePath> getVisiblePathsFrom(TreePath path);
/** {@collect.stats}
* Returns the number of visible children for row.
*
* @param path the path being queried
* @return the number of visible children for the specified path
*/
public abstract int getVisibleChildCount(TreePath path);
/** {@collect.stats}
* Marks the path <code>path</code> expanded state to
* <code>isExpanded</code>.
*
* @param path the path being expanded or collapsed
* @param isExpanded true if the path should be expanded, false otherwise
*/
public abstract void setExpandedState(TreePath path, boolean isExpanded);
/** {@collect.stats}
* Returns true if the path is expanded, and visible.
*
* @param path the path being queried
* @return true if the path is expanded and visible, false otherwise
*/
public abstract boolean getExpandedState(TreePath path);
/** {@collect.stats}
* Number of rows being displayed.
*
* @return the number of rows being displayed
*/
public abstract int getRowCount();
/** {@collect.stats}
* Informs the <code>TreeState</code> that it needs to recalculate
* all the sizes it is referencing.
*/
public abstract void invalidateSizes();
/** {@collect.stats}
* Instructs the <code>LayoutCache</code> that the bounds for
* <code>path</code> are invalid, and need to be updated.
*
* @param path the path being updated
*/
public abstract void invalidatePathBounds(TreePath path);
//
// TreeModelListener methods
// AbstractTreeState does not directly become a TreeModelListener on
// the model, it is up to some other object to forward these methods.
//
/** {@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>e.path() returns the path the parent of the changed node(s).</p>
*
* <p>e.childIndices() returns the index(es) of the changed node(s).</p>
*
* @param e the <code>TreeModelEvent</code>
*/
public abstract void treeNodesChanged(TreeModelEvent e);
/** {@collect.stats}
* <p>Invoked after nodes have been inserted into the tree.</p>
*
* <p>e.path() returns the parent of the new nodes</p>
* <p>e.childIndices() returns the indices of the new nodes in
* ascending order.</p>
*
* @param e the <code>TreeModelEvent</code>
*/
public abstract 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>e.path() returns the former parent of the deleted nodes.</p>
*
* <p>e.childIndices() returns the indices the nodes had before they were deleted in ascending order.</p>
*
* @param e the <code>TreeModelEvent</code>
*/
public abstract 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 <code>e.getPath()</code>
* 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>e.path() holds the path to the node.</p>
* <p>e.childIndices() returns null.</p>
*
* @param e the <code>TreeModelEvent</code>
*/
public abstract void treeStructureChanged(TreeModelEvent e);
//
// RowMapper
//
/** {@collect.stats}
* Returns the rows that the <code>TreePath</code> instances in
* <code>path</code> are being displayed at.
* This method should return an array of the same length as that passed
* in, and if one of the <code>TreePaths</code>
* in <code>path</code> is not valid its entry in the array should
* be set to -1.
*
* @param paths the array of <code>TreePath</code>s being queried
* @return an array of the same length that is passed in containing
* the rows that each corresponding where each
* <code>TreePath</code> is displayed; if <code>paths</code>
* is <code>null</code>, <code>null</code> is returned
*/
public int[] getRowsForPaths(TreePath[] paths) {
if(paths == null)
return null;
int numPaths = paths.length;
int[] rows = new int[numPaths];
for(int counter = 0; counter < numPaths; counter++)
rows[counter] = getRowForPath(paths[counter]);
return rows;
}
//
// Local methods that subclassers may wish to use that are primarly
// convenience methods.
//
/** {@collect.stats}
* Returns, by reference in <code>placeIn</code>,
* the size needed to represent <code>value</code>.
* If <code>inPlace</code> is <code>null</code>, a newly created
* <code>Rectangle</code> should be returned, otherwise the value
* should be placed in <code>inPlace</code> and returned. This will
* return <code>null</code> if there is no renderer.
*
* @param value the <code>value</code> to be represented
* @param row row being queried
* @param depth the depth of the row
* @param expanded true if row is expanded, false otherwise
* @param placeIn a <code>Rectangle</code> containing the size needed
* to represent <code>value</code>
* @return a <code>Rectangle</code> containing the node dimensions,
* or <code>null</code> if node has no dimension
*/
protected Rectangle getNodeDimensions(Object value, int row, int depth,
boolean expanded,
Rectangle placeIn) {
NodeDimensions nd = getNodeDimensions();
if(nd != null) {
return nd.getNodeDimensions(value, row, depth, expanded, placeIn);
}
return null;
}
/** {@collect.stats}
* Returns true if the height of each row is a fixed size.
*/
protected boolean isFixedRowHeight() {
return (rowHeight > 0);
}
/** {@collect.stats}
* Used by <code>AbstractLayoutCache</code> to determine the size
* and x origin of a particular node.
*/
static public abstract class NodeDimensions {
/** {@collect.stats}
* Returns, by reference in bounds, the size and x origin to
* place value at. The calling method is responsible for determining
* the Y location. If bounds is <code>null</code>, a newly created
* <code>Rectangle</code> should be returned,
* otherwise the value should be placed in bounds and returned.
*
* @param value the <code>value</code> to be represented
* @param row row being queried
* @param depth the depth of the row
* @param expanded true if row is expanded, false otherwise
* @param bounds a <code>Rectangle</code> containing the size needed
* to represent <code>value</code>
* @return a <code>Rectangle</code> containing the node dimensions,
* or <code>null</code> if node has no dimension
*/
public abstract Rectangle getNodeDimensions(Object value, int row,
int depth,
boolean expanded,
Rectangle bounds);
}
}
|
Java
|
/*
* Copyright (c) 1998, 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.tree;
import javax.swing.event.TreeModelEvent;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Stack;
/** {@collect.stats}
* NOTE: This will become more open in a future release.
* <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 FixedHeightLayoutCache extends AbstractLayoutCache {
/** {@collect.stats} Root node. */
private FHTreeStateNode root;
/** {@collect.stats} Number of rows currently visible. */
private int rowCount;
/** {@collect.stats}
* Used in getting sizes for nodes to avoid creating a new Rectangle
* every time a size is needed.
*/
private Rectangle boundsBuffer;
/** {@collect.stats}
* Maps from TreePath to a FHTreeStateNode.
*/
private Hashtable treePathMapping;
/** {@collect.stats}
* Used for getting path/row information.
*/
private SearchInfo info;
private Stack tempStacks;
public FixedHeightLayoutCache() {
super();
tempStacks = new Stack();
boundsBuffer = new Rectangle();
treePathMapping = new Hashtable();
info = new SearchInfo();
setRowHeight(1);
}
/** {@collect.stats}
* Sets the TreeModel that will provide the data.
*
* @param newModel the TreeModel that is to provide the data
*/
public void setModel(TreeModel newModel) {
super.setModel(newModel);
rebuild(false);
}
/** {@collect.stats}
* Determines whether or not the root node from
* the TreeModel is visible.
*
* @param rootVisible true if the root node of the tree is to be displayed
* @see #rootVisible
*/
public void setRootVisible(boolean rootVisible) {
if(isRootVisible() != rootVisible) {
super.setRootVisible(rootVisible);
if(root != null) {
if(rootVisible) {
rowCount++;
root.adjustRowBy(1);
}
else {
rowCount--;
root.adjustRowBy(-1);
}
visibleNodesChanged();
}
}
}
/** {@collect.stats}
* Sets the height of each cell. If rowHeight is less than or equal to
* 0 this will throw an IllegalArgumentException.
*
* @param rowHeight the height of each cell, in pixels
*/
public void setRowHeight(int rowHeight) {
if(rowHeight <= 0)
throw new IllegalArgumentException("FixedHeightLayoutCache only supports row heights greater than 0");
if(getRowHeight() != rowHeight) {
super.setRowHeight(rowHeight);
visibleNodesChanged();
}
}
/** {@collect.stats}
* Returns the number of visible rows.
*/
public int getRowCount() {
return rowCount;
}
/** {@collect.stats}
* Does nothing, FixedHeightLayoutCache doesn't cache width, and that
* is all that could change.
*/
public void invalidatePathBounds(TreePath path) {
}
/** {@collect.stats}
* Informs the TreeState that it needs to recalculate all the sizes
* it is referencing.
*/
public void invalidateSizes() {
// Nothing to do here, rowHeight still same, which is all
// this is interested in, visible region may have changed though.
visibleNodesChanged();
}
/** {@collect.stats}
* Returns true if the value identified by row is currently expanded.
*/
public boolean isExpanded(TreePath path) {
if(path != null) {
FHTreeStateNode lastNode = getNodeForPath(path, true, false);
return (lastNode != null && lastNode.isExpanded());
}
return false;
}
/** {@collect.stats}
* Returns a rectangle giving the bounds needed to draw path.
*
* @param path a TreePath specifying a node
* @param placeIn a Rectangle object giving the available space
* @return a Rectangle object specifying the space to be used
*/
public Rectangle getBounds(TreePath path, Rectangle placeIn) {
if(path == null)
return null;
FHTreeStateNode node = getNodeForPath(path, true, false);
if(node != null)
return getBounds(node, -1, placeIn);
// node hasn't been created yet.
TreePath parentPath = path.getParentPath();
node = getNodeForPath(parentPath, true, false);
if (node != null && node.isExpanded()) {
int childIndex = treeModel.getIndexOfChild
(parentPath.getLastPathComponent(),
path.getLastPathComponent());
if(childIndex != -1)
return getBounds(node, childIndex, placeIn);
}
return null;
}
/** {@collect.stats}
* Returns the path for passed in row. If row is not visible
* null is returned.
*/
public TreePath getPathForRow(int row) {
if(row >= 0 && row < getRowCount()) {
if(root.getPathForRow(row, getRowCount(), info)) {
return info.getPath();
}
}
return null;
}
/** {@collect.stats}
* Returns the row that the last item identified in path is visible
* at. Will return -1 if any of the elements in path are not
* currently visible.
*/
public int getRowForPath(TreePath path) {
if(path == null || root == null)
return -1;
FHTreeStateNode node = getNodeForPath(path, true, false);
if(node != null)
return node.getRow();
TreePath parentPath = path.getParentPath();
node = getNodeForPath(parentPath, true, false);
if(node != null && node.isExpanded()) {
return node.getRowToModelIndex(treeModel.getIndexOfChild
(parentPath.getLastPathComponent(),
path.getLastPathComponent()));
}
return -1;
}
/** {@collect.stats}
* Returns the path to the node that is closest to x,y. If
* there is nothing currently visible this will return null, otherwise
* it'll always return a valid path. If you need to test if the
* returned object is exactly at x, y you should get the bounds for
* the returned path and test x, y against that.
*/
public TreePath getPathClosestTo(int x, int y) {
if(getRowCount() == 0)
return null;
int row = getRowContainingYLocation(y);
return getPathForRow(row);
}
/** {@collect.stats}
* Returns the number of visible children for row.
*/
public int getVisibleChildCount(TreePath path) {
FHTreeStateNode node = getNodeForPath(path, true, false);
if(node == null)
return 0;
return node.getTotalChildCount();
}
/** {@collect.stats}
* Returns an Enumerator that increments over the visible paths
* starting at the passed in location. The ordering of the enumeration
* is based on how the paths are displayed.
*/
public Enumeration<TreePath> getVisiblePathsFrom(TreePath path) {
if(path == null)
return null;
FHTreeStateNode node = getNodeForPath(path, true, false);
if(node != null) {
return new VisibleFHTreeStateNodeEnumeration(node);
}
TreePath parentPath = path.getParentPath();
node = getNodeForPath(parentPath, true, false);
if(node != null && node.isExpanded()) {
return new VisibleFHTreeStateNodeEnumeration(node,
treeModel.getIndexOfChild(parentPath.getLastPathComponent(),
path.getLastPathComponent()));
}
return null;
}
/** {@collect.stats}
* Marks the path <code>path</code> expanded state to
* <code>isExpanded</code>.
*/
public void setExpandedState(TreePath path, boolean isExpanded) {
if(isExpanded)
ensurePathIsExpanded(path, true);
else if(path != null) {
TreePath parentPath = path.getParentPath();
// YECK! Make the parent expanded.
if(parentPath != null) {
FHTreeStateNode parentNode = getNodeForPath(parentPath,
false, true);
if(parentNode != null)
parentNode.makeVisible();
}
// And collapse the child.
FHTreeStateNode childNode = getNodeForPath(path, true,
false);
if(childNode != null)
childNode.collapse(true);
}
}
/** {@collect.stats}
* Returns true if the path is expanded, and visible.
*/
public boolean getExpandedState(TreePath path) {
FHTreeStateNode node = getNodeForPath(path, true, false);
return (node != null) ? (node.isVisible() && node.isExpanded()) :
false;
}
//
// TreeModelListener methods
//
/** {@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>e.path() returns the path the parent of the changed node(s).</p>
*
* <p>e.childIndices() returns the index(es) of the changed node(s).</p>
*/
public void treeNodesChanged(TreeModelEvent e) {
if(e != null) {
int changedIndexs[];
FHTreeStateNode changedParent = getNodeForPath
(e.getTreePath(), false, false);
int maxCounter;
changedIndexs = e.getChildIndices();
/* Only need to update the children if the node has been
expanded once. */
// PENDING(scott): make sure childIndexs is sorted!
if (changedParent != null) {
if (changedIndexs != null &&
(maxCounter = changedIndexs.length) > 0) {
Object parentValue = changedParent.getUserObject();
for(int counter = 0; counter < maxCounter; counter++) {
FHTreeStateNode child = changedParent.
getChildAtModelIndex(changedIndexs[counter]);
if(child != null) {
child.setUserObject(treeModel.getChild(parentValue,
changedIndexs[counter]));
}
}
if(changedParent.isVisible() && changedParent.isExpanded())
visibleNodesChanged();
}
// Null for root indicates it changed.
else if (changedParent == root && changedParent.isVisible() &&
changedParent.isExpanded()) {
visibleNodesChanged();
}
}
}
}
/** {@collect.stats}
* <p>Invoked after nodes have been inserted into the tree.</p>
*
* <p>e.path() returns the parent of the new nodes
* <p>e.childIndices() returns the indices of the new nodes in
* ascending order.
*/
public void treeNodesInserted(TreeModelEvent e) {
if(e != null) {
int changedIndexs[];
FHTreeStateNode changedParent = getNodeForPath
(e.getTreePath(), false, false);
int maxCounter;
changedIndexs = e.getChildIndices();
/* Only need to update the children if the node has been
expanded once. */
// PENDING(scott): make sure childIndexs is sorted!
if(changedParent != null && changedIndexs != null &&
(maxCounter = changedIndexs.length) > 0) {
boolean isVisible =
(changedParent.isVisible() &&
changedParent.isExpanded());
for(int counter = 0; counter < maxCounter; counter++) {
changedParent.childInsertedAtModelIndex
(changedIndexs[counter], isVisible);
}
if(isVisible && treeSelectionModel != null)
treeSelectionModel.resetRowSelection();
if(changedParent.isVisible())
this.visibleNodesChanged();
}
}
}
/** {@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>e.path() returns the former parent of the deleted nodes.</p>
*
* <p>e.childIndices() returns the indices the nodes had before they were deleted in ascending order.</p>
*/
public void treeNodesRemoved(TreeModelEvent e) {
if(e != null) {
int changedIndexs[];
int maxCounter;
TreePath parentPath = e.getTreePath();
FHTreeStateNode changedParentNode = getNodeForPath
(parentPath, false, false);
changedIndexs = e.getChildIndices();
// PENDING(scott): make sure that changedIndexs are sorted in
// ascending order.
if(changedParentNode != null && changedIndexs != null &&
(maxCounter = changedIndexs.length) > 0) {
Object[] children = e.getChildren();
boolean isVisible =
(changedParentNode.isVisible() &&
changedParentNode.isExpanded());
for(int counter = maxCounter - 1; counter >= 0; counter--) {
changedParentNode.removeChildAtModelIndex
(changedIndexs[counter], isVisible);
}
if(isVisible) {
if(treeSelectionModel != null)
treeSelectionModel.resetRowSelection();
if (treeModel.getChildCount(changedParentNode.
getUserObject()) == 0 &&
changedParentNode.isLeaf()) {
// Node has become a leaf, collapse it.
changedParentNode.collapse(false);
}
visibleNodesChanged();
}
else if(changedParentNode.isVisible())
visibleNodesChanged();
}
}
}
/** {@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>e.path() holds the path to the node.</p>
* <p>e.childIndices() returns null.</p>
*/
public void treeStructureChanged(TreeModelEvent e) {
if(e != null) {
TreePath changedPath = e.getTreePath();
FHTreeStateNode changedNode = getNodeForPath
(changedPath, false, false);
// Check if root has changed, either to a null root, or
// to an entirely new root.
if (changedNode == root ||
(changedNode == null &&
((changedPath == null && treeModel != null &&
treeModel.getRoot() == null) ||
(changedPath != null && changedPath.getPathCount() <= 1)))) {
rebuild(true);
}
else if(changedNode != null) {
boolean wasExpanded, wasVisible;
FHTreeStateNode parent = (FHTreeStateNode)
changedNode.getParent();
wasExpanded = changedNode.isExpanded();
wasVisible = changedNode.isVisible();
int index = parent.getIndex(changedNode);
changedNode.collapse(false);
parent.remove(index);
if(wasVisible && wasExpanded) {
int row = changedNode.getRow();
parent.resetChildrenRowsFrom(row, index,
changedNode.getChildIndex());
changedNode = getNodeForPath(changedPath, false, true);
changedNode.expand();
}
if(treeSelectionModel != null && wasVisible && wasExpanded)
treeSelectionModel.resetRowSelection();
if(wasVisible)
this.visibleNodesChanged();
}
}
}
//
// Local methods
//
private void visibleNodesChanged() {
}
/** {@collect.stats}
* Returns the bounds for the given node. If <code>childIndex</code>
* is -1, the bounds of <code>parent</code> are returned, otherwise
* the bounds of the node at <code>childIndex</code> are returned.
*/
private Rectangle getBounds(FHTreeStateNode parent, int childIndex,
Rectangle placeIn) {
boolean expanded;
int level;
int row;
Object value;
if(childIndex == -1) {
// Getting bounds for parent
row = parent.getRow();
value = parent.getUserObject();
expanded = parent.isExpanded();
level = parent.getLevel();
}
else {
row = parent.getRowToModelIndex(childIndex);
value = treeModel.getChild(parent.getUserObject(), childIndex);
expanded = false;
level = parent.getLevel() + 1;
}
Rectangle bounds = getNodeDimensions(value, row, level,
expanded, boundsBuffer);
// No node dimensions, bail.
if(bounds == null)
return null;
if(placeIn == null)
placeIn = new Rectangle();
placeIn.x = bounds.x;
placeIn.height = getRowHeight();
placeIn.y = row * placeIn.height;
placeIn.width = bounds.width;
return placeIn;
}
/** {@collect.stats}
* Adjust the large row count of the AbstractTreeUI the receiver was
* created with.
*/
private void adjustRowCountBy(int changeAmount) {
rowCount += changeAmount;
}
/** {@collect.stats}
* Adds a mapping for node.
*/
private void addMapping(FHTreeStateNode node) {
treePathMapping.put(node.getTreePath(), node);
}
/** {@collect.stats}
* Removes the mapping for a previously added node.
*/
private void removeMapping(FHTreeStateNode node) {
treePathMapping.remove(node.getTreePath());
}
/** {@collect.stats}
* Returns the node previously added for <code>path</code>. This may
* return null, if you to create a node use getNodeForPath.
*/
private FHTreeStateNode getMapping(TreePath path) {
return (FHTreeStateNode)treePathMapping.get(path);
}
/** {@collect.stats}
* Sent to completely rebuild the visible tree. All nodes are collapsed.
*/
private void rebuild(boolean clearSelection) {
Object rootUO;
treePathMapping.clear();
if(treeModel != null && (rootUO = treeModel.getRoot()) != null) {
root = createNodeForValue(rootUO, 0);
root.path = new TreePath(rootUO);
addMapping(root);
if(isRootVisible()) {
rowCount = 1;
root.row = 0;
}
else {
rowCount = 0;
root.row = -1;
}
root.expand();
}
else {
root = null;
rowCount = 0;
}
if(clearSelection && treeSelectionModel != null) {
treeSelectionModel.clearSelection();
}
this.visibleNodesChanged();
}
/** {@collect.stats}
* Returns the index of the row containing location. If there
* are no rows, -1 is returned. If location is beyond the last
* row index, the last row index is returned.
*/
private int getRowContainingYLocation(int location) {
if(getRowCount() == 0)
return -1;
return Math.max(0, Math.min(getRowCount() - 1,
location / getRowHeight()));
}
/** {@collect.stats}
* Ensures that all the path components in path are expanded, accept
* for the last component which will only be expanded if expandLast
* is true.
* Returns true if succesful in finding the path.
*/
private boolean ensurePathIsExpanded(TreePath aPath,
boolean expandLast) {
if(aPath != null) {
// Make sure the last entry isn't a leaf.
if(treeModel.isLeaf(aPath.getLastPathComponent())) {
aPath = aPath.getParentPath();
expandLast = true;
}
if(aPath != null) {
FHTreeStateNode lastNode = getNodeForPath(aPath, false,
true);
if(lastNode != null) {
lastNode.makeVisible();
if(expandLast)
lastNode.expand();
return true;
}
}
}
return false;
}
/** {@collect.stats}
* Creates and returns an instance of FHTreeStateNode.
*/
private FHTreeStateNode createNodeForValue(Object value,int childIndex) {
return new FHTreeStateNode(value, childIndex, -1);
}
/** {@collect.stats}
* Messages getTreeNodeForPage(path, onlyIfVisible, shouldCreate,
* path.length) as long as path is non-null and the length is > 0.
* Otherwise returns null.
*/
private FHTreeStateNode getNodeForPath(TreePath path,
boolean onlyIfVisible,
boolean shouldCreate) {
if(path != null) {
FHTreeStateNode node;
node = getMapping(path);
if(node != null) {
if(onlyIfVisible && !node.isVisible())
return null;
return node;
}
if(onlyIfVisible)
return null;
// Check all the parent paths, until a match is found.
Stack paths;
if(tempStacks.size() == 0) {
paths = new Stack();
}
else {
paths = (Stack)tempStacks.pop();
}
try {
paths.push(path);
path = path.getParentPath();
node = null;
while(path != null) {
node = getMapping(path);
if(node != null) {
// Found a match, create entries for all paths in
// paths.
while(node != null && paths.size() > 0) {
path = (TreePath)paths.pop();
node = node.createChildFor(path.
getLastPathComponent());
}
return node;
}
paths.push(path);
path = path.getParentPath();
}
}
finally {
paths.removeAllElements();
tempStacks.push(paths);
}
// If we get here it means they share a different root!
return null;
}
return null;
}
/** {@collect.stats}
* FHTreeStateNode is used to track what has been expanded.
* FHTreeStateNode differs from VariableHeightTreeState.TreeStateNode
* in that it is highly model intensive. That is almost all queries to a
* FHTreeStateNode result in the TreeModel being queried. And it
* obviously does not support variable sized row heights.
*/
private class FHTreeStateNode extends DefaultMutableTreeNode {
/** {@collect.stats} Is this node expanded? */
protected boolean isExpanded;
/** {@collect.stats} Index of this node from the model. */
protected int childIndex;
/** {@collect.stats} Child count of the receiver. */
protected int childCount;
/** {@collect.stats} Row of the receiver. This is only valid if the row is expanded.
*/
protected int row;
/** {@collect.stats} Path of this node. */
protected TreePath path;
public FHTreeStateNode(Object userObject, int childIndex, int row) {
super(userObject);
this.childIndex = childIndex;
this.row = row;
}
//
// Overriden DefaultMutableTreeNode methods
//
/** {@collect.stats}
* Messaged when this node is added somewhere, resets the path
* and adds a mapping from path to this node.
*/
public void setParent(MutableTreeNode parent) {
super.setParent(parent);
if(parent != null) {
path = ((FHTreeStateNode)parent).getTreePath().
pathByAddingChild(getUserObject());
addMapping(this);
}
}
/** {@collect.stats}
* Messaged when this node is removed from its parent, this messages
* <code>removedFromMapping</code> to remove all the children.
*/
public void remove(int childIndex) {
FHTreeStateNode node = (FHTreeStateNode)getChildAt(childIndex);
node.removeFromMapping();
super.remove(childIndex);
}
/** {@collect.stats}
* Messaged to set the user object. This resets the path.
*/
public void setUserObject(Object o) {
super.setUserObject(o);
if(path != null) {
FHTreeStateNode parent = (FHTreeStateNode)getParent();
if(parent != null)
resetChildrenPaths(parent.getTreePath());
else
resetChildrenPaths(null);
}
}
//
//
/** {@collect.stats}
* Returns the index of the receiver in the model.
*/
public int getChildIndex() {
return childIndex;
}
/** {@collect.stats}
* Returns the <code>TreePath</code> of the receiver.
*/
public TreePath getTreePath() {
return path;
}
/** {@collect.stats}
* Returns the child for the passed in model index, this will
* return <code>null</code> if the child for <code>index</code>
* has not yet been created (expanded).
*/
public FHTreeStateNode getChildAtModelIndex(int index) {
// PENDING: Make this a binary search!
for(int counter = getChildCount() - 1; counter >= 0; counter--)
if(((FHTreeStateNode)getChildAt(counter)).childIndex == index)
return (FHTreeStateNode)getChildAt(counter);
return null;
}
/** {@collect.stats}
* Returns true if this node is visible. This is determined by
* asking all the parents if they are expanded.
*/
public boolean isVisible() {
FHTreeStateNode parent = (FHTreeStateNode)getParent();
if(parent == null)
return true;
return (parent.isExpanded() && parent.isVisible());
}
/** {@collect.stats}
* Returns the row of the receiver.
*/
public int getRow() {
return row;
}
/** {@collect.stats}
* Returns the row of the child with a model index of
* <code>index</code>.
*/
public int getRowToModelIndex(int index) {
FHTreeStateNode child;
int lastRow = getRow() + 1;
int retValue = lastRow;
// This too could be a binary search!
for(int counter = 0, maxCounter = getChildCount();
counter < maxCounter; counter++) {
child = (FHTreeStateNode)getChildAt(counter);
if(child.childIndex >= index) {
if(child.childIndex == index)
return child.row;
if(counter == 0)
return getRow() + 1 + index;
return child.row - (child.childIndex - index);
}
}
// YECK!
return getRow() + 1 + getTotalChildCount() -
(childCount - index);
}
/** {@collect.stats}
* Returns the number of children in the receiver by descending all
* expanded nodes and messaging them with getTotalChildCount.
*/
public int getTotalChildCount() {
if(isExpanded()) {
FHTreeStateNode parent = (FHTreeStateNode)getParent();
int pIndex;
if(parent != null && (pIndex = parent.getIndex(this)) + 1 <
parent.getChildCount()) {
// This node has a created sibling, to calc total
// child count directly from that!
FHTreeStateNode nextSibling = (FHTreeStateNode)parent.
getChildAt(pIndex + 1);
return nextSibling.row - row -
(nextSibling.childIndex - childIndex);
}
else {
int retCount = childCount;
for(int counter = getChildCount() - 1; counter >= 0;
counter--) {
retCount += ((FHTreeStateNode)getChildAt(counter))
.getTotalChildCount();
}
return retCount;
}
}
return 0;
}
/** {@collect.stats}
* Returns true if this node is expanded.
*/
public boolean isExpanded() {
return isExpanded;
}
/** {@collect.stats}
* The highest visible nodes have a depth of 0.
*/
public int getVisibleLevel() {
if (isRootVisible()) {
return getLevel();
} else {
return getLevel() - 1;
}
}
/** {@collect.stats}
* Recreates the receivers path, and all its childrens paths.
*/
protected void resetChildrenPaths(TreePath parentPath) {
removeMapping(this);
if(parentPath == null)
path = new TreePath(getUserObject());
else
path = parentPath.pathByAddingChild(getUserObject());
addMapping(this);
for(int counter = getChildCount() - 1; counter >= 0; counter--)
((FHTreeStateNode)getChildAt(counter)).
resetChildrenPaths(path);
}
/** {@collect.stats}
* Removes the receiver, and all its children, from the mapping
* table.
*/
protected void removeFromMapping() {
if(path != null) {
removeMapping(this);
for(int counter = getChildCount() - 1; counter >= 0; counter--)
((FHTreeStateNode)getChildAt(counter)).removeFromMapping();
}
}
/** {@collect.stats}
* Creates a new node to represent <code>userObject</code>.
* This does NOT check to ensure there isn't already a child node
* to manage <code>userObject</code>.
*/
protected FHTreeStateNode createChildFor(Object userObject) {
int newChildIndex = treeModel.getIndexOfChild
(getUserObject(), userObject);
if(newChildIndex < 0)
return null;
FHTreeStateNode aNode;
FHTreeStateNode child = createNodeForValue(userObject,
newChildIndex);
int childRow;
if(isVisible()) {
childRow = getRowToModelIndex(newChildIndex);
}
else {
childRow = -1;
}
child.row = childRow;
for(int counter = 0, maxCounter = getChildCount();
counter < maxCounter; counter++) {
aNode = (FHTreeStateNode)getChildAt(counter);
if(aNode.childIndex > newChildIndex) {
insert(child, counter);
return child;
}
}
add(child);
return child;
}
/** {@collect.stats}
* Adjusts the receiver, and all its children rows by
* <code>amount</code>.
*/
protected void adjustRowBy(int amount) {
row += amount;
if(isExpanded) {
for(int counter = getChildCount() - 1; counter >= 0;
counter--)
((FHTreeStateNode)getChildAt(counter)).adjustRowBy(amount);
}
}
/** {@collect.stats}
* Adjusts this node, its child, and its parent starting at
* an index of <code>index</code> index is the index of the child
* to start adjusting from, which is not necessarily the model
* index.
*/
protected void adjustRowBy(int amount, int startIndex) {
// Could check isVisible, but probably isn't worth it.
if(isExpanded) {
// children following startIndex.
for(int counter = getChildCount() - 1; counter >= startIndex;
counter--)
((FHTreeStateNode)getChildAt(counter)).adjustRowBy(amount);
}
// Parent
FHTreeStateNode parent = (FHTreeStateNode)getParent();
if(parent != null) {
parent.adjustRowBy(amount, parent.getIndex(this) + 1);
}
}
/** {@collect.stats}
* Messaged when the node has expanded. This updates all of
* the receivers children rows, as well as the total row count.
*/
protected void didExpand() {
int nextRow = setRowAndChildren(row);
FHTreeStateNode parent = (FHTreeStateNode)getParent();
int childRowCount = nextRow - row - 1;
if(parent != null) {
parent.adjustRowBy(childRowCount, parent.getIndex(this) + 1);
}
adjustRowCountBy(childRowCount);
}
/** {@collect.stats}
* Sets the receivers row to <code>nextRow</code> and recursively
* updates all the children of the receivers rows. The index the
* next row is to be placed as is returned.
*/
protected int setRowAndChildren(int nextRow) {
row = nextRow;
if(!isExpanded())
return row + 1;
int lastRow = row + 1;
int lastModelIndex = 0;
FHTreeStateNode child;
int maxCounter = getChildCount();
for(int counter = 0; counter < maxCounter; counter++) {
child = (FHTreeStateNode)getChildAt(counter);
lastRow += (child.childIndex - lastModelIndex);
lastModelIndex = child.childIndex + 1;
if(child.isExpanded) {
lastRow = child.setRowAndChildren(lastRow);
}
else {
child.row = lastRow++;
}
}
return lastRow + childCount - lastModelIndex;
}
/** {@collect.stats}
* Resets the receivers childrens rows. Starting with the child
* at <code>childIndex</code> (and <code>modelIndex</code>) to
* <code>newRow</code>. This uses <code>setRowAndChildren</code>
* to recursively descend children, and uses
* <code>resetRowSelection</code> to ascend parents.
*/
// This can be rather expensive, but is needed for the collapse
// case this is resulting from a remove (although I could fix
// that by having instances of FHTreeStateNode hold a ref to
// the number of children). I prefer this though, making determing
// the row of a particular node fast is very nice!
protected void resetChildrenRowsFrom(int newRow, int childIndex,
int modelIndex) {
int lastRow = newRow;
int lastModelIndex = modelIndex;
FHTreeStateNode node;
int maxCounter = getChildCount();
for(int counter = childIndex; counter < maxCounter; counter++) {
node = (FHTreeStateNode)getChildAt(counter);
lastRow += (node.childIndex - lastModelIndex);
lastModelIndex = node.childIndex + 1;
if(node.isExpanded) {
lastRow = node.setRowAndChildren(lastRow);
}
else {
node.row = lastRow++;
}
}
lastRow += childCount - lastModelIndex;
node = (FHTreeStateNode)getParent();
if(node != null) {
node.resetChildrenRowsFrom(lastRow, node.getIndex(this) + 1,
this.childIndex + 1);
}
else { // This is the root, reset total ROWCOUNT!
rowCount = lastRow;
}
}
/** {@collect.stats}
* Makes the receiver visible, but invoking
* <code>expandParentAndReceiver</code> on the superclass.
*/
protected void makeVisible() {
FHTreeStateNode parent = (FHTreeStateNode)getParent();
if(parent != null)
parent.expandParentAndReceiver();
}
/** {@collect.stats}
* Invokes <code>expandParentAndReceiver</code> on the parent,
* and expands the receiver.
*/
protected void expandParentAndReceiver() {
FHTreeStateNode parent = (FHTreeStateNode)getParent();
if(parent != null)
parent.expandParentAndReceiver();
expand();
}
/** {@collect.stats}
* Expands the receiver.
*/
protected void expand() {
if(!isExpanded && !isLeaf()) {
boolean visible = isVisible();
isExpanded = true;
childCount = treeModel.getChildCount(getUserObject());
if(visible) {
didExpand();
}
// Update the selection model.
if(visible && treeSelectionModel != null) {
treeSelectionModel.resetRowSelection();
}
}
}
/** {@collect.stats}
* Collapses the receiver. If <code>adjustRows</code> is true,
* the rows of nodes after the receiver are adjusted.
*/
protected void collapse(boolean adjustRows) {
if(isExpanded) {
if(isVisible() && adjustRows) {
int childCount = getTotalChildCount();
isExpanded = false;
adjustRowCountBy(-childCount);
// We can do this because adjustRowBy won't descend
// the children.
adjustRowBy(-childCount, 0);
}
else
isExpanded = false;
if(adjustRows && isVisible() && treeSelectionModel != null)
treeSelectionModel.resetRowSelection();
}
}
/** {@collect.stats}
* Returns true if the receiver is a leaf.
*/
public boolean isLeaf() {
TreeModel model = getModel();
return (model != null) ? model.isLeaf(this.getUserObject()) :
true;
}
/** {@collect.stats}
* Adds newChild to this nodes children at the appropriate location.
* The location is determined from the childIndex of newChild.
*/
protected void addNode(FHTreeStateNode newChild) {
boolean added = false;
int childIndex = newChild.getChildIndex();
for(int counter = 0, maxCounter = getChildCount();
counter < maxCounter; counter++) {
if(((FHTreeStateNode)getChildAt(counter)).getChildIndex() >
childIndex) {
added = true;
insert(newChild, counter);
counter = maxCounter;
}
}
if(!added)
add(newChild);
}
/** {@collect.stats}
* Removes the child at <code>modelIndex</code>.
* <code>isChildVisible</code> should be true if the receiver
* is visible and expanded.
*/
protected void removeChildAtModelIndex(int modelIndex,
boolean isChildVisible) {
FHTreeStateNode childNode = getChildAtModelIndex(modelIndex);
if(childNode != null) {
int row = childNode.getRow();
int index = getIndex(childNode);
childNode.collapse(false);
remove(index);
adjustChildIndexs(index, -1);
childCount--;
if(isChildVisible) {
// Adjust the rows.
resetChildrenRowsFrom(row, index, modelIndex);
}
}
else {
int maxCounter = getChildCount();
FHTreeStateNode aChild;
for(int counter = 0; counter < maxCounter; counter++) {
aChild = (FHTreeStateNode)getChildAt(counter);
if(aChild.childIndex >= modelIndex) {
if(isChildVisible) {
adjustRowBy(-1, counter);
adjustRowCountBy(-1);
}
// Since matched and children are always sorted by
// index, no need to continue testing with the
// above.
for(; counter < maxCounter; counter++)
((FHTreeStateNode)getChildAt(counter)).
childIndex--;
childCount--;
return;
}
}
// No children to adjust, but it was a child, so we still need
// to adjust nodes after this one.
if(isChildVisible) {
adjustRowBy(-1, maxCounter);
adjustRowCountBy(-1);
}
childCount--;
}
}
/** {@collect.stats}
* Adjusts the child indexs of the receivers children by
* <code>amount</code>, starting at <code>index</code>.
*/
protected void adjustChildIndexs(int index, int amount) {
for(int counter = index, maxCounter = getChildCount();
counter < maxCounter; counter++) {
((FHTreeStateNode)getChildAt(counter)).childIndex += amount;
}
}
/** {@collect.stats}
* Messaged when a child has been inserted at index. For all the
* children that have a childIndex >= index their index is incremented
* by one.
*/
protected void childInsertedAtModelIndex(int index,
boolean isExpandedAndVisible) {
FHTreeStateNode aChild;
int maxCounter = getChildCount();
for(int counter = 0; counter < maxCounter; counter++) {
aChild = (FHTreeStateNode)getChildAt(counter);
if(aChild.childIndex >= index) {
if(isExpandedAndVisible) {
adjustRowBy(1, counter);
adjustRowCountBy(1);
}
/* Since matched and children are always sorted by
index, no need to continue testing with the above. */
for(; counter < maxCounter; counter++)
((FHTreeStateNode)getChildAt(counter)).childIndex++;
childCount++;
return;
}
}
// No children to adjust, but it was a child, so we still need
// to adjust nodes after this one.
if(isExpandedAndVisible) {
adjustRowBy(1, maxCounter);
adjustRowCountBy(1);
}
childCount++;
}
/** {@collect.stats}
* Returns true if there is a row for <code>row</code>.
* <code>nextRow</code> gives the bounds of the receiver.
* Information about the found row is returned in <code>info</code>.
* This should be invoked on root with <code>nextRow</code> set
* to <code>getRowCount</code>().
*/
protected boolean getPathForRow(int row, int nextRow,
SearchInfo info) {
if(this.row == row) {
info.node = this;
info.isNodeParentNode = false;
info.childIndex = childIndex;
return true;
}
FHTreeStateNode child;
FHTreeStateNode lastChild = null;
for(int counter = 0, maxCounter = getChildCount();
counter < maxCounter; counter++) {
child = (FHTreeStateNode)getChildAt(counter);
if(child.row > row) {
if(counter == 0) {
// No node exists for it, and is first.
info.node = this;
info.isNodeParentNode = true;
info.childIndex = row - this.row - 1;
return true;
}
else {
// May have been in last childs bounds.
int lastChildEndRow = 1 + child.row -
(child.childIndex - lastChild.childIndex);
if(row < lastChildEndRow) {
return lastChild.getPathForRow(row,
lastChildEndRow, info);
}
// Between last child and child, but not in last child
info.node = this;
info.isNodeParentNode = true;
info.childIndex = row - lastChildEndRow +
lastChild.childIndex + 1;
return true;
}
}
lastChild = child;
}
// Not in children, but we should have it, offset from
// nextRow.
if(lastChild != null) {
int lastChildEndRow = nextRow -
(childCount - lastChild.childIndex) + 1;
if(row < lastChildEndRow) {
return lastChild.getPathForRow(row, lastChildEndRow, info);
}
// Between last child and child, but not in last child
info.node = this;
info.isNodeParentNode = true;
info.childIndex = row - lastChildEndRow +
lastChild.childIndex + 1;
return true;
}
else {
// No children.
int retChildIndex = row - this.row - 1;
if(retChildIndex >= childCount) {
return false;
}
info.node = this;
info.isNodeParentNode = true;
info.childIndex = retChildIndex;
return true;
}
}
/** {@collect.stats}
* Asks all the children of the receiver for their totalChildCount
* and returns this value (plus stopIndex).
*/
protected int getCountTo(int stopIndex) {
FHTreeStateNode aChild;
int retCount = stopIndex + 1;
for(int counter = 0, maxCounter = getChildCount();
counter < maxCounter; counter++) {
aChild = (FHTreeStateNode)getChildAt(counter);
if(aChild.childIndex >= stopIndex)
counter = maxCounter;
else
retCount += aChild.getTotalChildCount();
}
if(parent != null)
return retCount + ((FHTreeStateNode)getParent())
.getCountTo(childIndex);
if(!isRootVisible())
return (retCount - 1);
return retCount;
}
/** {@collect.stats}
* Returns the number of children that are expanded to
* <code>stopIndex</code>. This does not include the number
* of children that the child at <code>stopIndex</code> might
* have.
*/
protected int getNumExpandedChildrenTo(int stopIndex) {
FHTreeStateNode aChild;
int retCount = stopIndex;
for(int counter = 0, maxCounter = getChildCount();
counter < maxCounter; counter++) {
aChild = (FHTreeStateNode)getChildAt(counter);
if(aChild.childIndex >= stopIndex)
return retCount;
else {
retCount += aChild.getTotalChildCount();
}
}
return retCount;
}
/** {@collect.stats}
* Messaged when this node either expands or collapses.
*/
protected void didAdjustTree() {
}
} // FixedHeightLayoutCache.FHTreeStateNode
/** {@collect.stats}
* Used as a placeholder when getting the path in FHTreeStateNodes.
*/
private class SearchInfo {
protected FHTreeStateNode node;
protected boolean isNodeParentNode;
protected int childIndex;
protected TreePath getPath() {
if(node == null)
return null;
if(isNodeParentNode)
return node.getTreePath().pathByAddingChild(treeModel.getChild
(node.getUserObject(),
childIndex));
return node.path;
}
} // FixedHeightLayoutCache.SearchInfo
/** {@collect.stats}
* An enumerator to iterate through visible nodes.
*/
// This is very similiar to
// VariableHeightTreeState.VisibleTreeStateNodeEnumeration
private class VisibleFHTreeStateNodeEnumeration
implements Enumeration<TreePath>
{
/** {@collect.stats} Parent thats children are being enumerated. */
protected FHTreeStateNode parent;
/** {@collect.stats} Index of next child. An index of -1 signifies parent should be
* visibled next. */
protected int nextIndex;
/** {@collect.stats} Number of children in parent. */
protected int childCount;
protected VisibleFHTreeStateNodeEnumeration(FHTreeStateNode node) {
this(node, -1);
}
protected VisibleFHTreeStateNodeEnumeration(FHTreeStateNode parent,
int startIndex) {
this.parent = parent;
this.nextIndex = startIndex;
this.childCount = treeModel.getChildCount(this.parent.
getUserObject());
}
/** {@collect.stats}
* @return true if more visible nodes.
*/
public boolean hasMoreElements() {
return (parent != null);
}
/** {@collect.stats}
* @return next visible TreePath.
*/
public TreePath nextElement() {
if(!hasMoreElements())
throw new NoSuchElementException("No more visible paths");
TreePath retObject;
if(nextIndex == -1)
retObject = parent.getTreePath();
else {
FHTreeStateNode node = parent.getChildAtModelIndex(nextIndex);
if(node == null)
retObject = parent.getTreePath().pathByAddingChild
(treeModel.getChild(parent.getUserObject(),
nextIndex));
else
retObject = node.getTreePath();
}
updateNextObject();
return retObject;
}
/** {@collect.stats}
* Determines the next object by invoking <code>updateNextIndex</code>
* and if not succesful <code>findNextValidParent</code>.
*/
protected void updateNextObject() {
if(!updateNextIndex()) {
findNextValidParent();
}
}
/** {@collect.stats}
* Finds the next valid parent, this should be called when nextIndex
* is beyond the number of children of the current parent.
*/
protected boolean findNextValidParent() {
if(parent == root) {
// mark as invalid!
parent = null;
return false;
}
while(parent != null) {
FHTreeStateNode newParent = (FHTreeStateNode)parent.
getParent();
if(newParent != null) {
nextIndex = parent.childIndex;
parent = newParent;
childCount = treeModel.getChildCount
(parent.getUserObject());
if(updateNextIndex())
return true;
}
else
parent = null;
}
return false;
}
/** {@collect.stats}
* Updates <code>nextIndex</code> returning false if it is beyond
* the number of children of parent.
*/
protected boolean updateNextIndex() {
// nextIndex == -1 identifies receiver, make sure is expanded
// before descend.
if(nextIndex == -1 && !parent.isExpanded()) {
return false;
}
// Check that it can have kids
if(childCount == 0) {
return false;
}
// Make sure next index not beyond child count.
else if(++nextIndex >= childCount) {
return false;
}
FHTreeStateNode child = parent.getChildAtModelIndex(nextIndex);
if(child != null && child.isExpanded()) {
parent = child;
nextIndex = -1;
childCount = treeModel.getChildCount(child.getUserObject());
}
return true;
}
} // FixedHeightLayoutCache.VisibleFHTreeStateNodeEnumeration
}
|
Java
|
/*
* Copyright (c) 1997, 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.tree;
import javax.swing.event.*;
import java.beans.PropertyChangeListener;
/** {@collect.stats}
* This interface represents the current state of the selection for
* the tree component.
* For information and examples of using tree selection models,
* see <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Trees</a>
* in <em>The Java Tutorial.</em>
*
* <p>
* The state of the tree selection is characterized by
* a set of TreePaths, and optionally a set of integers. The mapping
* from TreePath to integer is done by way of an instance of RowMapper.
* It is not necessary for a TreeSelectionModel to have a RowMapper to
* correctly operate, but without a RowMapper <code>getSelectionRows</code>
* will return null.
*
* <p>
*
* A TreeSelectionModel can be configured to allow only one
* path (<code>SINGLE_TREE_SELECTION</code>) a number of
* continguous paths (<code>CONTIGUOUS_TREE_SELECTION</code>) or a number of
* discontiguous paths (<code>DISCONTIGUOUS_TREE_SELECTION</code>).
* A <code>RowMapper</code> is used to determine if TreePaths are
* contiguous.
* In the absence of a RowMapper <code>CONTIGUOUS_TREE_SELECTION</code> and
* <code>DISCONTIGUOUS_TREE_SELECTION</code> behave the same, that is they
* allow any number of paths to be contained in the TreeSelectionModel.
*
* <p>
*
* For a selection model of <code>CONTIGUOUS_TREE_SELECTION</code> any
* time the paths are changed (<code>setSelectionPath</code>,
* <code>addSelectionPath</code> ...) the TreePaths are again checked to
* make they are contiguous. A check of the TreePaths can also be forced
* by invoking <code>resetRowSelection</code>. How a set of discontiguous
* TreePaths is mapped to a contiguous set is left to implementors of
* this interface to enforce a particular policy.
*
* <p>
*
* Implementations should combine duplicate TreePaths that are
* added to the selection. For example, the following code
* <pre>
* TreePath[] paths = new TreePath[] { treePath, treePath };
* treeSelectionModel.setSelectionPaths(paths);
* </pre>
* should result in only one path being selected:
* <code>treePath</code>, and
* not two copies of <code>treePath</code>.
*
* <p>
*
* The lead TreePath is the last path that was added (or set). The lead
* row is then the row that corresponds to the TreePath as determined
* from the RowMapper.
*
* @author Scott Violet
*/
public interface TreeSelectionModel
{
/** {@collect.stats} Selection can only contain one path at a time. */
public static final int SINGLE_TREE_SELECTION = 1;
/** {@collect.stats} Selection can only be contiguous. This will only be enforced if
* a RowMapper instance is provided. That is, if no RowMapper is set
* this behaves the same as DISCONTIGUOUS_TREE_SELECTION. */
public static final int CONTIGUOUS_TREE_SELECTION = 2;
/** {@collect.stats} Selection can contain any number of items that are not necessarily
* contiguous. */
public static final int DISCONTIGUOUS_TREE_SELECTION = 4;
/** {@collect.stats}
* Sets the selection model, which must be one of SINGLE_TREE_SELECTION,
* CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.
* <p>
* This may change the selection if the current selection is not valid
* for the new mode. For example, if three TreePaths are
* selected when the mode is changed to <code>SINGLE_TREE_SELECTION</code>,
* only one TreePath will remain selected. It is up to the particular
* implementation to decide what TreePath remains selected.
*/
void setSelectionMode(int mode);
/** {@collect.stats}
* Returns the current selection mode, one of
* <code>SINGLE_TREE_SELECTION</code>,
* <code>CONTIGUOUS_TREE_SELECTION</code> or
* <code>DISCONTIGUOUS_TREE_SELECTION</code>.
*/
int getSelectionMode();
/** {@collect.stats}
* Sets the selection to path. If this represents a change, then
* the TreeSelectionListeners are notified. If <code>path</code> is
* null, this has the same effect as invoking <code>clearSelection</code>.
*
* @param path new path to select
*/
void setSelectionPath(TreePath path);
/** {@collect.stats}
* Sets the selection to path. If this represents a change, then
* the TreeSelectionListeners are notified. If <code>paths</code> is
* null, this has the same effect as invoking <code>clearSelection</code>.
*
* @param paths new selection
*/
void setSelectionPaths(TreePath[] paths);
/** {@collect.stats}
* Adds path to the current selection. If path is not currently
* in the selection the TreeSelectionListeners are notified. This has
* no effect if <code>path</code> is null.
*
* @param path the new path to add to the current selection
*/
void addSelectionPath(TreePath path);
/** {@collect.stats}
* Adds paths to the current selection. If any of the paths in
* paths are not currently in the selection the TreeSelectionListeners
* are notified. This has
* no effect if <code>paths</code> is null.
*
* @param paths the new paths to add to the current selection
*/
void addSelectionPaths(TreePath[] paths);
/** {@collect.stats}
* Removes path from the selection. If path is in the selection
* The TreeSelectionListeners are notified. This has no effect if
* <code>path</code> is null.
*
* @param path the path to remove from the selection
*/
void removeSelectionPath(TreePath path);
/** {@collect.stats}
* Removes paths from the selection. If any of the paths in
* <code>paths</code>
* are in the selection, the TreeSelectionListeners are notified.
* This method has no effect if <code>paths</code> is null.
*
* @param paths the path to remove from the selection
*/
void removeSelectionPaths(TreePath[] paths);
/** {@collect.stats}
* Returns the first path in the selection. How first is defined is
* up to implementors, and may not necessarily be the TreePath with
* the smallest integer value as determined from the
* <code>RowMapper</code>.
*/
TreePath getSelectionPath();
/** {@collect.stats}
* Returns the paths in the selection. This will return null (or an
* empty array) if nothing is currently selected.
*/
TreePath[] getSelectionPaths();
/** {@collect.stats}
* Returns the number of paths that are selected.
*/
int getSelectionCount();
/** {@collect.stats}
* Returns true if the path, <code>path</code>, is in the current
* selection.
*/
boolean isPathSelected(TreePath path);
/** {@collect.stats}
* Returns true if the selection is currently empty.
*/
boolean isSelectionEmpty();
/** {@collect.stats}
* Empties the current selection. If this represents a change in the
* current selection, the selection listeners are notified.
*/
void clearSelection();
/** {@collect.stats}
* Sets the RowMapper instance. This instance is used to determine
* the row for a particular TreePath.
*/
void setRowMapper(RowMapper newMapper);
/** {@collect.stats}
* Returns the RowMapper instance that is able to map a TreePath to a
* row.
*/
RowMapper getRowMapper();
/** {@collect.stats}
* Returns all of the currently selected rows. This will return
* null (or an empty array) if there are no selected TreePaths or
* a RowMapper has not been set.
*/
int[] getSelectionRows();
/** {@collect.stats}
* Returns the smallest value obtained from the RowMapper for the
* current set of selected TreePaths. If nothing is selected,
* or there is no RowMapper, this will return -1.
*/
int getMinSelectionRow();
/** {@collect.stats}
* Returns the largest value obtained from the RowMapper for the
* current set of selected TreePaths. If nothing is selected,
* or there is no RowMapper, this will return -1.
*/
int getMaxSelectionRow();
/** {@collect.stats}
* Returns true if the row identified by <code>row</code> is selected.
*/
boolean isRowSelected(int row);
/** {@collect.stats}
* Updates this object's mapping from TreePaths to rows. This should
* be invoked when the mapping from TreePaths to integers has changed
* (for example, a node has been expanded).
* <p>
* You do not normally have to call this; JTree and its associated
* listeners will invoke this for you. If you are implementing your own
* view class, then you will have to invoke this.
*/
void resetRowSelection();
/** {@collect.stats}
* Returns the lead selection index. That is the last index that was
* added.
*/
int getLeadSelectionRow();
/** {@collect.stats}
* Returns the last path that was added. This may differ from the
* leadSelectionPath property maintained by the JTree.
*/
TreePath getLeadSelectionPath();
/** {@collect.stats}
* Adds a PropertyChangeListener to the listener list.
* The listener is registered for all properties.
* <p>
* A PropertyChangeEvent will get fired when the selection mode
* changes.
*
* @param listener the PropertyChangeListener to be added
*/
void addPropertyChangeListener(PropertyChangeListener listener);
/** {@collect.stats}
* Removes a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param listener the PropertyChangeListener to be removed
*/
void removePropertyChangeListener(PropertyChangeListener listener);
/** {@collect.stats}
* Adds x to the list of listeners that are notified each time the
* set of selected TreePaths changes.
*
* @param x the new listener to be added
*/
void addTreeSelectionListener(TreeSelectionListener x);
/** {@collect.stats}
* Removes x from the list of listeners that are notified each time
* the set of selected TreePaths changes.
*
* @param x the listener to remove
*/
void removeTreeSelectionListener(TreeSelectionListener x);
}
|
Java
|
/*
* Copyright (c) 1998, 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.tree;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.EventObject;
import java.util.Vector;
/** {@collect.stats}
* A <code>TreeCellEditor</code>. You need to supply an
* instance of <code>DefaultTreeCellRenderer</code>
* so that the icons can be obtained. You can optionally supply
* a <code>TreeCellEditor</code> that will be layed out according
* to the icon in the <code>DefaultTreeCellRenderer</code>.
* If you do not supply a <code>TreeCellEditor</code>,
* a <code>TextField</code> will be used. Editing is started
* on a triple mouse click, or after a click, pause, click and
* a delay of 1200 miliseconds.
*<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.JTree
*
* @author Scott Violet
*/
public class DefaultTreeCellEditor implements ActionListener, TreeCellEditor,
TreeSelectionListener {
/** {@collect.stats} Editor handling the editing. */
protected TreeCellEditor realEditor;
/** {@collect.stats} Renderer, used to get border and offsets from. */
protected DefaultTreeCellRenderer renderer;
/** {@collect.stats} Editing container, will contain the <code>editorComponent</code>. */
protected Container editingContainer;
/** {@collect.stats}
* Component used in editing, obtained from the
* <code>editingContainer</code>.
*/
transient protected Component editingComponent;
/** {@collect.stats}
* As of Java 2 platform v1.4 this field should no longer be used. If
* you wish to provide similar behavior you should directly override
* <code>isCellEditable</code>.
*/
protected boolean canEdit;
/** {@collect.stats}
* Used in editing. Indicates x position to place
* <code>editingComponent</code>.
*/
protected transient int offset;
/** {@collect.stats} <code>JTree</code> instance listening too. */
protected transient JTree tree;
/** {@collect.stats} Last path that was selected. */
protected transient TreePath lastPath;
/** {@collect.stats} Used before starting the editing session. */
protected transient Timer timer;
/** {@collect.stats}
* Row that was last passed into
* <code>getTreeCellEditorComponent</code>.
*/
protected transient int lastRow;
/** {@collect.stats} True if the border selection color should be drawn. */
protected Color borderSelectionColor;
/** {@collect.stats} Icon to use when editing. */
protected transient Icon editingIcon;
/** {@collect.stats}
* Font to paint with, <code>null</code> indicates
* font of renderer is to be used.
*/
protected Font font;
/** {@collect.stats}
* Constructs a <code>DefaultTreeCellEditor</code>
* object for a JTree using the specified renderer and
* a default editor. (Use this constructor for normal editing.)
*
* @param tree a <code>JTree</code> object
* @param renderer a <code>DefaultTreeCellRenderer</code> object
*/
public DefaultTreeCellEditor(JTree tree,
DefaultTreeCellRenderer renderer) {
this(tree, renderer, null);
}
/** {@collect.stats}
* Constructs a <code>DefaultTreeCellEditor</code>
* object for a <code>JTree</code> using the
* specified renderer and the specified editor. (Use this constructor
* for specialized editing.)
*
* @param tree a <code>JTree</code> object
* @param renderer a <code>DefaultTreeCellRenderer</code> object
* @param editor a <code>TreeCellEditor</code> object
*/
public DefaultTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer,
TreeCellEditor editor) {
this.renderer = renderer;
realEditor = editor;
if(realEditor == null)
realEditor = createTreeCellEditor();
editingContainer = createContainer();
setTree(tree);
setBorderSelectionColor(UIManager.getColor
("Tree.editorBorderSelectionColor"));
}
/** {@collect.stats}
* Sets the color to use for the border.
* @param newColor the new border color
*/
public void setBorderSelectionColor(Color newColor) {
borderSelectionColor = newColor;
}
/** {@collect.stats}
* Returns the color the border is drawn.
* @return the border selection color
*/
public Color getBorderSelectionColor() {
return borderSelectionColor;
}
/** {@collect.stats}
* Sets the font to edit with. <code>null</code> indicates
* the renderers font should be used. This will NOT
* override any font you have set in the editor
* the receiver was instantied with. If <code>null</code>
* for an editor was passed in a default editor will be
* created that will pick up this font.
*
* @param font the editing <code>Font</code>
* @see #getFont
*/
public void setFont(Font font) {
this.font = font;
}
/** {@collect.stats}
* Gets the font used for editing.
*
* @return the editing <code>Font</code>
* @see #setFont
*/
public Font getFont() {
return font;
}
//
// TreeCellEditor
//
/** {@collect.stats}
* Configures the editor. Passed onto the <code>realEditor</code>.
*/
public Component getTreeCellEditorComponent(JTree tree, Object value,
boolean isSelected,
boolean expanded,
boolean leaf, int row) {
setTree(tree);
lastRow = row;
determineOffset(tree, value, isSelected, expanded, leaf, row);
if (editingComponent != null) {
editingContainer.remove(editingComponent);
}
editingComponent = realEditor.getTreeCellEditorComponent(tree, value,
isSelected, expanded,leaf, row);
// this is kept for backwards compatability but isn't really needed
// with the current BasicTreeUI implementation.
TreePath newPath = tree.getPathForRow(row);
canEdit = (lastPath != null && newPath != null &&
lastPath.equals(newPath));
Font font = getFont();
if(font == null) {
if(renderer != null)
font = renderer.getFont();
if(font == null)
font = tree.getFont();
}
editingContainer.setFont(font);
prepareForEditing();
return editingContainer;
}
/** {@collect.stats}
* Returns the value currently being edited.
* @return the value currently being edited
*/
public Object getCellEditorValue() {
return realEditor.getCellEditorValue();
}
/** {@collect.stats}
* If the <code>realEditor</code> returns true to this
* message, <code>prepareForEditing</code>
* is messaged and true is returned.
*/
public boolean isCellEditable(EventObject event) {
boolean retValue = false;
boolean editable = false;
if (event != null) {
if (event.getSource() instanceof JTree) {
setTree((JTree)event.getSource());
if (event instanceof MouseEvent) {
TreePath path = tree.getPathForLocation(
((MouseEvent)event).getX(),
((MouseEvent)event).getY());
editable = (lastPath != null && path != null &&
lastPath.equals(path));
if (path!=null) {
lastRow = tree.getRowForPath(path);
Object value = path.getLastPathComponent();
boolean isSelected = tree.isRowSelected(lastRow);
boolean expanded = tree.isExpanded(path);
TreeModel treeModel = tree.getModel();
boolean leaf = treeModel.isLeaf(value);
determineOffset(tree, value, isSelected,
expanded, leaf, lastRow);
}
}
}
}
if(!realEditor.isCellEditable(event))
return false;
if(canEditImmediately(event))
retValue = true;
else if(editable && shouldStartEditingTimer(event)) {
startEditingTimer();
}
else if(timer != null && timer.isRunning())
timer.stop();
if(retValue)
prepareForEditing();
return retValue;
}
/** {@collect.stats}
* Messages the <code>realEditor</code> for the return value.
*/
public boolean shouldSelectCell(EventObject event) {
return realEditor.shouldSelectCell(event);
}
/** {@collect.stats}
* If the <code>realEditor</code> will allow editing to stop,
* the <code>realEditor</code> is removed and true is returned,
* otherwise false is returned.
*/
public boolean stopCellEditing() {
if(realEditor.stopCellEditing()) {
cleanupAfterEditing();
return true;
}
return false;
}
/** {@collect.stats}
* Messages <code>cancelCellEditing</code> to the
* <code>realEditor</code> and removes it from this instance.
*/
public void cancelCellEditing() {
realEditor.cancelCellEditing();
cleanupAfterEditing();
}
/** {@collect.stats}
* Adds the <code>CellEditorListener</code>.
* @param l the listener to be added
*/
public void addCellEditorListener(CellEditorListener l) {
realEditor.addCellEditorListener(l);
}
/** {@collect.stats}
* Removes the previously added <code>CellEditorListener</code>.
* @param l the listener to be removed
*/
public void removeCellEditorListener(CellEditorListener l) {
realEditor.removeCellEditorListener(l);
}
/** {@collect.stats}
* Returns an array of all the <code>CellEditorListener</code>s added
* to this DefaultTreeCellEditor with addCellEditorListener().
*
* @return all of the <code>CellEditorListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public CellEditorListener[] getCellEditorListeners() {
return ((DefaultCellEditor)realEditor).getCellEditorListeners();
}
//
// TreeSelectionListener
//
/** {@collect.stats}
* Resets <code>lastPath</code>.
*/
public void valueChanged(TreeSelectionEvent e) {
if(tree != null) {
if(tree.getSelectionCount() == 1)
lastPath = tree.getSelectionPath();
else
lastPath = null;
}
if(timer != null) {
timer.stop();
}
}
//
// ActionListener (for Timer).
//
/** {@collect.stats}
* Messaged when the timer fires, this will start the editing
* session.
*/
public void actionPerformed(ActionEvent e) {
if(tree != null && lastPath != null) {
tree.startEditingAtPath(lastPath);
}
}
//
// Local methods
//
/** {@collect.stats}
* Sets the tree currently editing for. This is needed to add
* a selection listener.
* @param newTree the new tree to be edited
*/
protected void setTree(JTree newTree) {
if(tree != newTree) {
if(tree != null)
tree.removeTreeSelectionListener(this);
tree = newTree;
if(tree != null)
tree.addTreeSelectionListener(this);
if(timer != null) {
timer.stop();
}
}
}
/** {@collect.stats}
* Returns true if <code>event</code> is a <code>MouseEvent</code>
* and the click count is 1.
* @param event the event being studied
*/
protected boolean shouldStartEditingTimer(EventObject event) {
if((event instanceof MouseEvent) &&
SwingUtilities.isLeftMouseButton((MouseEvent)event)) {
MouseEvent me = (MouseEvent)event;
return (me.getClickCount() == 1 &&
inHitRegion(me.getX(), me.getY()));
}
return false;
}
/** {@collect.stats}
* Starts the editing timer.
*/
protected void startEditingTimer() {
if(timer == null) {
timer = new Timer(1200, this);
timer.setRepeats(false);
}
timer.start();
}
/** {@collect.stats}
* Returns true if <code>event</code> is <code>null</code>,
* or it is a <code>MouseEvent</code> with a click count > 2
* and <code>inHitRegion</code> returns true.
* @param event the event being studied
*/
protected boolean canEditImmediately(EventObject event) {
if((event instanceof MouseEvent) &&
SwingUtilities.isLeftMouseButton((MouseEvent)event)) {
MouseEvent me = (MouseEvent)event;
return ((me.getClickCount() > 2) &&
inHitRegion(me.getX(), me.getY()));
}
return (event == null);
}
/** {@collect.stats}
* Returns true if the passed in location is a valid mouse location
* to start editing from. This is implemented to return false if
* <code>x</code> is <= the width of the icon and icon gap displayed
* by the renderer. In other words this returns true if the user
* clicks over the text part displayed by the renderer, and false
* otherwise.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return true if the passed in location is a valid mouse location
*/
protected boolean inHitRegion(int x, int y) {
if(lastRow != -1 && tree != null) {
Rectangle bounds = tree.getRowBounds(lastRow);
ComponentOrientation treeOrientation = tree.getComponentOrientation();
if ( treeOrientation.isLeftToRight() ) {
if (bounds != null && x <= (bounds.x + offset) &&
offset < (bounds.width - 5)) {
return false;
}
} else if ( bounds != null &&
( x >= (bounds.x+bounds.width-offset+5) ||
x <= (bounds.x + 5) ) &&
offset < (bounds.width - 5) ) {
return false;
}
}
return true;
}
protected void determineOffset(JTree tree, Object value,
boolean isSelected, boolean expanded,
boolean leaf, int row) {
if(renderer != null) {
if(leaf)
editingIcon = renderer.getLeafIcon();
else if(expanded)
editingIcon = renderer.getOpenIcon();
else
editingIcon = renderer.getClosedIcon();
if(editingIcon != null)
offset = renderer.getIconTextGap() +
editingIcon.getIconWidth();
else
offset = renderer.getIconTextGap();
}
else {
editingIcon = null;
offset = 0;
}
}
/** {@collect.stats}
* Invoked just before editing is to start. Will add the
* <code>editingComponent</code> to the
* <code>editingContainer</code>.
*/
protected void prepareForEditing() {
if (editingComponent != null) {
editingContainer.add(editingComponent);
}
}
/** {@collect.stats}
* Creates the container to manage placement of
* <code>editingComponent</code>.
*/
protected Container createContainer() {
return new EditorContainer();
}
/** {@collect.stats}
* This is invoked if a <code>TreeCellEditor</code>
* is not supplied in the constructor.
* It returns a <code>TextField</code> editor.
* @return a new <code>TextField</code> editor
*/
protected TreeCellEditor createTreeCellEditor() {
Border aBorder = UIManager.getBorder("Tree.editorBorder");
DefaultCellEditor editor = new DefaultCellEditor
(new DefaultTextField(aBorder)) {
public boolean shouldSelectCell(EventObject event) {
boolean retValue = super.shouldSelectCell(event);
return retValue;
}
};
// One click to edit.
editor.setClickCountToStart(1);
return editor;
}
/** {@collect.stats}
* Cleans up any state after editing has completed. Removes the
* <code>editingComponent</code> the <code>editingContainer</code>.
*/
private void cleanupAfterEditing() {
if (editingComponent != null) {
editingContainer.remove(editingComponent);
}
editingComponent = null;
}
// Serialization support.
private void writeObject(ObjectOutputStream s) throws IOException {
Vector values = new Vector();
s.defaultWriteObject();
// Save the realEditor, if its Serializable.
if(realEditor != null && realEditor instanceof Serializable) {
values.addElement("realEditor");
values.addElement(realEditor);
}
s.writeObject(values);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
Vector values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("realEditor")) {
realEditor = (TreeCellEditor)values.elementAt(++indexCounter);
indexCounter++;
}
}
/** {@collect.stats}
* <code>TextField</code> used when no editor is supplied.
* This textfield locks into the border it is constructed with.
* It also prefers its parents font over its font. And if the
* renderer is not <code>null</code> and no font
* has been specified the preferred height is that of the renderer.
*/
public class DefaultTextField extends JTextField {
/** {@collect.stats} Border to use. */
protected Border border;
/** {@collect.stats}
* Constructs a
* <code>DefaultTreeCellEditor.DefaultTextField</code> object.
*
* @param border a <code>Border</code> object
* @since 1.4
*/
public DefaultTextField(Border border) {
setBorder(border);
}
/** {@collect.stats}
* Sets the border of this component.<p>
* This is a bound property.
*
* @param border the border to be rendered for this component
* @see Border
* @see CompoundBorder
* @beaninfo
* bound: true
* preferred: true
* attribute: visualUpdate true
* description: The component's border.
*/
public void setBorder(Border border) {
super.setBorder(border);
this.border = border;
}
/** {@collect.stats}
* Overrides <code>JComponent.getBorder</code> to
* returns the current border.
*/
public Border getBorder() {
return border;
}
// implements java.awt.MenuContainer
public Font getFont() {
Font font = super.getFont();
// Prefer the parent containers font if our font is a
// FontUIResource
if(font instanceof FontUIResource) {
Container parent = getParent();
if(parent != null && parent.getFont() != null)
font = parent.getFont();
}
return font;
}
/** {@collect.stats}
* Overrides <code>JTextField.getPreferredSize</code> to
* return the preferred size based on current font, if set,
* or else use renderer's font.
* @return a <code>Dimension</code> object containing
* the preferred size
*/
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
// If not font has been set, prefer the renderers height.
if(renderer != null &&
DefaultTreeCellEditor.this.getFont() == null) {
Dimension rSize = renderer.getPreferredSize();
size.height = rSize.height;
}
return size;
}
}
/** {@collect.stats}
* Container responsible for placing the <code>editingComponent</code>.
*/
public class EditorContainer extends Container {
/** {@collect.stats}
* Constructs an <code>EditorContainer</code> object.
*/
public EditorContainer() {
setLayout(null);
}
// This should not be used. It will be removed when new API is
// allowed.
public void EditorContainer() {
setLayout(null);
}
/** {@collect.stats}
* Overrides <code>Container.paint</code> to paint the node's
* icon and use the selection color for the background.
*/
public void paint(Graphics g) {
int width = getWidth();
int height = getHeight();
// Then the icon.
if(editingIcon != null) {
int yLoc = calculateIconY(editingIcon);
if (getComponentOrientation().isLeftToRight()) {
editingIcon.paintIcon(this, g, 0, yLoc);
} else {
editingIcon.paintIcon(
this, g, width - editingIcon.getIconWidth(),
yLoc);
}
}
// Border selection color
Color background = getBorderSelectionColor();
if(background != null) {
g.setColor(background);
g.drawRect(0, 0, width - 1, height - 1);
}
super.paint(g);
}
/** {@collect.stats}
* Lays out this <code>Container</code>. If editing,
* the editor will be placed at
* <code>offset</code> in the x direction and 0 for y.
*/
public void doLayout() {
if(editingComponent != null) {
int width = getWidth();
int height = getHeight();
if (getComponentOrientation().isLeftToRight()) {
editingComponent.setBounds(
offset, 0, width - offset, height);
} else {
editingComponent.setBounds(
0, 0, width - offset, height);
}
}
}
/** {@collect.stats}
* Calculate the y location for the icon.
*/
private int calculateIconY(Icon icon) {
// To make sure the icon position matches that of the
// renderer, use the same algorithm as JLabel
// (SwingUtilities.layoutCompoundLabel).
int iconHeight = icon.getIconHeight();
int textHeight = editingComponent.getFontMetrics(
editingComponent.getFont()).getHeight();
int textY = iconHeight / 2 - textHeight / 2;
int totalY = Math.min(0, textY);
int totalHeight = Math.max(iconHeight, textY + textHeight) -
totalY;
return getHeight() / 2 - (totalY + (totalHeight / 2));
}
/** {@collect.stats}
* Returns the preferred size for the <code>Container</code>.
* This will be at least preferred size of the editor plus
* <code>offset</code>.
* @return a <code>Dimension</code> containing the preferred
* size for the <code>Container</code>; if
* <code>editingComponent</code> is <code>null</code> the
* <code>Dimension</code> returned is 0, 0
*/
public Dimension getPreferredSize() {
if(editingComponent != null) {
Dimension pSize = editingComponent.getPreferredSize();
pSize.width += offset + 5;
Dimension rSize = (renderer != null) ?
renderer.getPreferredSize() : null;
if(rSize != null)
pSize.height = Math.max(pSize.height, rSize.height);
if(editingIcon != null)
pSize.height = Math.max(pSize.height,
editingIcon.getIconHeight());
// Make sure width is at least 100.
pSize.width = Math.max(pSize.width, 100);
return pSize;
}
return new Dimension(0, 0);
}
}
}
|
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.tree;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.util.BitSet;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.event.*;
import javax.swing.DefaultListSelectionModel;
/** {@collect.stats}
* Default implementation of TreeSelectionModel. Listeners are notified
* whenever
* the paths in the selection change, not the rows. In order
* to be able to track row changes you may wish to become a listener
* for expansion events on the tree and test for changes from there.
* <p>resetRowSelection is called from any of the methods that update
* the selected paths. If you subclass any of these methods to
* filter what is allowed to be selected, be sure and message
* <code>resetRowSelection</code> if you do not message super.
*
* <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.JTree
*
* @author Scott Violet
*/
public class DefaultTreeSelectionModel extends Object implements Cloneable, Serializable, TreeSelectionModel
{
/** {@collect.stats} Property name for selectionMode. */
public static final String SELECTION_MODE_PROPERTY = "selectionMode";
/** {@collect.stats} Used to messaged registered listeners. */
protected SwingPropertyChangeSupport changeSupport;
/** {@collect.stats} Paths that are currently selected. Will be null if nothing is
* currently selected. */
protected TreePath[] selection;
/** {@collect.stats} Event listener list. */
protected EventListenerList listenerList = new EventListenerList();
/** {@collect.stats} Provides a row for a given path. */
transient protected RowMapper rowMapper;
/** {@collect.stats} Handles maintaining the list selection model. The RowMapper is used
* to map from a TreePath to a row, and the value is then placed here. */
protected DefaultListSelectionModel listSelectionModel;
/** {@collect.stats} Mode for the selection, will be either SINGLE_TREE_SELECTION,
* CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.
*/
protected int selectionMode;
/** {@collect.stats} Last path that was added. */
protected TreePath leadPath;
/** {@collect.stats} Index of the lead path in selection. */
protected int leadIndex;
/** {@collect.stats} Lead row. */
protected int leadRow;
/** {@collect.stats} Used to make sure the paths are unique, will contain all the paths
* in <code>selection</code>.
*/
private Hashtable uniquePaths;
private Hashtable lastPaths;
private TreePath[] tempPaths;
/** {@collect.stats}
* Creates a new instance of DefaultTreeSelectionModel that is
* empty, with a selection mode of DISCONTIGUOUS_TREE_SELECTION.
*/
public DefaultTreeSelectionModel() {
listSelectionModel = new DefaultListSelectionModel();
selectionMode = DISCONTIGUOUS_TREE_SELECTION;
leadIndex = leadRow = -1;
uniquePaths = new Hashtable();
lastPaths = new Hashtable();
tempPaths = new TreePath[1];
}
/** {@collect.stats}
* Sets the RowMapper instance. This instance is used to determine
* the row for a particular TreePath.
*/
public void setRowMapper(RowMapper newMapper) {
rowMapper = newMapper;
resetRowSelection();
}
/** {@collect.stats}
* Returns the RowMapper instance that is able to map a TreePath to a
* row.
*/
public RowMapper getRowMapper() {
return rowMapper;
}
/** {@collect.stats}
* Sets the selection model, which must be one of SINGLE_TREE_SELECTION,
* CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION. If mode
* is not one of the defined value,
* <code>DISCONTIGUOUS_TREE_SELECTION</code> is assumed.
* <p>This may change the selection if the current selection is not valid
* for the new mode. For example, if three TreePaths are
* selected when the mode is changed to <code>SINGLE_TREE_SELECTION</code>,
* only one TreePath will remain selected. It is up to the particular
* implementation to decide what TreePath remains selected.
* <p>
* Setting the mode to something other than the defined types will
* result in the mode becoming <code>DISCONTIGUOUS_TREE_SELECTION</code>.
*/
public void setSelectionMode(int mode) {
int oldMode = selectionMode;
selectionMode = mode;
if(selectionMode != TreeSelectionModel.SINGLE_TREE_SELECTION &&
selectionMode != TreeSelectionModel.CONTIGUOUS_TREE_SELECTION &&
selectionMode != TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION)
selectionMode = TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION;
if(oldMode != selectionMode && changeSupport != null)
changeSupport.firePropertyChange(SELECTION_MODE_PROPERTY,
new Integer(oldMode),
new Integer(selectionMode));
}
/** {@collect.stats}
* Returns the selection mode, one of <code>SINGLE_TREE_SELECTION</code>,
* <code>DISCONTIGUOUS_TREE_SELECTION</code> or
* <code>CONTIGUOUS_TREE_SELECTION</code>.
*/
public int getSelectionMode() {
return selectionMode;
}
/** {@collect.stats}
* Sets the selection to path. If this represents a change, then
* the TreeSelectionListeners are notified. If <code>path</code> is
* null, this has the same effect as invoking <code>clearSelection</code>.
*
* @param path new path to select
*/
public void setSelectionPath(TreePath path) {
if(path == null)
setSelectionPaths(null);
else {
TreePath[] newPaths = new TreePath[1];
newPaths[0] = path;
setSelectionPaths(newPaths);
}
}
/** {@collect.stats}
* Sets the selection to the paths in paths. If this represents a
* change the TreeSelectionListeners are notified. Potentially
* paths will be held by this object; in other words don't change
* any of the objects in the array once passed in.
* <p>If <code>paths</code> is
* null, this has the same effect as invoking <code>clearSelection</code>.
* <p>The lead path is set to the last path in <code>pPaths</code>.
* <p>If the selection mode is <code>CONTIGUOUS_TREE_SELECTION</code>,
* and adding the new paths would make the selection discontiguous,
* the selection is reset to the first TreePath in <code>paths</code>.
*
* @param pPaths new selection
*/
public void setSelectionPaths(TreePath[] pPaths) {
int newCount, newCounter, oldCount, oldCounter;
TreePath[] paths = pPaths;
if(paths == null)
newCount = 0;
else
newCount = paths.length;
if(selection == null)
oldCount = 0;
else
oldCount = selection.length;
if((newCount + oldCount) != 0) {
if(selectionMode == TreeSelectionModel.SINGLE_TREE_SELECTION) {
/* If single selection and more than one path, only allow
first. */
if(newCount > 1) {
paths = new TreePath[1];
paths[0] = pPaths[0];
newCount = 1;
}
}
else if(selectionMode ==
TreeSelectionModel.CONTIGUOUS_TREE_SELECTION) {
/* If contiguous selection and paths aren't contiguous,
only select the first path item. */
if(newCount > 0 && !arePathsContiguous(paths)) {
paths = new TreePath[1];
paths[0] = pPaths[0];
newCount = 1;
}
}
int validCount = 0;
TreePath beginLeadPath = leadPath;
Vector cPaths = new Vector(newCount + oldCount);
lastPaths.clear();
leadPath = null;
/* Find the paths that are new. */
for(newCounter = 0; newCounter < newCount; newCounter++) {
if(paths[newCounter] != null &&
lastPaths.get(paths[newCounter]) == null) {
validCount++;
lastPaths.put(paths[newCounter], Boolean.TRUE);
if (uniquePaths.get(paths[newCounter]) == null) {
cPaths.addElement(new PathPlaceHolder
(paths[newCounter], true));
}
leadPath = paths[newCounter];
}
}
/* If the validCount isn't equal to newCount it means there
are some null in paths, remove them and set selection to
the new path. */
TreePath[] newSelection;
if(validCount == 0) {
newSelection = null;
}
else if (validCount != newCount) {
Enumeration keys = lastPaths.keys();
newSelection = new TreePath[validCount];
validCount = 0;
while (keys.hasMoreElements()) {
newSelection[validCount++] = (TreePath)keys.nextElement();
}
}
else {
newSelection = new TreePath[paths.length];
System.arraycopy(paths, 0, newSelection, 0, paths.length);
}
/* Get the paths that were selected but no longer selected. */
for(oldCounter = 0; oldCounter < oldCount; oldCounter++)
if(selection[oldCounter] != null &&
lastPaths.get(selection[oldCounter]) == null)
cPaths.addElement(new PathPlaceHolder
(selection[oldCounter], false));
selection = newSelection;
Hashtable tempHT = uniquePaths;
uniquePaths = lastPaths;
lastPaths = tempHT;
lastPaths.clear();
// No reason to do this now, but will still call it.
if(selection != null)
insureUniqueness();
updateLeadIndex();
resetRowSelection();
/* Notify of the change. */
if(cPaths.size() > 0)
notifyPathChange(cPaths, beginLeadPath);
}
}
/** {@collect.stats}
* Adds path to the current selection. If path is not currently
* in the selection the TreeSelectionListeners are notified. This has
* no effect if <code>path</code> is null.
*
* @param path the new path to add to the current selection
*/
public void addSelectionPath(TreePath path) {
if(path != null) {
TreePath[] toAdd = new TreePath[1];
toAdd[0] = path;
addSelectionPaths(toAdd);
}
}
/** {@collect.stats}
* Adds paths to the current selection. If any of the paths in
* paths are not currently in the selection the TreeSelectionListeners
* are notified. This has
* no effect if <code>paths</code> is null.
* <p>The lead path is set to the last element in <code>paths</code>.
* <p>If the selection mode is <code>CONTIGUOUS_TREE_SELECTION</code>,
* and adding the new paths would make the selection discontiguous.
* Then two things can result: if the TreePaths in <code>paths</code>
* are contiguous, then the selection becomes these TreePaths,
* otherwise the TreePaths aren't contiguous and the selection becomes
* the first TreePath in <code>paths</code>.
*
* @param paths the new path to add to the current selection
*/
public void addSelectionPaths(TreePath[] paths) {
int newPathLength = ((paths == null) ? 0 : paths.length);
if(newPathLength > 0) {
if(selectionMode == TreeSelectionModel.SINGLE_TREE_SELECTION) {
setSelectionPaths(paths);
}
else if(selectionMode == TreeSelectionModel.
CONTIGUOUS_TREE_SELECTION && !canPathsBeAdded(paths)) {
if(arePathsContiguous(paths)) {
setSelectionPaths(paths);
}
else {
TreePath[] newPaths = new TreePath[1];
newPaths[0] = paths[0];
setSelectionPaths(newPaths);
}
}
else {
int counter, validCount;
int oldCount;
TreePath beginLeadPath = leadPath;
Vector cPaths = null;
if(selection == null)
oldCount = 0;
else
oldCount = selection.length;
/* Determine the paths that aren't currently in the
selection. */
lastPaths.clear();
for(counter = 0, validCount = 0; counter < newPathLength;
counter++) {
if(paths[counter] != null) {
if (uniquePaths.get(paths[counter]) == null) {
validCount++;
if(cPaths == null)
cPaths = new Vector();
cPaths.addElement(new PathPlaceHolder
(paths[counter], true));
uniquePaths.put(paths[counter], Boolean.TRUE);
lastPaths.put(paths[counter], Boolean.TRUE);
}
leadPath = paths[counter];
}
}
if(leadPath == null) {
leadPath = beginLeadPath;
}
if(validCount > 0) {
TreePath newSelection[] = new TreePath[oldCount +
validCount];
/* And build the new selection. */
if(oldCount > 0)
System.arraycopy(selection, 0, newSelection, 0,
oldCount);
if(validCount != paths.length) {
/* Some of the paths in paths are already in
the selection. */
Enumeration newPaths = lastPaths.keys();
counter = oldCount;
while (newPaths.hasMoreElements()) {
newSelection[counter++] = (TreePath)newPaths.
nextElement();
}
}
else {
System.arraycopy(paths, 0, newSelection, oldCount,
validCount);
}
selection = newSelection;
insureUniqueness();
updateLeadIndex();
resetRowSelection();
notifyPathChange(cPaths, beginLeadPath);
}
else
leadPath = beginLeadPath;
lastPaths.clear();
}
}
}
/** {@collect.stats}
* Removes path from the selection. If path is in the selection
* The TreeSelectionListeners are notified. This has no effect if
* <code>path</code> is null.
*
* @param path the path to remove from the selection
*/
public void removeSelectionPath(TreePath path) {
if(path != null) {
TreePath[] rPath = new TreePath[1];
rPath[0] = path;
removeSelectionPaths(rPath);
}
}
/** {@collect.stats}
* Removes paths from the selection. If any of the paths in paths
* are in the selection the TreeSelectionListeners are notified.
* This has no effect if <code>paths</code> is null.
*
* @param paths the paths to remove from the selection
*/
public void removeSelectionPaths(TreePath[] paths) {
if (paths != null && selection != null && paths.length > 0) {
if(!canPathsBeRemoved(paths)) {
/* Could probably do something more interesting here! */
clearSelection();
}
else {
Vector pathsToRemove = null;
/* Find the paths that can be removed. */
for (int removeCounter = paths.length - 1; removeCounter >= 0;
removeCounter--) {
if(paths[removeCounter] != null) {
if (uniquePaths.get(paths[removeCounter]) != null) {
if(pathsToRemove == null)
pathsToRemove = new Vector(paths.length);
uniquePaths.remove(paths[removeCounter]);
pathsToRemove.addElement(new PathPlaceHolder
(paths[removeCounter], false));
}
}
}
if(pathsToRemove != null) {
int removeCount = pathsToRemove.size();
TreePath beginLeadPath = leadPath;
if(removeCount == selection.length) {
selection = null;
}
else {
Enumeration pEnum = uniquePaths.keys();
int validCount = 0;
selection = new TreePath[selection.length -
removeCount];
while (pEnum.hasMoreElements()) {
selection[validCount++] = (TreePath)pEnum.
nextElement();
}
}
if (leadPath != null &&
uniquePaths.get(leadPath) == null) {
if (selection != null) {
leadPath = selection[selection.length - 1];
}
else {
leadPath = null;
}
}
else if (selection != null) {
leadPath = selection[selection.length - 1];
}
else {
leadPath = null;
}
updateLeadIndex();
resetRowSelection();
notifyPathChange(pathsToRemove, beginLeadPath);
}
}
}
}
/** {@collect.stats}
* Returns the first path in the selection. This is useful if there
* if only one item currently selected.
*/
public TreePath getSelectionPath() {
if(selection != null)
return selection[0];
return null;
}
/** {@collect.stats}
* Returns the paths in the selection. This will return null (or an
* empty array) if nothing is currently selected.
*/
public TreePath[] getSelectionPaths() {
if(selection != null) {
int pathSize = selection.length;
TreePath[] result = new TreePath[pathSize];
System.arraycopy(selection, 0, result, 0, pathSize);
return result;
}
return null;
}
/** {@collect.stats}
* Returns the number of paths that are selected.
*/
public int getSelectionCount() {
return (selection == null) ? 0 : selection.length;
}
/** {@collect.stats}
* Returns true if the path, <code>path</code>,
* is in the current selection.
*/
public boolean isPathSelected(TreePath path) {
return (path != null) ? (uniquePaths.get(path) != null) : false;
}
/** {@collect.stats}
* Returns true if the selection is currently empty.
*/
public boolean isSelectionEmpty() {
return (selection == null);
}
/** {@collect.stats}
* Empties the current selection. If this represents a change in the
* current selection, the selection listeners are notified.
*/
public void clearSelection() {
if(selection != null) {
int selSize = selection.length;
boolean[] newness = new boolean[selSize];
for(int counter = 0; counter < selSize; counter++)
newness[counter] = false;
TreeSelectionEvent event = new TreeSelectionEvent
(this, selection, newness, leadPath, null);
leadPath = null;
leadIndex = leadRow = -1;
uniquePaths.clear();
selection = null;
resetRowSelection();
fireValueChanged(event);
}
}
/** {@collect.stats}
* Adds x to the list of listeners that are notified each time the
* set of selected TreePaths changes.
*
* @param x the new listener to be added
*/
public void addTreeSelectionListener(TreeSelectionListener x) {
listenerList.add(TreeSelectionListener.class, x);
}
/** {@collect.stats}
* Removes x from the list of listeners that are notified each time
* the set of selected TreePaths changes.
*
* @param x the listener to remove
*/
public void removeTreeSelectionListener(TreeSelectionListener x) {
listenerList.remove(TreeSelectionListener.class, x);
}
/** {@collect.stats}
* Returns an array of all the tree selection listeners
* registered on this model.
*
* @return all of this model's <code>TreeSelectionListener</code>s
* or an empty
* array if no tree selection listeners are currently registered
*
* @see #addTreeSelectionListener
* @see #removeTreeSelectionListener
*
* @since 1.4
*/
public TreeSelectionListener[] getTreeSelectionListeners() {
return (TreeSelectionListener[])listenerList.getListeners(
TreeSelectionListener.class);
}
/** {@collect.stats}
* Notifies all listeners that are registered for
* tree selection events on this object.
* @see #addTreeSelectionListener
* @see EventListenerList
*/
protected void fireValueChanged(TreeSelectionEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// TreeSelectionEvent 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]==TreeSelectionListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((TreeSelectionListener)listeners[i+1]).valueChanged(e);
}
}
}
/** {@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>DefaultTreeSelectionModel</code> <code>m</code>
* for its tree selection listeners with the following code:
*
* <pre>TreeSelectionListener[] tsls = (TreeSelectionListener[])(m.getListeners(TreeSelectionListener.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 component,
* 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 #getTreeSelectionListeners
* @see #getPropertyChangeListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
/** {@collect.stats}
* Returns all of the currently selected rows. This will return
* null (or an empty array) if there are no selected TreePaths or
* a RowMapper has not been set.
* This may return an array of length less that than of the selected
* TreePaths if some of the rows are not visible (that is the
* RowMapper returned -1 for the row corresponding to the TreePath).
*/
public int[] getSelectionRows() {
// This is currently rather expensive. Needs
// to be better support from ListSelectionModel to speed this up.
if(rowMapper != null && selection != null) {
int[] rows = rowMapper.getRowsForPaths(selection);
if (rows != null) {
int invisCount = 0;
for (int counter = rows.length - 1; counter >= 0; counter--) {
if (rows[counter] == -1) {
invisCount++;
}
}
if (invisCount > 0) {
if (invisCount == rows.length) {
rows = null;
}
else {
int[] tempRows = new int[rows.length - invisCount];
for (int counter = rows.length - 1, visCounter = 0;
counter >= 0; counter--) {
if (rows[counter] != -1) {
tempRows[visCounter++] = rows[counter];
}
}
rows = tempRows;
}
}
}
return rows;
}
return null;
}
/** {@collect.stats}
* Returns the smallest value obtained from the RowMapper for the
* current set of selected TreePaths. If nothing is selected,
* or there is no RowMapper, this will return -1.
*/
public int getMinSelectionRow() {
return listSelectionModel.getMinSelectionIndex();
}
/** {@collect.stats}
* Returns the largest value obtained from the RowMapper for the
* current set of selected TreePaths. If nothing is selected,
* or there is no RowMapper, this will return -1.
*/
public int getMaxSelectionRow() {
return listSelectionModel.getMaxSelectionIndex();
}
/** {@collect.stats}
* Returns true if the row identified by <code>row</code> is selected.
*/
public boolean isRowSelected(int row) {
return listSelectionModel.isSelectedIndex(row);
}
/** {@collect.stats}
* Updates this object's mapping from TreePath to rows. This should
* be invoked when the mapping from TreePaths to integers has changed
* (for example, a node has been expanded).
* <p>You do not normally have to call this, JTree and its associated
* Listeners will invoke this for you. If you are implementing your own
* View class, then you will have to invoke this.
* <p>This will invoke <code>insureRowContinuity</code> to make sure
* the currently selected TreePaths are still valid based on the
* selection mode.
*/
public void resetRowSelection() {
listSelectionModel.clearSelection();
if(selection != null && rowMapper != null) {
int aRow;
int validCount = 0;
int[] rows = rowMapper.getRowsForPaths(selection);
for(int counter = 0, maxCounter = selection.length;
counter < maxCounter; counter++) {
aRow = rows[counter];
if(aRow != -1) {
listSelectionModel.addSelectionInterval(aRow, aRow);
}
}
if(leadIndex != -1 && rows != null) {
leadRow = rows[leadIndex];
}
else if (leadPath != null) {
// Lead selection path doesn't have to be in the selection.
tempPaths[0] = leadPath;
rows = rowMapper.getRowsForPaths(tempPaths);
leadRow = (rows != null) ? rows[0] : -1;
}
else {
leadRow = -1;
}
insureRowContinuity();
}
else
leadRow = -1;
}
/** {@collect.stats}
* Returns the lead selection index. That is the last index that was
* added.
*/
public int getLeadSelectionRow() {
return leadRow;
}
/** {@collect.stats}
* Returns the last path that was added. This may differ from the
* leadSelectionPath property maintained by the JTree.
*/
public TreePath getLeadSelectionPath() {
return leadPath;
}
/** {@collect.stats}
* Adds a PropertyChangeListener to the listener list.
* The listener is registered for all properties.
* <p>
* A PropertyChangeEvent will get fired when the selection mode
* changes.
*
* @param listener the PropertyChangeListener to be added
*/
public synchronized void addPropertyChangeListener(
PropertyChangeListener listener) {
if (changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
/** {@collect.stats}
* Removes a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param listener the PropertyChangeListener to be removed
*/
public synchronized void removePropertyChangeListener(
PropertyChangeListener listener) {
if (changeSupport == null) {
return;
}
changeSupport.removePropertyChangeListener(listener);
}
/** {@collect.stats}
* Returns an array of all the property change listeners
* registered on this <code>DefaultTreeSelectionModel</code>.
*
* @return all of this model's <code>PropertyChangeListener</code>s
* or an empty
* array if no property change listeners are currently registered
*
* @see #addPropertyChangeListener
* @see #removePropertyChangeListener
*
* @since 1.4
*/
public PropertyChangeListener[] getPropertyChangeListeners() {
if (changeSupport == null) {
return new PropertyChangeListener[0];
}
return changeSupport.getPropertyChangeListeners();
}
/** {@collect.stats}
* Makes sure the currently selected <code>TreePath</code>s are valid
* for the current selection mode.
* If the selection mode is <code>CONTIGUOUS_TREE_SELECTION</code>
* and a <code>RowMapper</code> exists, this will make sure all
* the rows are contiguous, that is, when sorted all the rows are
* in order with no gaps.
* If the selection isn't contiguous, the selection is
* reset to contain the first set, when sorted, of contiguous rows.
* <p>
* If the selection mode is <code>SINGLE_TREE_SELECTION</code> and
* more than one TreePath is selected, the selection is reset to
* contain the first path currently selected.
*/
protected void insureRowContinuity() {
if(selectionMode == TreeSelectionModel.CONTIGUOUS_TREE_SELECTION &&
selection != null && rowMapper != null) {
DefaultListSelectionModel lModel = listSelectionModel;
int min = lModel.getMinSelectionIndex();
if(min != -1) {
for(int counter = min,
maxCounter = lModel.getMaxSelectionIndex();
counter <= maxCounter; counter++) {
if(!lModel.isSelectedIndex(counter)) {
if(counter == min) {
clearSelection();
}
else {
TreePath[] newSel = new TreePath[counter - min];
int selectionIndex[] = rowMapper.getRowsForPaths(selection);
// find the actual selection pathes corresponded to the
// rows of the new selection
for (int i = 0; i < selectionIndex.length; i++) {
if (selectionIndex[i]<counter) {
newSel[selectionIndex[i]-min] = selection[i];
}
}
setSelectionPaths(newSel);
break;
}
}
}
}
}
else if(selectionMode == TreeSelectionModel.SINGLE_TREE_SELECTION &&
selection != null && selection.length > 1) {
setSelectionPath(selection[0]);
}
}
/** {@collect.stats}
* Returns true if the paths are contiguous,
* or this object has no RowMapper.
*/
protected boolean arePathsContiguous(TreePath[] paths) {
if(rowMapper == null || paths.length < 2)
return true;
else {
BitSet bitSet = new BitSet(32);
int anIndex, counter, min;
int pathCount = paths.length;
int validCount = 0;
TreePath[] tempPath = new TreePath[1];
tempPath[0] = paths[0];
min = rowMapper.getRowsForPaths(tempPath)[0];
for(counter = 0; counter < pathCount; counter++) {
if(paths[counter] != null) {
tempPath[0] = paths[counter];
int[] rows = rowMapper.getRowsForPaths(tempPath);
if (rows == null) {
return false;
}
anIndex = rows[0];
if(anIndex == -1 || anIndex < (min - pathCount) ||
anIndex > (min + pathCount))
return false;
if(anIndex < min)
min = anIndex;
if(!bitSet.get(anIndex)) {
bitSet.set(anIndex);
validCount++;
}
}
}
int maxCounter = validCount + min;
for(counter = min; counter < maxCounter; counter++)
if(!bitSet.get(counter))
return false;
}
return true;
}
/** {@collect.stats}
* Used to test if a particular set of <code>TreePath</code>s can
* be added. This will return true if <code>paths</code> is null (or
* empty), or this object has no RowMapper, or nothing is currently selected,
* or the selection mode is <code>DISCONTIGUOUS_TREE_SELECTION</code>, or
* adding the paths to the current selection still results in a
* contiguous set of <code>TreePath</code>s.
*/
protected boolean canPathsBeAdded(TreePath[] paths) {
if(paths == null || paths.length == 0 || rowMapper == null ||
selection == null || selectionMode ==
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION)
return true;
else {
BitSet bitSet = new BitSet();
DefaultListSelectionModel lModel = listSelectionModel;
int anIndex;
int counter;
int min = lModel.getMinSelectionIndex();
int max = lModel.getMaxSelectionIndex();
TreePath[] tempPath = new TreePath[1];
if(min != -1) {
for(counter = min; counter <= max; counter++) {
if(lModel.isSelectedIndex(counter))
bitSet.set(counter);
}
}
else {
tempPath[0] = paths[0];
min = max = rowMapper.getRowsForPaths(tempPath)[0];
}
for(counter = paths.length - 1; counter >= 0; counter--) {
if(paths[counter] != null) {
tempPath[0] = paths[counter];
int[] rows = rowMapper.getRowsForPaths(tempPath);
if (rows == null) {
return false;
}
anIndex = rows[0];
min = Math.min(anIndex, min);
max = Math.max(anIndex, max);
if(anIndex == -1)
return false;
bitSet.set(anIndex);
}
}
for(counter = min; counter <= max; counter++)
if(!bitSet.get(counter))
return false;
}
return true;
}
/** {@collect.stats}
* Returns true if the paths can be removed without breaking the
* continuity of the model.
* This is rather expensive.
*/
protected boolean canPathsBeRemoved(TreePath[] paths) {
if(rowMapper == null || selection == null ||
selectionMode == TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION)
return true;
else {
BitSet bitSet = new BitSet();
int counter;
int pathCount = paths.length;
int anIndex;
int min = -1;
int validCount = 0;
TreePath[] tempPath = new TreePath[1];
int[] rows;
/* Determine the rows for the removed entries. */
lastPaths.clear();
for (counter = 0; counter < pathCount; counter++) {
if (paths[counter] != null) {
lastPaths.put(paths[counter], Boolean.TRUE);
}
}
for(counter = selection.length - 1; counter >= 0; counter--) {
if(lastPaths.get(selection[counter]) == null) {
tempPath[0] = selection[counter];
rows = rowMapper.getRowsForPaths(tempPath);
if(rows != null && rows[0] != -1 && !bitSet.get(rows[0])) {
validCount++;
if(min == -1)
min = rows[0];
else
min = Math.min(min, rows[0]);
bitSet.set(rows[0]);
}
}
}
lastPaths.clear();
/* Make sure they are contiguous. */
if(validCount > 1) {
for(counter = min + validCount - 1; counter >= min;
counter--)
if(!bitSet.get(counter))
return false;
}
}
return true;
}
/** {@collect.stats}
* Notifies listeners of a change in path. changePaths should contain
* instances of PathPlaceHolder.
*/
protected void notifyPathChange(Vector<PathPlaceHolder> changedPaths,
TreePath oldLeadSelection) {
int cPathCount = changedPaths.size();
boolean[] newness = new boolean[cPathCount];
TreePath[] paths = new TreePath[cPathCount];
PathPlaceHolder placeholder;
for(int counter = 0; counter < cPathCount; counter++) {
placeholder = (PathPlaceHolder)changedPaths.elementAt(counter);
newness[counter] = placeholder.isNew;
paths[counter] = placeholder.path;
}
TreeSelectionEvent event = new TreeSelectionEvent
(this, paths, newness, oldLeadSelection, leadPath);
fireValueChanged(event);
}
/** {@collect.stats}
* Updates the leadIndex instance variable.
*/
protected void updateLeadIndex() {
if(leadPath != null) {
if(selection == null) {
leadPath = null;
leadIndex = leadRow = -1;
}
else {
leadRow = leadIndex = -1;
for(int counter = selection.length - 1; counter >= 0;
counter--) {
// Can use == here since we know leadPath came from
// selection
if(selection[counter] == leadPath) {
leadIndex = counter;
break;
}
}
}
}
else {
leadIndex = -1;
}
}
/** {@collect.stats}
* This method is obsolete and its implementation is now a noop. It's
* still called by setSelectionPaths and addSelectionPaths, but only
* for backwards compatability.
*/
protected void insureUniqueness() {
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public String toString() {
int selCount = getSelectionCount();
StringBuffer retBuffer = new StringBuffer();
int[] rows;
if(rowMapper != null)
rows = rowMapper.getRowsForPaths(selection);
else
rows = null;
retBuffer.append(getClass().getName() + " " + hashCode() + " [ ");
for(int counter = 0; counter < selCount; counter++) {
if(rows != null)
retBuffer.append(selection[counter].toString() + "@" +
Integer.toString(rows[counter])+ " ");
else
retBuffer.append(selection[counter].toString() + " ");
}
retBuffer.append("]");
return retBuffer.toString();
}
/** {@collect.stats}
* Returns a clone of this object with the same selection.
* This method does not duplicate
* selection listeners and property listeners.
*
* @exception CloneNotSupportedException never thrown by instances of
* this class
*/
public Object clone() throws CloneNotSupportedException {
DefaultTreeSelectionModel clone = (DefaultTreeSelectionModel)
super.clone();
clone.changeSupport = null;
if(selection != null) {
int selLength = selection.length;
clone.selection = new TreePath[selLength];
System.arraycopy(selection, 0, clone.selection, 0, selLength);
}
clone.listenerList = new EventListenerList();
clone.listSelectionModel = (DefaultListSelectionModel)
listSelectionModel.clone();
clone.uniquePaths = new Hashtable();
clone.lastPaths = new Hashtable();
clone.tempPaths = new TreePath[1];
return clone;
}
// Serialization support.
private void writeObject(ObjectOutputStream s) throws IOException {
Object[] tValues;
s.defaultWriteObject();
// Save the rowMapper, if it implements Serializable
if(rowMapper != null && rowMapper instanceof Serializable) {
tValues = new Object[2];
tValues[0] = "rowMapper";
tValues[1] = rowMapper;
}
else
tValues = new Object[0];
s.writeObject(tValues);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
Object[] tValues;
s.defaultReadObject();
tValues = (Object[])s.readObject();
if(tValues.length > 0 && tValues[0].equals("rowMapper"))
rowMapper = (RowMapper)tValues[1];
}
}
/** {@collect.stats}
* Holds a path and whether or not it is new.
*/
class PathPlaceHolder {
protected boolean isNew;
protected TreePath path;
PathPlaceHolder(TreePath path, boolean isNew) {
this.path = path;
this.isNew = isNew;
}
}
|
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.tree;
import java.util.*;
import java.io.*;
import javax.swing.event.*;
/** {@collect.stats}
* A simple tree data model that uses TreeNodes.
* For further information and examples that use DefaultTreeModel,
* see <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Trees</a>
* 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 DefaultTreeModel implements Serializable, TreeModel {
/** {@collect.stats} Root of the tree. */
protected TreeNode root;
/** {@collect.stats} Listeners. */
protected EventListenerList listenerList = new EventListenerList();
/** {@collect.stats}
* Determines how the <code>isLeaf</code> method figures
* out if a node is a leaf node. If true, a node is a leaf
* node if it does not allow children. (If it allows
* children, it is not a leaf node, even if no children
* are present.) That lets you distinguish between <i>folder</i>
* nodes and <i>file</i> nodes in a file system, for example.
* <p>
* If this value is false, then any node which has no
* children is a leaf node, and any node may acquire
* children.
*
* @see TreeNode#getAllowsChildren
* @see TreeModel#isLeaf
* @see #setAsksAllowsChildren
*/
protected boolean asksAllowsChildren;
/** {@collect.stats}
* Creates a tree in which any node can have children.
*
* @param root a TreeNode object that is the root of the tree
* @see #DefaultTreeModel(TreeNode, boolean)
*/
public DefaultTreeModel(TreeNode root) {
this(root, false);
}
/** {@collect.stats}
* Creates a tree specifying whether any node can have children,
* or whether only certain nodes can have children.
*
* @param root a TreeNode object that is the root of the tree
* @param asksAllowsChildren a boolean, false if any node can
* have children, true if each node is asked to see if
* it can have children
* @see #asksAllowsChildren
*/
public DefaultTreeModel(TreeNode root, boolean asksAllowsChildren) {
super();
this.root = root;
this.asksAllowsChildren = asksAllowsChildren;
}
/** {@collect.stats}
* Sets whether or not to test leafness by asking getAllowsChildren()
* or isLeaf() to the TreeNodes. If newvalue is true, getAllowsChildren()
* is messaged, otherwise isLeaf() is messaged.
*/
public void setAsksAllowsChildren(boolean newValue) {
asksAllowsChildren = newValue;
}
/** {@collect.stats}
* Tells how leaf nodes are determined.
*
* @return true if only nodes which do not allow children are
* leaf nodes, false if nodes which have no children
* (even if allowed) are leaf nodes
* @see #asksAllowsChildren
*/
public boolean asksAllowsChildren() {
return asksAllowsChildren;
}
/** {@collect.stats}
* Sets the root to <code>root</code>. A null <code>root</code> implies
* the tree is to display nothing, and is legal.
*/
public void setRoot(TreeNode root) {
Object oldRoot = this.root;
this.root = root;
if (root == null && oldRoot != null) {
fireTreeStructureChanged(this, null);
}
else {
nodeStructureChanged(root);
}
}
/** {@collect.stats}
* Returns the root of the tree. Returns null only if the tree has
* no nodes.
*
* @return the root of the tree
*/
public Object getRoot() {
return root;
}
/** {@collect.stats}
* Returns the index of child in parent.
* If either the parent or child is <code>null</code>, returns -1.
* @param parent a note in the tree, obtained from this data source
* @param child the node we are interested in
* @return the index of the child in the parent, or -1
* if either the parent or the child is <code>null</code>
*/
public int getIndexOfChild(Object parent, Object child) {
if(parent == null || child == null)
return -1;
return ((TreeNode)parent).getIndex((TreeNode)child);
}
/** {@collect.stats}
* Returns the child of <I>parent</I> at index <I>index</I> in the parent's
* child array. <I>parent</I> must be a node previously obtained from
* this data source. This should not return null if <i>index</i>
* is a valid index for <i>parent</i> (that is <i>index</i> >= 0 &&
* <i>index</i> < getChildCount(<i>parent</i>)).
*
* @param parent a node in the tree, obtained from this data source
* @return the child of <I>parent</I> at index <I>index</I>
*/
public Object getChild(Object parent, int index) {
return ((TreeNode)parent).getChildAt(index);
}
/** {@collect.stats}
* Returns the number of children of <I>parent</I>. Returns 0 if the node
* is a leaf or if it has no children. <I>parent</I> must be a node
* previously obtained from this data source.
*
* @param parent a node in the tree, obtained from this data source
* @return the number of children of the node <I>parent</I>
*/
public int getChildCount(Object parent) {
return ((TreeNode)parent).getChildCount();
}
/** {@collect.stats}
* Returns whether the specified node is a leaf node.
* The way the test is performed depends on the
* <code>askAllowsChildren</code> setting.
*
* @param node the node to check
* @return true if the node is a leaf node
*
* @see #asksAllowsChildren
* @see TreeModel#isLeaf
*/
public boolean isLeaf(Object node) {
if(asksAllowsChildren)
return !((TreeNode)node).getAllowsChildren();
return ((TreeNode)node).isLeaf();
}
/** {@collect.stats}
* Invoke this method if you've modified the {@code TreeNode}s upon which
* this model depends. The model will notify all of its listeners that the
* model has changed.
*/
public void reload() {
reload(root);
}
/** {@collect.stats}
* This sets the user object of the TreeNode identified by path
* and posts a node changed. If you use custom user objects in
* the TreeModel you're going to need to subclass this and
* set the user object of the changed node to something meaningful.
*/
public void valueForPathChanged(TreePath path, Object newValue) {
MutableTreeNode aNode = (MutableTreeNode)path.getLastPathComponent();
aNode.setUserObject(newValue);
nodeChanged(aNode);
}
/** {@collect.stats}
* Invoked this to insert newChild at location index in parents children.
* This will then message nodesWereInserted to create the appropriate
* event. This is the preferred way to add children as it will create
* the appropriate event.
*/
public void insertNodeInto(MutableTreeNode newChild,
MutableTreeNode parent, int index){
parent.insert(newChild, index);
int[] newIndexs = new int[1];
newIndexs[0] = index;
nodesWereInserted(parent, newIndexs);
}
/** {@collect.stats}
* Message this to remove node from its parent. This will message
* nodesWereRemoved to create the appropriate event. This is the
* preferred way to remove a node as it handles the event creation
* for you.
*/
public void removeNodeFromParent(MutableTreeNode node) {
MutableTreeNode parent = (MutableTreeNode)node.getParent();
if(parent == null)
throw new IllegalArgumentException("node does not have a parent.");
int[] childIndex = new int[1];
Object[] removedArray = new Object[1];
childIndex[0] = parent.getIndex(node);
parent.remove(childIndex[0]);
removedArray[0] = node;
nodesWereRemoved(parent, childIndex, removedArray);
}
/** {@collect.stats}
* Invoke this method after you've changed how node is to be
* represented in the tree.
*/
public void nodeChanged(TreeNode node) {
if(listenerList != null && node != null) {
TreeNode parent = node.getParent();
if(parent != null) {
int anIndex = parent.getIndex(node);
if(anIndex != -1) {
int[] cIndexs = new int[1];
cIndexs[0] = anIndex;
nodesChanged(parent, cIndexs);
}
}
else if (node == getRoot()) {
nodesChanged(node, null);
}
}
}
/** {@collect.stats}
* Invoke this method if you've modified the {@code TreeNode}s upon which
* this model depends. The model will notify all of its listeners that the
* model has changed below the given node.
*
* @param node the node below which the model has changed
*/
public void reload(TreeNode node) {
if(node != null) {
fireTreeStructureChanged(this, getPathToRoot(node), null, null);
}
}
/** {@collect.stats}
* Invoke this method after you've inserted some TreeNodes into
* node. childIndices should be the index of the new elements and
* must be sorted in ascending order.
*/
public void nodesWereInserted(TreeNode node, int[] childIndices) {
if(listenerList != null && node != null && childIndices != null
&& childIndices.length > 0) {
int cCount = childIndices.length;
Object[] newChildren = new Object[cCount];
for(int counter = 0; counter < cCount; counter++)
newChildren[counter] = node.getChildAt(childIndices[counter]);
fireTreeNodesInserted(this, getPathToRoot(node), childIndices,
newChildren);
}
}
/** {@collect.stats}
* Invoke this method after you've removed some TreeNodes from
* node. childIndices should be the index of the removed elements and
* must be sorted in ascending order. And removedChildren should be
* the array of the children objects that were removed.
*/
public void nodesWereRemoved(TreeNode node, int[] childIndices,
Object[] removedChildren) {
if(node != null && childIndices != null) {
fireTreeNodesRemoved(this, getPathToRoot(node), childIndices,
removedChildren);
}
}
/** {@collect.stats}
* Invoke this method after you've changed how the children identified by
* childIndicies are to be represented in the tree.
*/
public void nodesChanged(TreeNode node, int[] childIndices) {
if(node != null) {
if (childIndices != null) {
int cCount = childIndices.length;
if(cCount > 0) {
Object[] cChildren = new Object[cCount];
for(int counter = 0; counter < cCount; counter++)
cChildren[counter] = node.getChildAt
(childIndices[counter]);
fireTreeNodesChanged(this, getPathToRoot(node),
childIndices, cChildren);
}
}
else if (node == getRoot()) {
fireTreeNodesChanged(this, getPathToRoot(node), null, null);
}
}
}
/** {@collect.stats}
* Invoke this method if you've totally changed the children of
* node and its childrens children... This will post a
* treeStructureChanged event.
*/
public void nodeStructureChanged(TreeNode node) {
if(node != null) {
fireTreeStructureChanged(this, getPathToRoot(node), null, null);
}
}
/** {@collect.stats}
* Builds the parents of node up to and including the root node,
* where the original node is the last element in the returned array.
* The length of the returned array gives the node's depth in the
* tree.
*
* @param aNode the TreeNode to get the path for
*/
public TreeNode[] getPathToRoot(TreeNode aNode) {
return getPathToRoot(aNode, 0);
}
/** {@collect.stats}
* Builds the parents of node up to and including the root node,
* where the original node is the last element in the returned array.
* The length of the returned array gives the node's depth in the
* tree.
*
* @param aNode the TreeNode to get the path for
* @param depth an int giving the number of steps already taken towards
* the root (on recursive calls), used to size the returned array
* @return an array of TreeNodes giving the path from the root to the
* specified node
*/
protected TreeNode[] getPathToRoot(TreeNode aNode, int depth) {
TreeNode[] retNodes;
// This method recurses, traversing towards the root in order
// size the array. On the way back, it fills in the nodes,
// starting from the root and working back to the original node.
/* Check for null, in case someone passed in a null node, or
they passed in an element that isn't rooted at root. */
if(aNode == null) {
if(depth == 0)
return null;
else
retNodes = new TreeNode[depth];
}
else {
depth++;
if(aNode == root)
retNodes = new TreeNode[depth];
else
retNodes = getPathToRoot(aNode.getParent(), depth);
retNodes[retNodes.length - depth] = aNode;
}
return retNodes;
}
//
// Events
//
/** {@collect.stats}
* Adds a listener for the TreeModelEvent posted after the tree changes.
*
* @see #removeTreeModelListener
* @param l the listener to add
*/
public void addTreeModelListener(TreeModelListener l) {
listenerList.add(TreeModelListener.class, l);
}
/** {@collect.stats}
* Removes a listener previously added with <B>addTreeModelListener()</B>.
*
* @see #addTreeModelListener
* @param l the listener to remove
*/
public void removeTreeModelListener(TreeModelListener l) {
listenerList.remove(TreeModelListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the tree model listeners
* registered on this model.
*
* @return all of this model's <code>TreeModelListener</code>s
* or an empty
* array if no tree model listeners are currently registered
*
* @see #addTreeModelListener
* @see #removeTreeModelListener
*
* @since 1.4
*/
public TreeModelListener[] getTreeModelListeners() {
return (TreeModelListener[])listenerList.getListeners(
TreeModelListener.class);
}
/** {@collect.stats}
* Notifies 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.
*
* @param source the node being changed
* @param path the path to the root node
* @param childIndices the indices of the changed elements
* @param children the changed elements
* @see EventListenerList
*/
protected void fireTreeNodesChanged(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent 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]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeNodesChanged(e);
}
}
}
/** {@collect.stats}
* Notifies 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.
*
* @param source the node where new elements are being inserted
* @param path the path to the root node
* @param childIndices the indices of the new elements
* @param children the new elements
* @see EventListenerList
*/
protected void fireTreeNodesInserted(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent 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]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeNodesInserted(e);
}
}
}
/** {@collect.stats}
* Notifies 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.
*
* @param source the node where elements are being removed
* @param path the path to the root node
* @param childIndices the indices of the removed elements
* @param children the removed elements
* @see EventListenerList
*/
protected void fireTreeNodesRemoved(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent 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]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeNodesRemoved(e);
}
}
}
/** {@collect.stats}
* Notifies 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.
*
* @param source the node where the tree model has changed
* @param path the path to the root node
* @param childIndices the indices of the affected elements
* @param children the affected elements
* @see EventListenerList
*/
protected void fireTreeStructureChanged(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent 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]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeStructureChanged(e);
}
}
}
/*
* Notifies 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.
*
* @param source the node where the tree model has changed
* @param path the path to the root node
* @see EventListenerList
*/
private void fireTreeStructureChanged(Object source, TreePath path) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent 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]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path);
((TreeModelListener)listeners[i+1]).treeStructureChanged(e);
}
}
}
/** {@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>DefaultTreeModel</code> <code>m</code>
* for its tree model listeners with the following code:
*
* <pre>TreeModelListener[] tmls = (TreeModelListener[])(m.getListeners(TreeModelListener.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 component,
* 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 #getTreeModelListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
// Serialization support.
private void writeObject(ObjectOutputStream s) throws IOException {
Vector values = new Vector();
s.defaultWriteObject();
// Save the root, if its Serializable.
if(root != null && root instanceof Serializable) {
values.addElement("root");
values.addElement(root);
}
s.writeObject(values);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
Vector values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("root")) {
root = (TreeNode)values.elementAt(++indexCounter);
indexCounter++;
}
}
} // End of class DefaultTreeModel
|
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.tree;
/** {@collect.stats}
* Defines the requirements for a tree node object that can change --
* by adding or removing child nodes, or by changing the contents
* of a user object stored in the node.
*
* @see DefaultMutableTreeNode
* @see javax.swing.JTree
*
* @author Rob Davis
* @author Scott Violet
*/
public interface MutableTreeNode extends TreeNode
{
/** {@collect.stats}
* Adds <code>child</code> to the receiver at <code>index</code>.
* <code>child</code> will be messaged with <code>setParent</code>.
*/
void insert(MutableTreeNode child, int index);
/** {@collect.stats}
* Removes the child at <code>index</code> from the receiver.
*/
void remove(int index);
/** {@collect.stats}
* Removes <code>node</code> from the receiver. <code>setParent</code>
* will be messaged on <code>node</code>.
*/
void remove(MutableTreeNode node);
/** {@collect.stats}
* Resets the user object of the receiver to <code>object</code>.
*/
void setUserObject(Object object);
/** {@collect.stats}
* Removes the receiver from its parent.
*/
void removeFromParent();
/** {@collect.stats}
* Sets the parent of the receiver to <code>newParent</code>.
*/
void setParent(MutableTreeNode newParent);
}
|
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.tree;
import javax.swing.event.TreeExpansionEvent;
/** {@collect.stats}
* Exception used to stop and expand/collapse from happening.
* See <a
href="http://java.sun.com/docs/books/tutorial/uiswing/events/treewillexpandlistener.html">How to Write a Tree-Will-Expand Listener</a>
* in <em>The Java Tutorial</em>
* for further information and examples.
*
* @author Scott Violet
*/
public class ExpandVetoException extends Exception {
/** {@collect.stats} The event that the exception was created for. */
protected TreeExpansionEvent event;
/** {@collect.stats}
* Constructs an ExpandVetoException object with no message.
*
* @param event a TreeExpansionEvent object
*/
public ExpandVetoException(TreeExpansionEvent event) {
this(event, null);
}
/** {@collect.stats}
* Constructs an ExpandVetoException object with the specified message.
*
* @param event a TreeExpansionEvent object
* @param message a String containing the message
*/
public ExpandVetoException(TreeExpansionEvent event, String message) {
super(message);
this.event = event;
}
}
|
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.tree;
import javax.swing.event.TreeModelEvent;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Stack;
import java.util.Vector;
/** {@collect.stats}
* NOTE: This will become more open in a future release.
* <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 VariableHeightLayoutCache extends AbstractLayoutCache {
/** {@collect.stats}
* The array of nodes that are currently visible, in the order they
* are displayed.
*/
private Vector visibleNodes;
/** {@collect.stats}
* This is set to true if one of the entries has an invalid size.
*/
private boolean updateNodeSizes;
/** {@collect.stats}
* The root node of the internal cache of nodes that have been shown.
* If the treeModel is vending a network rather than a true tree,
* there may be one cached node for each path to a modeled node.
*/
private TreeStateNode root;
/** {@collect.stats}
* Used in getting sizes for nodes to avoid creating a new Rectangle
* every time a size is needed.
*/
private Rectangle boundsBuffer;
/** {@collect.stats}
* Maps from <code>TreePath</code> to a <code>TreeStateNode</code>.
*/
private Hashtable treePathMapping;
/** {@collect.stats}
* A stack of stacks.
*/
private Stack tempStacks;
public VariableHeightLayoutCache() {
super();
tempStacks = new Stack();
visibleNodes = new Vector();
boundsBuffer = new Rectangle();
treePathMapping = new Hashtable();
}
/** {@collect.stats}
* Sets the <code>TreeModel</code> that will provide the data.
*
* @param newModel the <code>TreeModel</code> that is to provide the data
* @beaninfo
* bound: true
* description: The TreeModel that will provide the data.
*/
public void setModel(TreeModel newModel) {
super.setModel(newModel);
rebuild(false);
}
/** {@collect.stats}
* Determines whether or not the root node from
* the <code>TreeModel</code> is visible.
*
* @param rootVisible true if the root node of the tree is to be displayed
* @see #rootVisible
* @beaninfo
* bound: true
* description: Whether or not the root node
* from the TreeModel is visible.
*/
public void setRootVisible(boolean rootVisible) {
if(isRootVisible() != rootVisible && root != null) {
if(rootVisible) {
root.updatePreferredSize(0);
visibleNodes.insertElementAt(root, 0);
}
else if(visibleNodes.size() > 0) {
visibleNodes.removeElementAt(0);
if(treeSelectionModel != null)
treeSelectionModel.removeSelectionPath
(root.getTreePath());
}
if(treeSelectionModel != null)
treeSelectionModel.resetRowSelection();
if(getRowCount() > 0)
getNode(0).setYOrigin(0);
updateYLocationsFrom(0);
visibleNodesChanged();
}
super.setRootVisible(rootVisible);
}
/** {@collect.stats}
* Sets the height of each cell. If the specified value
* is less than or equal to zero the current cell renderer is
* queried for each row's height.
*
* @param rowHeight the height of each cell, in pixels
* @beaninfo
* bound: true
* description: The height of each cell.
*/
public void setRowHeight(int rowHeight) {
if(rowHeight != getRowHeight()) {
super.setRowHeight(rowHeight);
invalidateSizes();
this.visibleNodesChanged();
}
}
/** {@collect.stats}
* Sets the renderer that is responsible for drawing nodes in the tree.
* @param nd the renderer
*/
public void setNodeDimensions(NodeDimensions nd) {
super.setNodeDimensions(nd);
invalidateSizes();
visibleNodesChanged();
}
/** {@collect.stats}
* Marks the path <code>path</code> expanded state to
* <code>isExpanded</code>.
* @param path the <code>TreePath</code> of interest
* @param isExpanded true if the path should be expanded, otherwise false
*/
public void setExpandedState(TreePath path, boolean isExpanded) {
if(path != null) {
if(isExpanded)
ensurePathIsExpanded(path, true);
else {
TreeStateNode node = getNodeForPath(path, false, true);
if(node != null) {
node.makeVisible();
node.collapse();
}
}
}
}
/** {@collect.stats}
* Returns true if the path is expanded, and visible.
* @return true if the path is expanded and visible, otherwise false
*/
public boolean getExpandedState(TreePath path) {
TreeStateNode node = getNodeForPath(path, true, false);
return (node != null) ? (node.isVisible() && node.isExpanded()) :
false;
}
/** {@collect.stats}
* Returns the <code>Rectangle</code> enclosing the label portion
* into which the item identified by <code>path</code> will be drawn.
*
* @param path the path to be drawn
* @param placeIn the bounds of the enclosing rectangle
* @return the bounds of the enclosing rectangle or <code>null</code>
* if the node could not be ascertained
*/
public Rectangle getBounds(TreePath path, Rectangle placeIn) {
TreeStateNode node = getNodeForPath(path, true, false);
if(node != null) {
if(updateNodeSizes)
updateNodeSizes(false);
return node.getNodeBounds(placeIn);
}
return null;
}
/** {@collect.stats}
* Returns the path for <code>row</code>. If <code>row</code>
* is not visible, <code>null</code> is returned.
*
* @param row the location of interest
* @return the path for <code>row</code>, or <code>null</code>
* if <code>row</code> is not visible
*/
public TreePath getPathForRow(int row) {
if(row >= 0 && row < getRowCount()) {
return getNode(row).getTreePath();
}
return null;
}
/** {@collect.stats}
* Returns the row where the last item identified in path is visible.
* Will return -1 if any of the elements in path are not
* currently visible.
*
* @param path the <code>TreePath</code> of interest
* @return the row where the last item in path is visible
*/
public int getRowForPath(TreePath path) {
if(path == null)
return -1;
TreeStateNode visNode = getNodeForPath(path, true, false);
if(visNode != null)
return visNode.getRow();
return -1;
}
/** {@collect.stats}
* Returns the number of visible rows.
* @return the number of visible rows
*/
public int getRowCount() {
return visibleNodes.size();
}
/** {@collect.stats}
* Instructs the <code>LayoutCache</code> that the bounds for
* <code>path</code> are invalid, and need to be updated.
*
* @param path the <code>TreePath</code> which is now invalid
*/
public void invalidatePathBounds(TreePath path) {
TreeStateNode node = getNodeForPath(path, true, false);
if(node != null) {
node.markSizeInvalid();
if(node.isVisible())
updateYLocationsFrom(node.getRow());
}
}
/** {@collect.stats}
* Returns the preferred height.
* @return the preferred height
*/
public int getPreferredHeight() {
// Get the height
int rowCount = getRowCount();
if(rowCount > 0) {
TreeStateNode node = getNode(rowCount - 1);
return node.getYOrigin() + node.getPreferredHeight();
}
return 0;
}
/** {@collect.stats}
* Returns the preferred width and height for the region in
* <code>visibleRegion</code>.
*
* @param bounds the region being queried
*/
public int getPreferredWidth(Rectangle bounds) {
if(updateNodeSizes)
updateNodeSizes(false);
return getMaxNodeWidth();
}
/** {@collect.stats}
* Returns the path to the node that is closest to x,y. If
* there is nothing currently visible this will return <code>null</code>,
* otherwise it will always return a valid path.
* If you need to test if the
* returned object is exactly at x, y you should get the bounds for
* the returned path and test x, y against that.
*
* @param x the x-coordinate
* @param y the y-coordinate
* @return the path to the node that is closest to x, y
*/
public TreePath getPathClosestTo(int x, int y) {
if(getRowCount() == 0)
return null;
if(updateNodeSizes)
updateNodeSizes(false);
int row = getRowContainingYLocation(y);
return getNode(row).getTreePath();
}
/** {@collect.stats}
* Returns an <code>Enumerator</code> that increments over the visible paths
* starting at the passed in location. The ordering of the enumeration
* is based on how the paths are displayed.
*
* @param path the location in the <code>TreePath</code> to start
* @return an <code>Enumerator</code> that increments over the visible
* paths
*/
public Enumeration<TreePath> getVisiblePathsFrom(TreePath path) {
TreeStateNode node = getNodeForPath(path, true, false);
if(node != null) {
return new VisibleTreeStateNodeEnumeration(node);
}
return null;
}
/** {@collect.stats}
* Returns the number of visible children for <code>path</code>.
* @return the number of visible children for <code>path</code>
*/
public int getVisibleChildCount(TreePath path) {
TreeStateNode node = getNodeForPath(path, true, false);
return (node != null) ? node.getVisibleChildCount() : 0;
}
/** {@collect.stats}
* Informs the <code>TreeState</code> that it needs to recalculate
* all the sizes it is referencing.
*/
public void invalidateSizes() {
if(root != null)
root.deepMarkSizeInvalid();
if(!isFixedRowHeight() && visibleNodes.size() > 0) {
updateNodeSizes(true);
}
}
/** {@collect.stats}
* Returns true if the value identified by <code>path</code> is
* currently expanded.
* @return true if the value identified by <code>path</code> is
* currently expanded
*/
public boolean isExpanded(TreePath path) {
if(path != null) {
TreeStateNode lastNode = getNodeForPath(path, true, false);
return (lastNode != null && lastNode.isExpanded());
}
return false;
}
//
// TreeModelListener methods
//
/** {@collect.stats}
* 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><code>e.path</code> returns the path the parent of the
* changed node(s).
*
* <p><code>e.childIndices</code> returns the index(es) of the
* changed node(s).
*
* @param e the <code>TreeModelEvent</code> of interest
*/
public void treeNodesChanged(TreeModelEvent e) {
if(e != null) {
int changedIndexs[];
TreeStateNode changedNode;
changedIndexs = e.getChildIndices();
changedNode = getNodeForPath(e.getTreePath(), false, false);
if(changedNode != null) {
Object changedValue = changedNode.getValue();
/* Update the size of the changed node, as well as all the
child indexs that are passed in. */
changedNode.updatePreferredSize();
if(changedNode.hasBeenExpanded() && changedIndexs != null) {
int counter;
TreeStateNode changedChildNode;
for(counter = 0; counter < changedIndexs.length;
counter++) {
changedChildNode = (TreeStateNode)changedNode
.getChildAt(changedIndexs[counter]);
/* Reset the user object. */
changedChildNode.setUserObject
(treeModel.getChild(changedValue,
changedIndexs[counter]));
changedChildNode.updatePreferredSize();
}
}
else if (changedNode == root) {
// Null indicies for root indicates it changed.
changedNode.updatePreferredSize();
}
if(!isFixedRowHeight()) {
int aRow = changedNode.getRow();
if(aRow != -1)
this.updateYLocationsFrom(aRow);
}
this.visibleNodesChanged();
}
}
}
/** {@collect.stats}
* Invoked after nodes have been inserted into the tree.
*
* <p><code>e.path</code> returns the parent of the new nodes.
* <p><code>e.childIndices</code> returns the indices of the new nodes in
* ascending order.
*
* @param e the <code>TreeModelEvent</code> of interest
*/
public void treeNodesInserted(TreeModelEvent e) {
if(e != null) {
int changedIndexs[];
TreeStateNode changedParentNode;
changedIndexs = e.getChildIndices();
changedParentNode = getNodeForPath(e.getTreePath(), false, false);
/* Only need to update the children if the node has been
expanded once. */
// PENDING(scott): make sure childIndexs is sorted!
if(changedParentNode != null && changedIndexs != null &&
changedIndexs.length > 0) {
if(changedParentNode.hasBeenExpanded()) {
boolean makeVisible;
int counter;
Object changedParent;
TreeStateNode newNode;
int oldChildCount = changedParentNode.
getChildCount();
changedParent = changedParentNode.getValue();
makeVisible = ((changedParentNode == root &&
!rootVisible) ||
(changedParentNode.getRow() != -1 &&
changedParentNode.isExpanded()));
for(counter = 0;counter < changedIndexs.length;counter++)
{
newNode = this.createNodeAt(changedParentNode,
changedIndexs[counter]);
}
if(oldChildCount == 0) {
// Update the size of the parent.
changedParentNode.updatePreferredSize();
}
if(treeSelectionModel != null)
treeSelectionModel.resetRowSelection();
/* Update the y origins from the index of the parent
to the end of the visible rows. */
if(!isFixedRowHeight() && (makeVisible ||
(oldChildCount == 0 &&
changedParentNode.isVisible()))) {
if(changedParentNode == root)
this.updateYLocationsFrom(0);
else
this.updateYLocationsFrom(changedParentNode.
getRow());
this.visibleNodesChanged();
}
else if(makeVisible)
this.visibleNodesChanged();
}
else if(treeModel.getChildCount(changedParentNode.getValue())
- changedIndexs.length == 0) {
changedParentNode.updatePreferredSize();
if(!isFixedRowHeight() && changedParentNode.isVisible())
updateYLocationsFrom(changedParentNode.getRow());
}
}
}
}
/** {@collect.stats}
* 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><code>e.path</code> returns the former parent of the deleted nodes.
*
* <p><code>e.childIndices</code> returns the indices the nodes had
* before they were deleted in ascending order.
*
* @param e the <code>TreeModelEvent</code> of interest
*/
public void treeNodesRemoved(TreeModelEvent e) {
if(e != null) {
int changedIndexs[];
TreeStateNode changedParentNode;
changedIndexs = e.getChildIndices();
changedParentNode = getNodeForPath(e.getTreePath(), false, false);
// PENDING(scott): make sure that changedIndexs are sorted in
// ascending order.
if(changedParentNode != null && changedIndexs != null &&
changedIndexs.length > 0) {
if(changedParentNode.hasBeenExpanded()) {
boolean makeInvisible;
int counter;
int removedRow;
TreeStateNode removedNode;
makeInvisible = ((changedParentNode == root &&
!rootVisible) ||
(changedParentNode.getRow() != -1 &&
changedParentNode.isExpanded()));
for(counter = changedIndexs.length - 1;counter >= 0;
counter--) {
removedNode = (TreeStateNode)changedParentNode.
getChildAt(changedIndexs[counter]);
if(removedNode.isExpanded()) {
removedNode.collapse(false);
}
/* Let the selection model now. */
if(makeInvisible) {
removedRow = removedNode.getRow();
if(removedRow != -1) {
visibleNodes.removeElementAt(removedRow);
}
}
changedParentNode.remove(changedIndexs[counter]);
}
if(changedParentNode.getChildCount() == 0) {
// Update the size of the parent.
changedParentNode.updatePreferredSize();
if (changedParentNode.isExpanded() &&
changedParentNode.isLeaf()) {
// Node has become a leaf, collapse it.
changedParentNode.collapse(false);
}
}
if(treeSelectionModel != null)
treeSelectionModel.resetRowSelection();
/* Update the y origins from the index of the parent
to the end of the visible rows. */
if(!isFixedRowHeight() && (makeInvisible ||
(changedParentNode.getChildCount() == 0 &&
changedParentNode.isVisible()))) {
if(changedParentNode == root) {
/* It is possible for first row to have been
removed if the root isn't visible, in which
case ylocations will be off! */
if(getRowCount() > 0)
getNode(0).setYOrigin(0);
updateYLocationsFrom(0);
}
else
updateYLocationsFrom(changedParentNode.getRow());
this.visibleNodesChanged();
}
else if(makeInvisible)
this.visibleNodesChanged();
}
else if(treeModel.getChildCount(changedParentNode.getValue())
== 0) {
changedParentNode.updatePreferredSize();
if(!isFixedRowHeight() && changedParentNode.isVisible())
this.updateYLocationsFrom(changedParentNode.getRow());
}
}
}
}
/** {@collect.stats}
* Invoked after the tree has drastically changed structure from a
* given node down. If the path returned by <code>e.getPath</code>
* 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><code>e.path</code> holds the path to the node.
* <p><code>e.childIndices</code> returns <code>null</code>.
*
* @param e the <code>TreeModelEvent</code> of interest
*/
public void treeStructureChanged(TreeModelEvent e) {
if(e != null)
{
TreePath changedPath = e.getTreePath();
TreeStateNode changedNode;
changedNode = getNodeForPath(changedPath, false, false);
// Check if root has changed, either to a null root, or
// to an entirely new root.
if(changedNode == root ||
(changedNode == null &&
((changedPath == null && treeModel != null &&
treeModel.getRoot() == null) ||
(changedPath != null && changedPath.getPathCount() == 1)))) {
rebuild(true);
}
else if(changedNode != null) {
int nodeIndex, oldRow;
TreeStateNode newNode, parent;
boolean wasExpanded, wasVisible;
int newIndex;
wasExpanded = changedNode.isExpanded();
wasVisible = (changedNode.getRow() != -1);
/* Remove the current node and recreate a new one. */
parent = (TreeStateNode)changedNode.getParent();
nodeIndex = parent.getIndex(changedNode);
if(wasVisible && wasExpanded) {
changedNode.collapse(false);
}
if(wasVisible)
visibleNodes.removeElement(changedNode);
changedNode.removeFromParent();
createNodeAt(parent, nodeIndex);
newNode = (TreeStateNode)parent.getChildAt(nodeIndex);
if(wasVisible && wasExpanded)
newNode.expand(false);
newIndex = newNode.getRow();
if(!isFixedRowHeight() && wasVisible) {
if(newIndex == 0)
updateYLocationsFrom(newIndex);
else
updateYLocationsFrom(newIndex - 1);
this.visibleNodesChanged();
}
else if(wasVisible)
this.visibleNodesChanged();
}
}
}
//
// Local methods
//
private void visibleNodesChanged() {
}
/** {@collect.stats}
* Adds a mapping for node.
*/
private void addMapping(TreeStateNode node) {
treePathMapping.put(node.getTreePath(), node);
}
/** {@collect.stats}
* Removes the mapping for a previously added node.
*/
private void removeMapping(TreeStateNode node) {
treePathMapping.remove(node.getTreePath());
}
/** {@collect.stats}
* Returns the node previously added for <code>path</code>. This may
* return null, if you to create a node use getNodeForPath.
*/
private TreeStateNode getMapping(TreePath path) {
return (TreeStateNode)treePathMapping.get(path);
}
/** {@collect.stats}
* Retursn the bounds for row, <code>row</code> by reference in
* <code>placeIn</code>. If <code>placeIn</code> is null a new
* Rectangle will be created and returned.
*/
private Rectangle getBounds(int row, Rectangle placeIn) {
if(updateNodeSizes)
updateNodeSizes(false);
if(row >= 0 && row < getRowCount()) {
return getNode(row).getNodeBounds(placeIn);
}
return null;
}
/** {@collect.stats}
* Completely rebuild the tree, all expanded state, and node caches are
* removed. All nodes are collapsed, except the root.
*/
private void rebuild(boolean clearSelection) {
Object rootObject;
treePathMapping.clear();
if(treeModel != null && (rootObject = treeModel.getRoot()) != null) {
root = createNodeForValue(rootObject);
root.path = new TreePath(rootObject);
addMapping(root);
root.updatePreferredSize(0);
visibleNodes.removeAllElements();
if (isRootVisible())
visibleNodes.addElement(root);
if(!root.isExpanded())
root.expand();
else {
Enumeration cursor = root.children();
while(cursor.hasMoreElements()) {
visibleNodes.addElement(cursor.nextElement());
}
if(!isFixedRowHeight())
updateYLocationsFrom(0);
}
}
else {
visibleNodes.removeAllElements();
root = null;
}
if(clearSelection && treeSelectionModel != null) {
treeSelectionModel.clearSelection();
}
this.visibleNodesChanged();
}
/** {@collect.stats}
* Creates a new node to represent the node at <I>childIndex</I> in
* <I>parent</I>s children. This should be called if the node doesn't
* already exist and <I>parent</I> has been expanded at least once.
* The newly created node will be made visible if <I>parent</I> is
* currently expanded. This does not update the position of any
* cells, nor update the selection if it needs to be. If succesful
* in creating the new TreeStateNode, it is returned, otherwise
* null is returned.
*/
private TreeStateNode createNodeAt(TreeStateNode parent,
int childIndex) {
boolean isParentRoot;
Object newValue;
TreeStateNode newChildNode;
newValue = treeModel.getChild(parent.getValue(), childIndex);
newChildNode = createNodeForValue(newValue);
parent.insert(newChildNode, childIndex);
newChildNode.updatePreferredSize(-1);
isParentRoot = (parent == root);
if(newChildNode != null && parent.isExpanded() &&
(parent.getRow() != -1 || isParentRoot)) {
int newRow;
/* Find the new row to insert this newly visible node at. */
if(childIndex == 0) {
if(isParentRoot && !isRootVisible())
newRow = 0;
else
newRow = parent.getRow() + 1;
}
else if(childIndex == parent.getChildCount())
newRow = parent.getLastVisibleNode().getRow() + 1;
else {
TreeStateNode previousNode;
previousNode = (TreeStateNode)parent.
getChildAt(childIndex - 1);
newRow = previousNode.getLastVisibleNode().getRow() + 1;
}
visibleNodes.insertElementAt(newChildNode, newRow);
}
return newChildNode;
}
/** {@collect.stats}
* Returns the TreeStateNode identified by path. This mirrors
* the behavior of getNodeForPath, but tries to take advantage of
* path if it is an instance of AbstractTreePath.
*/
private TreeStateNode getNodeForPath(TreePath path,
boolean onlyIfVisible,
boolean shouldCreate) {
if(path != null) {
TreeStateNode node;
node = getMapping(path);
if(node != null) {
if(onlyIfVisible && !node.isVisible())
return null;
return node;
}
// Check all the parent paths, until a match is found.
Stack paths;
if(tempStacks.size() == 0) {
paths = new Stack();
}
else {
paths = (Stack)tempStacks.pop();
}
try {
paths.push(path);
path = path.getParentPath();
node = null;
while(path != null) {
node = getMapping(path);
if(node != null) {
// Found a match, create entries for all paths in
// paths.
while(node != null && paths.size() > 0) {
path = (TreePath)paths.pop();
node.getLoadedChildren(shouldCreate);
int childIndex = treeModel.
getIndexOfChild(node.getUserObject(),
path.getLastPathComponent());
if(childIndex == -1 ||
childIndex >= node.getChildCount() ||
(onlyIfVisible && !node.isVisible())) {
node = null;
}
else
node = (TreeStateNode)node.getChildAt
(childIndex);
}
return node;
}
paths.push(path);
path = path.getParentPath();
}
}
finally {
paths.removeAllElements();
tempStacks.push(paths);
}
// If we get here it means they share a different root!
// We could throw an exception...
}
return null;
}
/** {@collect.stats}
* Updates the y locations of all of the visible nodes after
* location.
*/
private void updateYLocationsFrom(int location) {
if(location >= 0 && location < getRowCount()) {
int counter, maxCounter, newYOrigin;
TreeStateNode aNode;
aNode = getNode(location);
newYOrigin = aNode.getYOrigin() + aNode.getPreferredHeight();
for(counter = location + 1, maxCounter = visibleNodes.size();
counter < maxCounter;counter++) {
aNode = (TreeStateNode)visibleNodes.
elementAt(counter);
aNode.setYOrigin(newYOrigin);
newYOrigin += aNode.getPreferredHeight();
}
}
}
/** {@collect.stats}
* Resets the y origin of all the visible nodes as well as messaging
* all the visible nodes to updatePreferredSize(). You should not
* normally have to call this. Expanding and contracting the nodes
* automaticly adjusts the locations.
* updateAll determines if updatePreferredSize() is call on all nodes
* or just those that don't have a valid size.
*/
private void updateNodeSizes(boolean updateAll) {
int aY, counter, maxCounter;
TreeStateNode node;
updateNodeSizes = false;
for(aY = counter = 0, maxCounter = visibleNodes.size();
counter < maxCounter; counter++) {
node = (TreeStateNode)visibleNodes.elementAt(counter);
node.setYOrigin(aY);
if(updateAll || !node.hasValidSize())
node.updatePreferredSize(counter);
aY += node.getPreferredHeight();
}
}
/** {@collect.stats}
* Returns the index of the row containing location. If there
* are no rows, -1 is returned. If location is beyond the last
* row index, the last row index is returned.
*/
private int getRowContainingYLocation(int location) {
if(isFixedRowHeight()) {
if(getRowCount() == 0)
return -1;
return Math.max(0, Math.min(getRowCount() - 1,
location / getRowHeight()));
}
int max, maxY, mid, min, minY;
TreeStateNode node;
if((max = getRowCount()) <= 0)
return -1;
mid = min = 0;
while(min < max) {
mid = (max - min) / 2 + min;
node = (TreeStateNode)visibleNodes.elementAt(mid);
minY = node.getYOrigin();
maxY = minY + node.getPreferredHeight();
if(location < minY) {
max = mid - 1;
}
else if(location >= maxY) {
min = mid + 1;
}
else
break;
}
if(min == max) {
mid = min;
if(mid >= getRowCount())
mid = getRowCount() - 1;
}
return mid;
}
/** {@collect.stats}
* Ensures that all the path components in path are expanded, accept
* for the last component which will only be expanded if expandLast
* is true.
* Returns true if succesful in finding the path.
*/
private void ensurePathIsExpanded(TreePath aPath, boolean expandLast) {
if(aPath != null) {
// Make sure the last entry isn't a leaf.
if(treeModel.isLeaf(aPath.getLastPathComponent())) {
aPath = aPath.getParentPath();
expandLast = true;
}
if(aPath != null) {
TreeStateNode lastNode = getNodeForPath(aPath, false,
true);
if(lastNode != null) {
lastNode.makeVisible();
if(expandLast)
lastNode.expand();
}
}
}
}
/** {@collect.stats}
* Returns the AbstractTreeUI.VisibleNode displayed at the given row
*/
private TreeStateNode getNode(int row) {
return (TreeStateNode)visibleNodes.elementAt(row);
}
/** {@collect.stats}
* Returns the maximum node width.
*/
private int getMaxNodeWidth() {
int maxWidth = 0;
int nodeWidth;
int counter;
TreeStateNode node;
for(counter = getRowCount() - 1;counter >= 0;counter--) {
node = this.getNode(counter);
nodeWidth = node.getPreferredWidth() + node.getXOrigin();
if(nodeWidth > maxWidth)
maxWidth = nodeWidth;
}
return maxWidth;
}
/** {@collect.stats}
* Responsible for creating a TreeStateNode that will be used
* to track display information about value.
*/
private TreeStateNode createNodeForValue(Object value) {
return new TreeStateNode(value);
}
/** {@collect.stats}
* TreeStateNode is used to keep track of each of
* the nodes that have been expanded. This will also cache the preferred
* size of the value it represents.
*/
private class TreeStateNode extends DefaultMutableTreeNode {
/** {@collect.stats} Preferred size needed to draw the user object. */
protected int preferredWidth;
protected int preferredHeight;
/** {@collect.stats} X location that the user object will be drawn at. */
protected int xOrigin;
/** {@collect.stats} Y location that the user object will be drawn at. */
protected int yOrigin;
/** {@collect.stats} Is this node currently expanded? */
protected boolean expanded;
/** {@collect.stats} Has this node been expanded at least once? */
protected boolean hasBeenExpanded;
/** {@collect.stats} Path of this node. */
protected TreePath path;
public TreeStateNode(Object value) {
super(value);
}
//
// Overriden DefaultMutableTreeNode methods
//
/** {@collect.stats}
* Messaged when this node is added somewhere, resets the path
* and adds a mapping from path to this node.
*/
public void setParent(MutableTreeNode parent) {
super.setParent(parent);
if(parent != null) {
path = ((TreeStateNode)parent).getTreePath().
pathByAddingChild(getUserObject());
addMapping(this);
}
}
/** {@collect.stats}
* Messaged when this node is removed from its parent, this messages
* <code>removedFromMapping</code> to remove all the children.
*/
public void remove(int childIndex) {
TreeStateNode node = (TreeStateNode)getChildAt(childIndex);
node.removeFromMapping();
super.remove(childIndex);
}
/** {@collect.stats}
* Messaged to set the user object. This resets the path.
*/
public void setUserObject(Object o) {
super.setUserObject(o);
if(path != null) {
TreeStateNode parent = (TreeStateNode)getParent();
if(parent != null)
resetChildrenPaths(parent.getTreePath());
else
resetChildrenPaths(null);
}
}
/** {@collect.stats}
* Returns the children of the receiver.
* If the receiver is not currently expanded, this will return an
* empty enumeration.
*/
public Enumeration children() {
if (!this.isExpanded()) {
return DefaultMutableTreeNode.EMPTY_ENUMERATION;
} else {
return super.children();
}
}
/** {@collect.stats}
* Returns true if the receiver is a leaf.
*/
public boolean isLeaf() {
return getModel().isLeaf(this.getValue());
}
//
// VariableHeightLayoutCache
//
/** {@collect.stats}
* Returns the location and size of this node.
*/
public Rectangle getNodeBounds(Rectangle placeIn) {
if(placeIn == null)
placeIn = new Rectangle(getXOrigin(), getYOrigin(),
getPreferredWidth(),
getPreferredHeight());
else {
placeIn.x = getXOrigin();
placeIn.y = getYOrigin();
placeIn.width = getPreferredWidth();
placeIn.height = getPreferredHeight();
}
return placeIn;
}
/** {@collect.stats}
* @return x location to draw node at.
*/
public int getXOrigin() {
if(!hasValidSize())
updatePreferredSize(getRow());
return xOrigin;
}
/** {@collect.stats}
* Returns the y origin the user object will be drawn at.
*/
public int getYOrigin() {
if(isFixedRowHeight()) {
int aRow = getRow();
if(aRow == -1)
return -1;
return getRowHeight() * aRow;
}
return yOrigin;
}
/** {@collect.stats}
* Returns the preferred height of the receiver.
*/
public int getPreferredHeight() {
if(isFixedRowHeight())
return getRowHeight();
else if(!hasValidSize())
updatePreferredSize(getRow());
return preferredHeight;
}
/** {@collect.stats}
* Returns the preferred width of the receiver.
*/
public int getPreferredWidth() {
if(!hasValidSize())
updatePreferredSize(getRow());
return preferredWidth;
}
/** {@collect.stats}
* Returns true if this node has a valid size.
*/
public boolean hasValidSize() {
return (preferredHeight != 0);
}
/** {@collect.stats}
* Returns the row of the receiver.
*/
public int getRow() {
return visibleNodes.indexOf(this);
}
/** {@collect.stats}
* Returns true if this node has been expanded at least once.
*/
public boolean hasBeenExpanded() {
return hasBeenExpanded;
}
/** {@collect.stats}
* Returns true if the receiver has been expanded.
*/
public boolean isExpanded() {
return expanded;
}
/** {@collect.stats}
* Returns the last visible node that is a child of this
* instance.
*/
public TreeStateNode getLastVisibleNode() {
TreeStateNode node = this;
while(node.isExpanded() && node.getChildCount() > 0)
node = (TreeStateNode)node.getLastChild();
return node;
}
/** {@collect.stats}
* Returns true if the receiver is currently visible.
*/
public boolean isVisible() {
if(this == root)
return true;
TreeStateNode parent = (TreeStateNode)getParent();
return (parent != null && parent.isExpanded() &&
parent.isVisible());
}
/** {@collect.stats}
* Returns the number of children this will have. If the children
* have not yet been loaded, this messages the model.
*/
public int getModelChildCount() {
if(hasBeenExpanded)
return super.getChildCount();
return getModel().getChildCount(getValue());
}
/** {@collect.stats}
* Returns the number of visible children, that is the number of
* children that are expanded, or leafs.
*/
public int getVisibleChildCount() {
int childCount = 0;
if(isExpanded()) {
int maxCounter = getChildCount();
childCount += maxCounter;
for(int counter = 0; counter < maxCounter; counter++)
childCount += ((TreeStateNode)getChildAt(counter)).
getVisibleChildCount();
}
return childCount;
}
/** {@collect.stats}
* Toggles the receiver between expanded and collapsed.
*/
public void toggleExpanded() {
if (isExpanded()) {
collapse();
} else {
expand();
}
}
/** {@collect.stats}
* Makes the receiver visible, but invoking
* <code>expandParentAndReceiver</code> on the superclass.
*/
public void makeVisible() {
TreeStateNode parent = (TreeStateNode)getParent();
if(parent != null)
parent.expandParentAndReceiver();
}
/** {@collect.stats}
* Expands the receiver.
*/
public void expand() {
expand(true);
}
/** {@collect.stats}
* Collapses the receiver.
*/
public void collapse() {
collapse(true);
}
/** {@collect.stats}
* Returns the value the receiver is representing. This is a cover
* for getUserObject.
*/
public Object getValue() {
return getUserObject();
}
/** {@collect.stats}
* Returns a TreePath instance for this node.
*/
public TreePath getTreePath() {
return path;
}
//
// Local methods
//
/** {@collect.stats}
* Recreates the receivers path, and all its childrens paths.
*/
protected void resetChildrenPaths(TreePath parentPath) {
removeMapping(this);
if(parentPath == null)
path = new TreePath(getUserObject());
else
path = parentPath.pathByAddingChild(getUserObject());
addMapping(this);
for(int counter = getChildCount() - 1; counter >= 0; counter--)
((TreeStateNode)getChildAt(counter)).resetChildrenPaths(path);
}
/** {@collect.stats}
* Sets y origin the user object will be drawn at to
* <I>newYOrigin</I>.
*/
protected void setYOrigin(int newYOrigin) {
yOrigin = newYOrigin;
}
/** {@collect.stats}
* Shifts the y origin by <code>offset</code>.
*/
protected void shiftYOriginBy(int offset) {
yOrigin += offset;
}
/** {@collect.stats}
* Updates the receivers preferredSize by invoking
* <code>updatePreferredSize</code> with an argument of -1.
*/
protected void updatePreferredSize() {
updatePreferredSize(getRow());
}
/** {@collect.stats}
* Updates the preferred size by asking the current renderer
* for the Dimension needed to draw the user object this
* instance represents.
*/
protected void updatePreferredSize(int index) {
Rectangle bounds = getNodeDimensions(this.getUserObject(),
index, getLevel(),
isExpanded(),
boundsBuffer);
if(bounds == null) {
xOrigin = 0;
preferredWidth = preferredHeight = 0;
updateNodeSizes = true;
}
else if(bounds.height == 0) {
xOrigin = 0;
preferredWidth = preferredHeight = 0;
updateNodeSizes = true;
}
else {
xOrigin = bounds.x;
preferredWidth = bounds.width;
if(isFixedRowHeight())
preferredHeight = getRowHeight();
else
preferredHeight = bounds.height;
}
}
/** {@collect.stats}
* Marks the receivers size as invalid. Next time the size, location
* is asked for it will be obtained.
*/
protected void markSizeInvalid() {
preferredHeight = 0;
}
/** {@collect.stats}
* Marks the receivers size, and all its descendants sizes, as invalid.
*/
protected void deepMarkSizeInvalid() {
markSizeInvalid();
for(int counter = getChildCount() - 1; counter >= 0; counter--)
((TreeStateNode)getChildAt(counter)).deepMarkSizeInvalid();
}
/** {@collect.stats}
* Returns the children of the receiver. If the children haven't
* been loaded from the model and
* <code>createIfNeeded</code> is true, the children are first
* loaded.
*/
protected Enumeration getLoadedChildren(boolean createIfNeeded) {
if(!createIfNeeded || hasBeenExpanded)
return super.children();
TreeStateNode newNode;
Object realNode = getValue();
TreeModel treeModel = getModel();
int count = treeModel.getChildCount(realNode);
hasBeenExpanded = true;
int childRow = getRow();
if(childRow == -1) {
for (int i = 0; i < count; i++) {
newNode = createNodeForValue
(treeModel.getChild(realNode, i));
this.add(newNode);
newNode.updatePreferredSize(-1);
}
}
else {
childRow++;
for (int i = 0; i < count; i++) {
newNode = createNodeForValue
(treeModel.getChild(realNode, i));
this.add(newNode);
newNode.updatePreferredSize(childRow++);
}
}
return super.children();
}
/** {@collect.stats}
* Messaged from expand and collapse. This is meant for subclassers
* that may wish to do something interesting with this.
*/
protected void didAdjustTree() {
}
/** {@collect.stats}
* Invokes <code>expandParentAndReceiver</code> on the parent,
* and expands the receiver.
*/
protected void expandParentAndReceiver() {
TreeStateNode parent = (TreeStateNode)getParent();
if(parent != null)
parent.expandParentAndReceiver();
expand();
}
/** {@collect.stats}
* Expands this node in the tree. This will load the children
* from the treeModel if this node has not previously been
* expanded. If <I>adjustTree</I> is true the tree and selection
* are updated accordingly.
*/
protected void expand(boolean adjustTree) {
if (!isExpanded() && !isLeaf()) {
boolean isFixed = isFixedRowHeight();
int startHeight = getPreferredHeight();
int originalRow = getRow();
expanded = true;
updatePreferredSize(originalRow);
if (!hasBeenExpanded) {
TreeStateNode newNode;
Object realNode = getValue();
TreeModel treeModel = getModel();
int count = treeModel.getChildCount(realNode);
hasBeenExpanded = true;
if(originalRow == -1) {
for (int i = 0; i < count; i++) {
newNode = createNodeForValue(treeModel.getChild
(realNode, i));
this.add(newNode);
newNode.updatePreferredSize(-1);
}
}
else {
int offset = originalRow + 1;
for (int i = 0; i < count; i++) {
newNode = createNodeForValue(treeModel.getChild
(realNode, i));
this.add(newNode);
newNode.updatePreferredSize(offset);
}
}
}
int i = originalRow;
Enumeration cursor = preorderEnumeration();
cursor.nextElement(); // don't add me, I'm already in
int newYOrigin;
if(isFixed)
newYOrigin = 0;
else if(this == root && !isRootVisible())
newYOrigin = 0;
else
newYOrigin = getYOrigin() + this.getPreferredHeight();
TreeStateNode aNode;
if(!isFixed) {
while (cursor.hasMoreElements()) {
aNode = (TreeStateNode)cursor.nextElement();
if(!updateNodeSizes && !aNode.hasValidSize())
aNode.updatePreferredSize(i + 1);
aNode.setYOrigin(newYOrigin);
newYOrigin += aNode.getPreferredHeight();
visibleNodes.insertElementAt(aNode, ++i);
}
}
else {
while (cursor.hasMoreElements()) {
aNode = (TreeStateNode)cursor.nextElement();
visibleNodes.insertElementAt(aNode, ++i);
}
}
if(adjustTree && (originalRow != i ||
getPreferredHeight() != startHeight)) {
// Adjust the Y origin of any nodes following this row.
if(!isFixed && ++i < getRowCount()) {
int counter;
int heightDiff = newYOrigin -
(getYOrigin() + getPreferredHeight()) +
(getPreferredHeight() - startHeight);
for(counter = visibleNodes.size() - 1;counter >= i;
counter--)
((TreeStateNode)visibleNodes.elementAt(counter)).
shiftYOriginBy(heightDiff);
}
didAdjustTree();
visibleNodesChanged();
}
// Update the rows in the selection
if(treeSelectionModel != null) {
treeSelectionModel.resetRowSelection();
}
}
}
/** {@collect.stats}
* Collapses this node in the tree. If <I>adjustTree</I> is
* true the tree and selection are updated accordingly.
*/
protected void collapse(boolean adjustTree) {
if (isExpanded()) {
Enumeration cursor = preorderEnumeration();
cursor.nextElement(); // don't remove me, I'm still visible
int rowsDeleted = 0;
boolean isFixed = isFixedRowHeight();
int lastYEnd;
if(isFixed)
lastYEnd = 0;
else
lastYEnd = getPreferredHeight() + getYOrigin();
int startHeight = getPreferredHeight();
int startYEnd = lastYEnd;
int myRow = getRow();
if(!isFixed) {
while(cursor.hasMoreElements()) {
TreeStateNode node = (TreeStateNode)cursor.
nextElement();
if (node.isVisible()) {
rowsDeleted++;
//visibleNodes.removeElement(node);
lastYEnd = node.getYOrigin() +
node.getPreferredHeight();
}
}
}
else {
while(cursor.hasMoreElements()) {
TreeStateNode node = (TreeStateNode)cursor.
nextElement();
if (node.isVisible()) {
rowsDeleted++;
//visibleNodes.removeElement(node);
}
}
}
// Clean up the visible nodes.
for (int counter = rowsDeleted + myRow; counter > myRow;
counter--) {
visibleNodes.removeElementAt(counter);
}
expanded = false;
if(myRow == -1)
markSizeInvalid();
else if (adjustTree)
updatePreferredSize(myRow);
if(myRow != -1 && adjustTree &&
(rowsDeleted > 0 || startHeight != getPreferredHeight())) {
// Adjust the Y origin of any rows following this one.
startYEnd += (getPreferredHeight() - startHeight);
if(!isFixed && (myRow + 1) < getRowCount() &&
startYEnd != lastYEnd) {
int counter, maxCounter, shiftAmount;
shiftAmount = startYEnd - lastYEnd;
for(counter = myRow + 1, maxCounter =
visibleNodes.size();
counter < maxCounter;counter++)
((TreeStateNode)visibleNodes.elementAt(counter))
.shiftYOriginBy(shiftAmount);
}
didAdjustTree();
visibleNodesChanged();
}
if(treeSelectionModel != null && rowsDeleted > 0 &&
myRow != -1) {
treeSelectionModel.resetRowSelection();
}
}
}
/** {@collect.stats}
* Removes the receiver, and all its children, from the mapping
* table.
*/
protected void removeFromMapping() {
if(path != null) {
removeMapping(this);
for(int counter = getChildCount() - 1; counter >= 0; counter--)
((TreeStateNode)getChildAt(counter)).removeFromMapping();
}
}
} // End of VariableHeightLayoutCache.TreeStateNode
/** {@collect.stats}
* An enumerator to iterate through visible nodes.
*/
private class VisibleTreeStateNodeEnumeration implements
Enumeration<TreePath> {
/** {@collect.stats} Parent thats children are being enumerated. */
protected TreeStateNode parent;
/** {@collect.stats} Index of next child. An index of -1 signifies parent should be
* visibled next. */
protected int nextIndex;
/** {@collect.stats} Number of children in parent. */
protected int childCount;
protected VisibleTreeStateNodeEnumeration(TreeStateNode node) {
this(node, -1);
}
protected VisibleTreeStateNodeEnumeration(TreeStateNode parent,
int startIndex) {
this.parent = parent;
this.nextIndex = startIndex;
this.childCount = this.parent.getChildCount();
}
/** {@collect.stats}
* @return true if more visible nodes.
*/
public boolean hasMoreElements() {
return (parent != null);
}
/** {@collect.stats}
* @return next visible TreePath.
*/
public TreePath nextElement() {
if(!hasMoreElements())
throw new NoSuchElementException("No more visible paths");
TreePath retObject;
if(nextIndex == -1) {
retObject = parent.getTreePath();
}
else {
TreeStateNode node = (TreeStateNode)parent.
getChildAt(nextIndex);
retObject = node.getTreePath();
}
updateNextObject();
return retObject;
}
/** {@collect.stats}
* Determines the next object by invoking <code>updateNextIndex</code>
* and if not succesful <code>findNextValidParent</code>.
*/
protected void updateNextObject() {
if(!updateNextIndex()) {
findNextValidParent();
}
}
/** {@collect.stats}
* Finds the next valid parent, this should be called when nextIndex
* is beyond the number of children of the current parent.
*/
protected boolean findNextValidParent() {
if(parent == root) {
// mark as invalid!
parent = null;
return false;
}
while(parent != null) {
TreeStateNode newParent = (TreeStateNode)parent.
getParent();
if(newParent != null) {
nextIndex = newParent.getIndex(parent);
parent = newParent;
childCount = parent.getChildCount();
if(updateNextIndex())
return true;
}
else
parent = null;
}
return false;
}
/** {@collect.stats}
* Updates <code>nextIndex</code> returning false if it is beyond
* the number of children of parent.
*/
protected boolean updateNextIndex() {
// nextIndex == -1 identifies receiver, make sure is expanded
// before descend.
if(nextIndex == -1 && !parent.isExpanded())
return false;
// Check that it can have kids
if(childCount == 0)
return false;
// Make sure next index not beyond child count.
else if(++nextIndex >= childCount)
return false;
TreeStateNode child = (TreeStateNode)parent.
getChildAt(nextIndex);
if(child != null && child.isExpanded()) {
parent = child;
nextIndex = -1;
childCount = child.getChildCount();
}
return true;
}
} // VariableHeightLayoutCache.VisibleTreeStateNodeEnumeration
}
|
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.tree;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
import javax.swing.plaf.basic.BasicGraphicsUtils;
import sun.swing.DefaultLookup;
/** {@collect.stats}
* Displays an entry in a tree.
* <code>DefaultTreeCellRenderer</code> is not opaque and
* unless you subclass paint you should not change this.
* See <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Trees</a>
* in <em>The Java Tutorial</em>
* for examples of customizing node display using this class.
* <p>
*
* <strong><a name="override">Implementation Note:</a></strong>
* This class overrides
* <code>invalidate</code>,
* <code>validate</code>,
* <code>revalidate</code>,
* <code>repaint</code>,
* and
* <code>firePropertyChange</code>
* solely to improve performance.
* If not overridden, these frequently called methods would execute code paths
* that are unnecessary for the default tree cell renderer.
* If you write your own renderer,
* take care to weigh the benefits and
* drawbacks of overriding these methods.
*
* <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 DefaultTreeCellRenderer extends JLabel implements TreeCellRenderer
{
/** {@collect.stats} Last tree the renderer was painted in. */
private JTree tree;
/** {@collect.stats} Is the value currently selected. */
protected boolean selected;
/** {@collect.stats} True if has focus. */
protected boolean hasFocus;
/** {@collect.stats} True if draws focus border around icon as well. */
private boolean drawsFocusBorderAroundIcon;
/** {@collect.stats} If true, a dashed line is drawn as the focus indicator. */
private boolean drawDashedFocusIndicator;
// If drawDashedFocusIndicator is true, the following are used.
/** {@collect.stats}
* Background color of the tree.
*/
private Color treeBGColor;
/** {@collect.stats}
* Color to draw the focus indicator in, determined from the background.
* color.
*/
private Color focusBGColor;
// Icons
/** {@collect.stats} Icon used to show non-leaf nodes that aren't expanded. */
transient protected Icon closedIcon;
/** {@collect.stats} Icon used to show leaf nodes. */
transient protected Icon leafIcon;
/** {@collect.stats} Icon used to show non-leaf nodes that are expanded. */
transient protected Icon openIcon;
// Colors
/** {@collect.stats} Color to use for the foreground for selected nodes. */
protected Color textSelectionColor;
/** {@collect.stats} Color to use for the foreground for non-selected nodes. */
protected Color textNonSelectionColor;
/** {@collect.stats} Color to use for the background when a node is selected. */
protected Color backgroundSelectionColor;
/** {@collect.stats} Color to use for the background when the node isn't selected. */
protected Color backgroundNonSelectionColor;
/** {@collect.stats} Color to use for the focus indicator when the node has focus. */
protected Color borderSelectionColor;
private boolean isDropCell;
private boolean fillBackground = true;
/** {@collect.stats}
* Returns a new instance of DefaultTreeCellRenderer. Alignment is
* set to left aligned. Icons and text color are determined from the
* UIManager.
*/
public DefaultTreeCellRenderer() {
setLeafIcon(DefaultLookup.getIcon(this, ui, "Tree.leafIcon"));
setClosedIcon(DefaultLookup.getIcon(this, ui, "Tree.closedIcon"));
setOpenIcon(DefaultLookup.getIcon(this, ui, "Tree.openIcon"));
setTextSelectionColor(DefaultLookup.getColor(this, ui, "Tree.selectionForeground"));
setTextNonSelectionColor(DefaultLookup.getColor(this, ui, "Tree.textForeground"));
setBackgroundSelectionColor(DefaultLookup.getColor(this, ui, "Tree.selectionBackground"));
setBackgroundNonSelectionColor(DefaultLookup.getColor(this, ui, "Tree.textBackground"));
setBorderSelectionColor(DefaultLookup.getColor(this, ui, "Tree.selectionBorderColor"));
drawsFocusBorderAroundIcon = DefaultLookup.getBoolean(
this, ui, "Tree.drawsFocusBorderAroundIcon", false);
drawDashedFocusIndicator = DefaultLookup.getBoolean(
this, ui, "Tree.drawDashedFocusIndicator", false);
fillBackground = DefaultLookup.getBoolean(this, ui, "Tree.rendererFillBackground", true);
Insets margins = DefaultLookup.getInsets(this, ui, "Tree.rendererMargins");
if (margins != null) {
setBorder(new EmptyBorder(margins.top, margins.left,
margins.bottom, margins.right));
}
setName("Tree.cellRenderer");
}
/** {@collect.stats}
* Returns the default icon, for the current laf, that is used to
* represent non-leaf nodes that are expanded.
*/
public Icon getDefaultOpenIcon() {
return DefaultLookup.getIcon(this, ui, "Tree.openIcon");
}
/** {@collect.stats}
* Returns the default icon, for the current laf, that is used to
* represent non-leaf nodes that are not expanded.
*/
public Icon getDefaultClosedIcon() {
return DefaultLookup.getIcon(this, ui, "Tree.closedIcon");
}
/** {@collect.stats}
* Returns the default icon, for the current laf, that is used to
* represent leaf nodes.
*/
public Icon getDefaultLeafIcon() {
return DefaultLookup.getIcon(this, ui, "Tree.leafIcon");
}
/** {@collect.stats}
* Sets the icon used to represent non-leaf nodes that are expanded.
*/
public void setOpenIcon(Icon newIcon) {
openIcon = newIcon;
}
/** {@collect.stats}
* Returns the icon used to represent non-leaf nodes that are expanded.
*/
public Icon getOpenIcon() {
return openIcon;
}
/** {@collect.stats}
* Sets the icon used to represent non-leaf nodes that are not expanded.
*/
public void setClosedIcon(Icon newIcon) {
closedIcon = newIcon;
}
/** {@collect.stats}
* Returns the icon used to represent non-leaf nodes that are not
* expanded.
*/
public Icon getClosedIcon() {
return closedIcon;
}
/** {@collect.stats}
* Sets the icon used to represent leaf nodes.
*/
public void setLeafIcon(Icon newIcon) {
leafIcon = newIcon;
}
/** {@collect.stats}
* Returns the icon used to represent leaf nodes.
*/
public Icon getLeafIcon() {
return leafIcon;
}
/** {@collect.stats}
* Sets the color the text is drawn with when the node is selected.
*/
public void setTextSelectionColor(Color newColor) {
textSelectionColor = newColor;
}
/** {@collect.stats}
* Returns the color the text is drawn with when the node is selected.
*/
public Color getTextSelectionColor() {
return textSelectionColor;
}
/** {@collect.stats}
* Sets the color the text is drawn with when the node isn't selected.
*/
public void setTextNonSelectionColor(Color newColor) {
textNonSelectionColor = newColor;
}
/** {@collect.stats}
* Returns the color the text is drawn with when the node isn't selected.
*/
public Color getTextNonSelectionColor() {
return textNonSelectionColor;
}
/** {@collect.stats}
* Sets the color to use for the background if node is selected.
*/
public void setBackgroundSelectionColor(Color newColor) {
backgroundSelectionColor = newColor;
}
/** {@collect.stats}
* Returns the color to use for the background if node is selected.
*/
public Color getBackgroundSelectionColor() {
return backgroundSelectionColor;
}
/** {@collect.stats}
* Sets the background color to be used for non selected nodes.
*/
public void setBackgroundNonSelectionColor(Color newColor) {
backgroundNonSelectionColor = newColor;
}
/** {@collect.stats}
* Returns the background color to be used for non selected nodes.
*/
public Color getBackgroundNonSelectionColor() {
return backgroundNonSelectionColor;
}
/** {@collect.stats}
* Sets the color to use for the border.
*/
public void setBorderSelectionColor(Color newColor) {
borderSelectionColor = newColor;
}
/** {@collect.stats}
* Returns the color the border is drawn.
*/
public Color getBorderSelectionColor() {
return borderSelectionColor;
}
/** {@collect.stats}
* Subclassed to map <code>FontUIResource</code>s to null. If
* <code>font</code> is null, or a <code>FontUIResource</code>, this
* has the effect of letting the font of the JTree show
* through. On the other hand, if <code>font</code> is non-null, and not
* a <code>FontUIResource</code>, the font becomes <code>font</code>.
*/
public void setFont(Font font) {
if(font instanceof FontUIResource)
font = null;
super.setFont(font);
}
/** {@collect.stats}
* Gets the font of this component.
* @return this component's font; if a font has not been set
* for this component, the font of its parent is returned
*/
public Font getFont() {
Font font = super.getFont();
if (font == null && tree != null) {
// Strive to return a non-null value, otherwise the html support
// will typically pick up the wrong font in certain situations.
font = tree.getFont();
}
return font;
}
/** {@collect.stats}
* Subclassed to map <code>ColorUIResource</code>s to null. If
* <code>color</code> is null, or a <code>ColorUIResource</code>, this
* has the effect of letting the background color of the JTree show
* through. On the other hand, if <code>color</code> is non-null, and not
* a <code>ColorUIResource</code>, the background becomes
* <code>color</code>.
*/
public void setBackground(Color color) {
if(color instanceof ColorUIResource)
color = null;
super.setBackground(color);
}
/** {@collect.stats}
* Configures the renderer based on the passed in components.
* The value is set from messaging the tree with
* <code>convertValueToText</code>, which ultimately invokes
* <code>toString</code> on <code>value</code>.
* The foreground color is set based on the selection and the icon
* is set based on the <code>leaf</code> and <code>expanded</code>
* parameters.
*/
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel,
boolean expanded,
boolean leaf, int row,
boolean hasFocus) {
String stringValue = tree.convertValueToText(value, sel,
expanded, leaf, row, hasFocus);
this.tree = tree;
this.hasFocus = hasFocus;
setText(stringValue);
Color fg = null;
isDropCell = false;
JTree.DropLocation dropLocation = tree.getDropLocation();
if (dropLocation != null
&& dropLocation.getChildIndex() == -1
&& tree.getRowForPath(dropLocation.getPath()) == row) {
Color col = DefaultLookup.getColor(this, ui, "Tree.dropCellForeground");
if (col != null) {
fg = col;
} else {
fg = getTextSelectionColor();
}
isDropCell = true;
} else if (sel) {
fg = getTextSelectionColor();
} else {
fg = getTextNonSelectionColor();
}
setForeground(fg);
Icon icon = null;
if (leaf) {
icon = getLeafIcon();
} else if (expanded) {
icon = getOpenIcon();
} else {
icon = getClosedIcon();
}
if (!tree.isEnabled()) {
setEnabled(false);
LookAndFeel laf = UIManager.getLookAndFeel();
Icon disabledIcon = laf.getDisabledIcon(tree, icon);
if (disabledIcon != null) icon = disabledIcon;
setDisabledIcon(icon);
} else {
setEnabled(true);
setIcon(icon);
}
setComponentOrientation(tree.getComponentOrientation());
selected = sel;
return this;
}
/** {@collect.stats}
* Paints the value. The background is filled based on selected.
*/
public void paint(Graphics g) {
Color bColor;
if (isDropCell) {
bColor = DefaultLookup.getColor(this, ui, "Tree.dropCellBackground");
if (bColor == null) {
bColor = getBackgroundSelectionColor();
}
} else if (selected) {
bColor = getBackgroundSelectionColor();
} else {
bColor = getBackgroundNonSelectionColor();
if (bColor == null) {
bColor = getBackground();
}
}
int imageOffset = -1;
if (bColor != null && fillBackground) {
imageOffset = getLabelStart();
g.setColor(bColor);
if(getComponentOrientation().isLeftToRight()) {
g.fillRect(imageOffset, 0, getWidth() - imageOffset,
getHeight());
} else {
g.fillRect(0, 0, getWidth() - imageOffset,
getHeight());
}
}
if (hasFocus) {
if (drawsFocusBorderAroundIcon) {
imageOffset = 0;
}
else if (imageOffset == -1) {
imageOffset = getLabelStart();
}
if(getComponentOrientation().isLeftToRight()) {
paintFocus(g, imageOffset, 0, getWidth() - imageOffset,
getHeight(), bColor);
} else {
paintFocus(g, 0, 0, getWidth() - imageOffset, getHeight(), bColor);
}
}
super.paint(g);
}
private void paintFocus(Graphics g, int x, int y, int w, int h, Color notColor) {
Color bsColor = getBorderSelectionColor();
if (bsColor != null && (selected || !drawDashedFocusIndicator)) {
g.setColor(bsColor);
g.drawRect(x, y, w - 1, h - 1);
}
if (drawDashedFocusIndicator && notColor != null) {
if (treeBGColor != notColor) {
treeBGColor = notColor;
focusBGColor = new Color(~notColor.getRGB());
}
g.setColor(focusBGColor);
BasicGraphicsUtils.drawDashedRect(g, x, y, w, h);
}
}
private int getLabelStart() {
Icon currentI = getIcon();
if(currentI != null && getText() != null) {
return currentI.getIconWidth() + Math.max(0, getIconTextGap() - 1);
}
return 0;
}
/** {@collect.stats}
* Overrides <code>JComponent.getPreferredSize</code> to
* return slightly wider preferred size value.
*/
public Dimension getPreferredSize() {
Dimension retDimension = super.getPreferredSize();
if(retDimension != null)
retDimension = new Dimension(retDimension.width + 3,
retDimension.height);
return retDimension;
}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void validate() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*
* @since 1.5
*/
public void invalidate() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void revalidate() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void repaint(long tm, int x, int y, int width, int height) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void repaint(Rectangle r) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*
* @since 1.5
*/
public void repaint() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
// Strings get interned...
if (propertyName == "text"
|| ((propertyName == "font" || propertyName == "foreground")
&& oldValue != newValue
&& getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey) != null)) {
super.firePropertyChange(propertyName, oldValue, newValue);
}
}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, char oldValue, char newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, short oldValue, short newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, long oldValue, long newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, float oldValue, float newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, double oldValue, double newValue) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
}
|
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.tree;
import java.awt.Component;
import javax.swing.JTree;
/** {@collect.stats}
* Defines the requirements for an object that displays a tree node.
* See <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Trees</a>
* in <em>The Java Tutorial</em>
* for an example of implementing a tree cell renderer
* that displays custom icons.
*
* @author Rob Davis
* @author Ray Ryan
* @author Scott Violet
*/
public interface TreeCellRenderer {
/** {@collect.stats}
* Sets the value of the current tree cell to <code>value</code>.
* If <code>selected</code> is true, the cell will be drawn as if
* selected. If <code>expanded</code> is true the node is currently
* expanded and if <code>leaf</code> is true the node represents a
* leaf and if <code>hasFocus</code> is true the node currently has
* focus. <code>tree</code> is the <code>JTree</code> the receiver is being
* configured for. Returns the <code>Component</code> that the renderer
* uses to draw the value.
* <p>
* The <code>TreeCellRenderer</code> is also responsible for rendering the
* the cell representing the tree's current DnD drop location if
* it has one. If this renderer cares about rendering
* the DnD drop location, it should query the tree directly to
* see if the given row represents the drop location:
* <pre>
* JTree.DropLocation dropLocation = tree.getDropLocation();
* if (dropLocation != null
* && dropLocation.getChildIndex() == -1
* && tree.getRowForPath(dropLocation.getPath()) == row) {
*
* // this row represents the current drop location
* // so render it specially, perhaps with a different color
* }
* </pre>
*
* @return the <code>Component</code> that the renderer uses to draw the value
*/
Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus);
}
|
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.tree;
// ISSUE: this class depends on nothing in AWT -- move to java.util?
import java.io.*;
import java.util.*;
/** {@collect.stats}
* A <code>DefaultMutableTreeNode</code> is a general-purpose node in a tree data
* structure.
* For examples of using default mutable tree nodes, see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Trees</a>
* in <em>The Java Tutorial.</em>
*
* <p>
*
* A tree node may have at most one parent and 0 or more children.
* <code>DefaultMutableTreeNode</code> provides operations for examining and modifying a
* node's parent and children and also operations for examining the tree that
* the node is a part of. A node's tree is the set of all nodes that can be
* reached by starting at the node and following all the possible links to
* parents and children. A node with no parent is the root of its tree; a
* node with no children is a leaf. A tree may consist of many subtrees,
* each node acting as the root for its own subtree.
* <p>
* This class provides enumerations for efficiently traversing a tree or
* subtree in various orders or for following the path between two nodes.
* A <code>DefaultMutableTreeNode</code> may also hold a reference to a user object, the
* use of which is left to the user. Asking a <code>DefaultMutableTreeNode</code> for its
* string representation with <code>toString()</code> returns the string
* representation of its user object.
* <p>
* <b>This is not a thread safe class.</b>If you intend to use
* a DefaultMutableTreeNode (or a tree of TreeNodes) in more than one thread, you
* need to do your own synchronizing. A good convention to adopt is
* synchronizing on the root node of a tree.
* <p>
* While DefaultMutableTreeNode implements the MutableTreeNode interface and
* will allow you to add in any implementation of MutableTreeNode not all
* of the methods in DefaultMutableTreeNode will be applicable to all
* MutableTreeNodes implementations. Especially with some of the enumerations
* that are provided, using some of these methods assumes the
* DefaultMutableTreeNode contains only DefaultMutableNode instances. All
* of the TreeNode/MutableTreeNode methods will behave as defined no
* matter what implementations are added.
*
* <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 MutableTreeNode
*
* @author Rob Davis
*/
public class DefaultMutableTreeNode extends Object implements Cloneable,
MutableTreeNode, Serializable
{
private static final long serialVersionUID = -4298474751201349152L;
/** {@collect.stats}
* An enumeration that is always empty. This is used when an enumeration
* of a leaf node's children is requested.
*/
static public final Enumeration<TreeNode> EMPTY_ENUMERATION
= new Enumeration<TreeNode>() {
public boolean hasMoreElements() { return false; }
public TreeNode nextElement() {
throw new NoSuchElementException("No more elements");
}
};
/** {@collect.stats} this node's parent, or null if this node has no parent */
protected MutableTreeNode parent;
/** {@collect.stats} array of children, may be null if this node has no children */
protected Vector children;
/** {@collect.stats} optional user object */
transient protected Object userObject;
/** {@collect.stats} true if the node is able to have children */
protected boolean allowsChildren;
/** {@collect.stats}
* Creates a tree node that has no parent and no children, but which
* allows children.
*/
public DefaultMutableTreeNode() {
this(null);
}
/** {@collect.stats}
* Creates a tree node with no parent, no children, but which allows
* children, and initializes it with the specified user object.
*
* @param userObject an Object provided by the user that constitutes
* the node's data
*/
public DefaultMutableTreeNode(Object userObject) {
this(userObject, true);
}
/** {@collect.stats}
* Creates a tree node with no parent, no children, initialized with
* the specified user object, and that allows children only if
* specified.
*
* @param userObject an Object provided by the user that constitutes
* the node's data
* @param allowsChildren if true, the node is allowed to have child
* nodes -- otherwise, it is always a leaf node
*/
public DefaultMutableTreeNode(Object userObject, boolean allowsChildren) {
super();
parent = null;
this.allowsChildren = allowsChildren;
this.userObject = userObject;
}
//
// Primitives
//
/** {@collect.stats}
* Removes <code>newChild</code> from its present parent (if it has a
* parent), sets the child's parent to this node, and then adds the child
* to this node's child array at index <code>childIndex</code>.
* <code>newChild</code> must not be null and must not be an ancestor of
* this node.
*
* @param newChild the MutableTreeNode to insert under this node
* @param childIndex the index in this node's child array
* where this node is to be inserted
* @exception ArrayIndexOutOfBoundsException if
* <code>childIndex</code> is out of bounds
* @exception IllegalArgumentException if
* <code>newChild</code> is null or is an
* ancestor of this node
* @exception IllegalStateException if this node does not allow
* children
* @see #isNodeDescendant
*/
public void insert(MutableTreeNode newChild, int childIndex) {
if (!allowsChildren) {
throw new IllegalStateException("node does not allow children");
} else if (newChild == null) {
throw new IllegalArgumentException("new child is null");
} else if (isNodeAncestor(newChild)) {
throw new IllegalArgumentException("new child is an ancestor");
}
MutableTreeNode oldParent = (MutableTreeNode)newChild.getParent();
if (oldParent != null) {
oldParent.remove(newChild);
}
newChild.setParent(this);
if (children == null) {
children = new Vector();
}
children.insertElementAt(newChild, childIndex);
}
/** {@collect.stats}
* Removes the child at the specified index from this node's children
* and sets that node's parent to null. The child node to remove
* must be a <code>MutableTreeNode</code>.
*
* @param childIndex the index in this node's child array
* of the child to remove
* @exception ArrayIndexOutOfBoundsException if
* <code>childIndex</code> is out of bounds
*/
public void remove(int childIndex) {
MutableTreeNode child = (MutableTreeNode)getChildAt(childIndex);
children.removeElementAt(childIndex);
child.setParent(null);
}
/** {@collect.stats}
* Sets this node's parent to <code>newParent</code> but does not
* change the parent's child array. This method is called from
* <code>insert()</code> and <code>remove()</code> to
* reassign a child's parent, it should not be messaged from anywhere
* else.
*
* @param newParent this node's new parent
*/
public void setParent(MutableTreeNode newParent) {
parent = newParent;
}
/** {@collect.stats}
* Returns this node's parent or null if this node has no parent.
*
* @return this node's parent TreeNode, or null if this node has no parent
*/
public TreeNode getParent() {
return parent;
}
/** {@collect.stats}
* Returns the child at the specified index in this node's child array.
*
* @param index an index into this node's child array
* @exception ArrayIndexOutOfBoundsException if <code>index</code>
* is out of bounds
* @return the TreeNode in this node's child array at the specified index
*/
public TreeNode getChildAt(int index) {
if (children == null) {
throw new ArrayIndexOutOfBoundsException("node has no children");
}
return (TreeNode)children.elementAt(index);
}
/** {@collect.stats}
* Returns the number of children of this node.
*
* @return an int giving the number of children of this node
*/
public int getChildCount() {
if (children == null) {
return 0;
} else {
return children.size();
}
}
/** {@collect.stats}
* Returns the index of the specified child in this node's child array.
* If the specified node is not a child of this node, returns
* <code>-1</code>. This method performs a linear search and is O(n)
* where n is the number of children.
*
* @param aChild the TreeNode to search for among this node's children
* @exception IllegalArgumentException if <code>aChild</code>
* is null
* @return an int giving the index of the node in this node's child
* array, or <code>-1</code> if the specified node is a not
* a child of this node
*/
public int getIndex(TreeNode aChild) {
if (aChild == null) {
throw new IllegalArgumentException("argument is null");
}
if (!isNodeChild(aChild)) {
return -1;
}
return children.indexOf(aChild); // linear search
}
/** {@collect.stats}
* Creates and returns a forward-order enumeration of this node's
* children. Modifying this node's child array invalidates any child
* enumerations created before the modification.
*
* @return an Enumeration of this node's children
*/
public Enumeration children() {
if (children == null) {
return EMPTY_ENUMERATION;
} else {
return children.elements();
}
}
/** {@collect.stats}
* Determines whether or not this node is allowed to have children.
* If <code>allows</code> is false, all of this node's children are
* removed.
* <p>
* Note: By default, a node allows children.
*
* @param allows true if this node is allowed to have children
*/
public void setAllowsChildren(boolean allows) {
if (allows != allowsChildren) {
allowsChildren = allows;
if (!allowsChildren) {
removeAllChildren();
}
}
}
/** {@collect.stats}
* Returns true if this node is allowed to have children.
*
* @return true if this node allows children, else false
*/
public boolean getAllowsChildren() {
return allowsChildren;
}
/** {@collect.stats}
* Sets the user object for this node to <code>userObject</code>.
*
* @param userObject the Object that constitutes this node's
* user-specified data
* @see #getUserObject
* @see #toString
*/
public void setUserObject(Object userObject) {
this.userObject = userObject;
}
/** {@collect.stats}
* Returns this node's user object.
*
* @return the Object stored at this node by the user
* @see #setUserObject
* @see #toString
*/
public Object getUserObject() {
return userObject;
}
//
// Derived methods
//
/** {@collect.stats}
* Removes the subtree rooted at this node from the tree, giving this
* node a null parent. Does nothing if this node is the root of its
* tree.
*/
public void removeFromParent() {
MutableTreeNode parent = (MutableTreeNode)getParent();
if (parent != null) {
parent.remove(this);
}
}
/** {@collect.stats}
* Removes <code>aChild</code> from this node's child array, giving it a
* null parent.
*
* @param aChild a child of this node to remove
* @exception IllegalArgumentException if <code>aChild</code>
* is null or is not a child of this node
*/
public void remove(MutableTreeNode aChild) {
if (aChild == null) {
throw new IllegalArgumentException("argument is null");
}
if (!isNodeChild(aChild)) {
throw new IllegalArgumentException("argument is not a child");
}
remove(getIndex(aChild)); // linear search
}
/** {@collect.stats}
* Removes all of this node's children, setting their parents to null.
* If this node has no children, this method does nothing.
*/
public void removeAllChildren() {
for (int i = getChildCount()-1; i >= 0; i--) {
remove(i);
}
}
/** {@collect.stats}
* Removes <code>newChild</code> from its parent and makes it a child of
* this node by adding it to the end of this node's child array.
*
* @see #insert
* @param newChild node to add as a child of this node
* @exception IllegalArgumentException if <code>newChild</code>
* is null
* @exception IllegalStateException if this node does not allow
* children
*/
public void add(MutableTreeNode newChild) {
if(newChild != null && newChild.getParent() == this)
insert(newChild, getChildCount() - 1);
else
insert(newChild, getChildCount());
}
//
// Tree Queries
//
/** {@collect.stats}
* Returns true if <code>anotherNode</code> is an ancestor of this node
* -- if it is this node, this node's parent, or an ancestor of this
* node's parent. (Note that a node is considered an ancestor of itself.)
* If <code>anotherNode</code> is null, this method returns false. This
* operation is at worst O(h) where h is the distance from the root to
* this node.
*
* @see #isNodeDescendant
* @see #getSharedAncestor
* @param anotherNode node to test as an ancestor of this node
* @return true if this node is a descendant of <code>anotherNode</code>
*/
public boolean isNodeAncestor(TreeNode anotherNode) {
if (anotherNode == null) {
return false;
}
TreeNode ancestor = this;
do {
if (ancestor == anotherNode) {
return true;
}
} while((ancestor = ancestor.getParent()) != null);
return false;
}
/** {@collect.stats}
* Returns true if <code>anotherNode</code> is a descendant of this node
* -- if it is this node, one of this node's children, or a descendant of
* one of this node's children. Note that a node is considered a
* descendant of itself. If <code>anotherNode</code> is null, returns
* false. This operation is at worst O(h) where h is the distance from the
* root to <code>anotherNode</code>.
*
* @see #isNodeAncestor
* @see #getSharedAncestor
* @param anotherNode node to test as descendant of this node
* @return true if this node is an ancestor of <code>anotherNode</code>
*/
public boolean isNodeDescendant(DefaultMutableTreeNode anotherNode) {
if (anotherNode == null)
return false;
return anotherNode.isNodeAncestor(this);
}
/** {@collect.stats}
* Returns the nearest common ancestor to this node and <code>aNode</code>.
* Returns null, if no such ancestor exists -- if this node and
* <code>aNode</code> are in different trees or if <code>aNode</code> is
* null. A node is considered an ancestor of itself.
*
* @see #isNodeAncestor
* @see #isNodeDescendant
* @param aNode node to find common ancestor with
* @return nearest ancestor common to this node and <code>aNode</code>,
* or null if none
*/
public TreeNode getSharedAncestor(DefaultMutableTreeNode aNode) {
if (aNode == this) {
return this;
} else if (aNode == null) {
return null;
}
int level1, level2, diff;
TreeNode node1, node2;
level1 = getLevel();
level2 = aNode.getLevel();
if (level2 > level1) {
diff = level2 - level1;
node1 = aNode;
node2 = this;
} else {
diff = level1 - level2;
node1 = this;
node2 = aNode;
}
// Go up the tree until the nodes are at the same level
while (diff > 0) {
node1 = node1.getParent();
diff--;
}
// Move up the tree until we find a common ancestor. Since we know
// that both nodes are at the same level, we won't cross paths
// unknowingly (if there is a common ancestor, both nodes hit it in
// the same iteration).
do {
if (node1 == node2) {
return node1;
}
node1 = node1.getParent();
node2 = node2.getParent();
} while (node1 != null);// only need to check one -- they're at the
// same level so if one is null, the other is
if (node1 != null || node2 != null) {
throw new Error ("nodes should be null");
}
return null;
}
/** {@collect.stats}
* Returns true if and only if <code>aNode</code> is in the same tree
* as this node. Returns false if <code>aNode</code> is null.
*
* @see #getSharedAncestor
* @see #getRoot
* @return true if <code>aNode</code> is in the same tree as this node;
* false if <code>aNode</code> is null
*/
public boolean isNodeRelated(DefaultMutableTreeNode aNode) {
return (aNode != null) && (getRoot() == aNode.getRoot());
}
/** {@collect.stats}
* Returns the depth of the tree rooted at this node -- the longest
* distance from this node to a leaf. If this node has no children,
* returns 0. This operation is much more expensive than
* <code>getLevel()</code> because it must effectively traverse the entire
* tree rooted at this node.
*
* @see #getLevel
* @return the depth of the tree whose root is this node
*/
public int getDepth() {
Object last = null;
Enumeration enum_ = breadthFirstEnumeration();
while (enum_.hasMoreElements()) {
last = enum_.nextElement();
}
if (last == null) {
throw new Error ("nodes should be null");
}
return ((DefaultMutableTreeNode)last).getLevel() - getLevel();
}
/** {@collect.stats}
* Returns the number of levels above this node -- the distance from
* the root to this node. If this node is the root, returns 0.
*
* @see #getDepth
* @return the number of levels above this node
*/
public int getLevel() {
TreeNode ancestor;
int levels = 0;
ancestor = this;
while((ancestor = ancestor.getParent()) != null){
levels++;
}
return levels;
}
/** {@collect.stats}
* Returns the path from the root, to get to this node. The last
* element in the path is this node.
*
* @return an array of TreeNode objects giving the path, where the
* first element in the path is the root and the last
* element is this node.
*/
public TreeNode[] getPath() {
return getPathToRoot(this, 0);
}
/** {@collect.stats}
* Builds the parents of node up to and including the root node,
* where the original node is the last element in the returned array.
* The length of the returned array gives the node's depth in the
* tree.
*
* @param aNode the TreeNode to get the path for
* @param depth an int giving the number of steps already taken towards
* the root (on recursive calls), used to size the returned array
* @return an array of TreeNodes giving the path from the root to the
* specified node
*/
protected TreeNode[] getPathToRoot(TreeNode aNode, int depth) {
TreeNode[] retNodes;
/* Check for null, in case someone passed in a null node, or
they passed in an element that isn't rooted at root. */
if(aNode == null) {
if(depth == 0)
return null;
else
retNodes = new TreeNode[depth];
}
else {
depth++;
retNodes = getPathToRoot(aNode.getParent(), depth);
retNodes[retNodes.length - depth] = aNode;
}
return retNodes;
}
/** {@collect.stats}
* Returns the user object path, from the root, to get to this node.
* If some of the TreeNodes in the path have null user objects, the
* returned path will contain nulls.
*/
public Object[] getUserObjectPath() {
TreeNode[] realPath = getPath();
Object[] retPath = new Object[realPath.length];
for(int counter = 0; counter < realPath.length; counter++)
retPath[counter] = ((DefaultMutableTreeNode)realPath[counter])
.getUserObject();
return retPath;
}
/** {@collect.stats}
* Returns the root of the tree that contains this node. The root is
* the ancestor with a null parent.
*
* @see #isNodeAncestor
* @return the root of the tree that contains this node
*/
public TreeNode getRoot() {
TreeNode ancestor = this;
TreeNode previous;
do {
previous = ancestor;
ancestor = ancestor.getParent();
} while (ancestor != null);
return previous;
}
/** {@collect.stats}
* Returns true if this node is the root of the tree. The root is
* the only node in the tree with a null parent; every tree has exactly
* one root.
*
* @return true if this node is the root of its tree
*/
public boolean isRoot() {
return getParent() == null;
}
/** {@collect.stats}
* Returns the node that follows this node in a preorder traversal of this
* node's tree. Returns null if this node is the last node of the
* traversal. This is an inefficient way to traverse the entire tree; use
* an enumeration, instead.
*
* @see #preorderEnumeration
* @return the node that follows this node in a preorder traversal, or
* null if this node is last
*/
public DefaultMutableTreeNode getNextNode() {
if (getChildCount() == 0) {
// No children, so look for nextSibling
DefaultMutableTreeNode nextSibling = getNextSibling();
if (nextSibling == null) {
DefaultMutableTreeNode aNode = (DefaultMutableTreeNode)getParent();
do {
if (aNode == null) {
return null;
}
nextSibling = aNode.getNextSibling();
if (nextSibling != null) {
return nextSibling;
}
aNode = (DefaultMutableTreeNode)aNode.getParent();
} while(true);
} else {
return nextSibling;
}
} else {
return (DefaultMutableTreeNode)getChildAt(0);
}
}
/** {@collect.stats}
* Returns the node that precedes this node in a preorder traversal of
* this node's tree. Returns <code>null</code> if this node is the
* first node of the traversal -- the root of the tree.
* This is an inefficient way to
* traverse the entire tree; use an enumeration, instead.
*
* @see #preorderEnumeration
* @return the node that precedes this node in a preorder traversal, or
* null if this node is the first
*/
public DefaultMutableTreeNode getPreviousNode() {
DefaultMutableTreeNode previousSibling;
DefaultMutableTreeNode myParent = (DefaultMutableTreeNode)getParent();
if (myParent == null) {
return null;
}
previousSibling = getPreviousSibling();
if (previousSibling != null) {
if (previousSibling.getChildCount() == 0)
return previousSibling;
else
return previousSibling.getLastLeaf();
} else {
return myParent;
}
}
/** {@collect.stats}
* Creates and returns an enumeration that traverses the subtree rooted at
* this node in preorder. The first node returned by the enumeration's
* <code>nextElement()</code> method is this node.<P>
*
* Modifying the tree by inserting, removing, or moving a node invalidates
* any enumerations created before the modification.
*
* @see #postorderEnumeration
* @return an enumeration for traversing the tree in preorder
*/
public Enumeration preorderEnumeration() {
return new PreorderEnumeration(this);
}
/** {@collect.stats}
* Creates and returns an enumeration that traverses the subtree rooted at
* this node in postorder. The first node returned by the enumeration's
* <code>nextElement()</code> method is the leftmost leaf. This is the
* same as a depth-first traversal.<P>
*
* Modifying the tree by inserting, removing, or moving a node invalidates
* any enumerations created before the modification.
*
* @see #depthFirstEnumeration
* @see #preorderEnumeration
* @return an enumeration for traversing the tree in postorder
*/
public Enumeration postorderEnumeration() {
return new PostorderEnumeration(this);
}
/** {@collect.stats}
* Creates and returns an enumeration that traverses the subtree rooted at
* this node in breadth-first order. The first node returned by the
* enumeration's <code>nextElement()</code> method is this node.<P>
*
* Modifying the tree by inserting, removing, or moving a node invalidates
* any enumerations created before the modification.
*
* @see #depthFirstEnumeration
* @return an enumeration for traversing the tree in breadth-first order
*/
public Enumeration breadthFirstEnumeration() {
return new BreadthFirstEnumeration(this);
}
/** {@collect.stats}
* Creates and returns an enumeration that traverses the subtree rooted at
* this node in depth-first order. The first node returned by the
* enumeration's <code>nextElement()</code> method is the leftmost leaf.
* This is the same as a postorder traversal.<P>
*
* Modifying the tree by inserting, removing, or moving a node invalidates
* any enumerations created before the modification.
*
* @see #breadthFirstEnumeration
* @see #postorderEnumeration
* @return an enumeration for traversing the tree in depth-first order
*/
public Enumeration depthFirstEnumeration() {
return postorderEnumeration();
}
/** {@collect.stats}
* Creates and returns an enumeration that follows the path from
* <code>ancestor</code> to this node. The enumeration's
* <code>nextElement()</code> method first returns <code>ancestor</code>,
* then the child of <code>ancestor</code> that is an ancestor of this
* node, and so on, and finally returns this node. Creation of the
* enumeration is O(m) where m is the number of nodes between this node
* and <code>ancestor</code>, inclusive. Each <code>nextElement()</code>
* message is O(1).<P>
*
* Modifying the tree by inserting, removing, or moving a node invalidates
* any enumerations created before the modification.
*
* @see #isNodeAncestor
* @see #isNodeDescendant
* @exception IllegalArgumentException if <code>ancestor</code> is
* not an ancestor of this node
* @return an enumeration for following the path from an ancestor of
* this node to this one
*/
public Enumeration pathFromAncestorEnumeration(TreeNode ancestor) {
return new PathBetweenNodesEnumeration(ancestor, this);
}
//
// Child Queries
//
/** {@collect.stats}
* Returns true if <code>aNode</code> is a child of this node. If
* <code>aNode</code> is null, this method returns false.
*
* @return true if <code>aNode</code> is a child of this node; false if
* <code>aNode</code> is null
*/
public boolean isNodeChild(TreeNode aNode) {
boolean retval;
if (aNode == null) {
retval = false;
} else {
if (getChildCount() == 0) {
retval = false;
} else {
retval = (aNode.getParent() == this);
}
}
return retval;
}
/** {@collect.stats}
* Returns this node's first child. If this node has no children,
* throws NoSuchElementException.
*
* @return the first child of this node
* @exception NoSuchElementException if this node has no children
*/
public TreeNode getFirstChild() {
if (getChildCount() == 0) {
throw new NoSuchElementException("node has no children");
}
return getChildAt(0);
}
/** {@collect.stats}
* Returns this node's last child. If this node has no children,
* throws NoSuchElementException.
*
* @return the last child of this node
* @exception NoSuchElementException if this node has no children
*/
public TreeNode getLastChild() {
if (getChildCount() == 0) {
throw new NoSuchElementException("node has no children");
}
return getChildAt(getChildCount()-1);
}
/** {@collect.stats}
* Returns the child in this node's child array that immediately
* follows <code>aChild</code>, which must be a child of this node. If
* <code>aChild</code> is the last child, returns null. This method
* performs a linear search of this node's children for
* <code>aChild</code> and is O(n) where n is the number of children; to
* traverse the entire array of children, use an enumeration instead.
*
* @see #children
* @exception IllegalArgumentException if <code>aChild</code> is
* null or is not a child of this node
* @return the child of this node that immediately follows
* <code>aChild</code>
*/
public TreeNode getChildAfter(TreeNode aChild) {
if (aChild == null) {
throw new IllegalArgumentException("argument is null");
}
int index = getIndex(aChild); // linear search
if (index == -1) {
throw new IllegalArgumentException("node is not a child");
}
if (index < getChildCount() - 1) {
return getChildAt(index + 1);
} else {
return null;
}
}
/** {@collect.stats}
* Returns the child in this node's child array that immediately
* precedes <code>aChild</code>, which must be a child of this node. If
* <code>aChild</code> is the first child, returns null. This method
* performs a linear search of this node's children for <code>aChild</code>
* and is O(n) where n is the number of children.
*
* @exception IllegalArgumentException if <code>aChild</code> is null
* or is not a child of this node
* @return the child of this node that immediately precedes
* <code>aChild</code>
*/
public TreeNode getChildBefore(TreeNode aChild) {
if (aChild == null) {
throw new IllegalArgumentException("argument is null");
}
int index = getIndex(aChild); // linear search
if (index == -1) {
throw new IllegalArgumentException("argument is not a child");
}
if (index > 0) {
return getChildAt(index - 1);
} else {
return null;
}
}
//
// Sibling Queries
//
/** {@collect.stats}
* Returns true if <code>anotherNode</code> is a sibling of (has the
* same parent as) this node. A node is its own sibling. If
* <code>anotherNode</code> is null, returns false.
*
* @param anotherNode node to test as sibling of this node
* @return true if <code>anotherNode</code> is a sibling of this node
*/
public boolean isNodeSibling(TreeNode anotherNode) {
boolean retval;
if (anotherNode == null) {
retval = false;
} else if (anotherNode == this) {
retval = true;
} else {
TreeNode myParent = getParent();
retval = (myParent != null && myParent == anotherNode.getParent());
if (retval && !((DefaultMutableTreeNode)getParent())
.isNodeChild(anotherNode)) {
throw new Error("sibling has different parent");
}
}
return retval;
}
/** {@collect.stats}
* Returns the number of siblings of this node. A node is its own sibling
* (if it has no parent or no siblings, this method returns
* <code>1</code>).
*
* @return the number of siblings of this node
*/
public int getSiblingCount() {
TreeNode myParent = getParent();
if (myParent == null) {
return 1;
} else {
return myParent.getChildCount();
}
}
/** {@collect.stats}
* Returns the next sibling of this node in the parent's children array.
* Returns null if this node has no parent or is the parent's last child.
* This method performs a linear search that is O(n) where n is the number
* of children; to traverse the entire array, use the parent's child
* enumeration instead.
*
* @see #children
* @return the sibling of this node that immediately follows this node
*/
public DefaultMutableTreeNode getNextSibling() {
DefaultMutableTreeNode retval;
DefaultMutableTreeNode myParent = (DefaultMutableTreeNode)getParent();
if (myParent == null) {
retval = null;
} else {
retval = (DefaultMutableTreeNode)myParent.getChildAfter(this); // linear search
}
if (retval != null && !isNodeSibling(retval)) {
throw new Error("child of parent is not a sibling");
}
return retval;
}
/** {@collect.stats}
* Returns the previous sibling of this node in the parent's children
* array. Returns null if this node has no parent or is the parent's
* first child. This method performs a linear search that is O(n) where n
* is the number of children.
*
* @return the sibling of this node that immediately precedes this node
*/
public DefaultMutableTreeNode getPreviousSibling() {
DefaultMutableTreeNode retval;
DefaultMutableTreeNode myParent = (DefaultMutableTreeNode)getParent();
if (myParent == null) {
retval = null;
} else {
retval = (DefaultMutableTreeNode)myParent.getChildBefore(this); // linear search
}
if (retval != null && !isNodeSibling(retval)) {
throw new Error("child of parent is not a sibling");
}
return retval;
}
//
// Leaf Queries
//
/** {@collect.stats}
* Returns true if this node has no children. To distinguish between
* nodes that have no children and nodes that <i>cannot</i> have
* children (e.g. to distinguish files from empty directories), use this
* method in conjunction with <code>getAllowsChildren</code>
*
* @see #getAllowsChildren
* @return true if this node has no children
*/
public boolean isLeaf() {
return (getChildCount() == 0);
}
/** {@collect.stats}
* Finds and returns the first leaf that is a descendant of this node --
* either this node or its first child's first leaf.
* Returns this node if it is a leaf.
*
* @see #isLeaf
* @see #isNodeDescendant
* @return the first leaf in the subtree rooted at this node
*/
public DefaultMutableTreeNode getFirstLeaf() {
DefaultMutableTreeNode node = this;
while (!node.isLeaf()) {
node = (DefaultMutableTreeNode)node.getFirstChild();
}
return node;
}
/** {@collect.stats}
* Finds and returns the last leaf that is a descendant of this node --
* either this node or its last child's last leaf.
* Returns this node if it is a leaf.
*
* @see #isLeaf
* @see #isNodeDescendant
* @return the last leaf in the subtree rooted at this node
*/
public DefaultMutableTreeNode getLastLeaf() {
DefaultMutableTreeNode node = this;
while (!node.isLeaf()) {
node = (DefaultMutableTreeNode)node.getLastChild();
}
return node;
}
/** {@collect.stats}
* Returns the leaf after this node or null if this node is the
* last leaf in the tree.
* <p>
* In this implementation of the <code>MutableNode</code> interface,
* this operation is very inefficient. In order to determine the
* next node, this method first performs a linear search in the
* parent's child-list in order to find the current node.
* <p>
* That implementation makes the operation suitable for short
* traversals from a known position. But to traverse all of the
* leaves in the tree, you should use <code>depthFirstEnumeration</code>
* to enumerate the nodes in the tree and use <code>isLeaf</code>
* on each node to determine which are leaves.
*
* @see #depthFirstEnumeration
* @see #isLeaf
* @return returns the next leaf past this node
*/
public DefaultMutableTreeNode getNextLeaf() {
DefaultMutableTreeNode nextSibling;
DefaultMutableTreeNode myParent = (DefaultMutableTreeNode)getParent();
if (myParent == null)
return null;
nextSibling = getNextSibling(); // linear search
if (nextSibling != null)
return nextSibling.getFirstLeaf();
return myParent.getNextLeaf(); // tail recursion
}
/** {@collect.stats}
* Returns the leaf before this node or null if this node is the
* first leaf in the tree.
* <p>
* In this implementation of the <code>MutableNode</code> interface,
* this operation is very inefficient. In order to determine the
* previous node, this method first performs a linear search in the
* parent's child-list in order to find the current node.
* <p>
* That implementation makes the operation suitable for short
* traversals from a known position. But to traverse all of the
* leaves in the tree, you should use <code>depthFirstEnumeration</code>
* to enumerate the nodes in the tree and use <code>isLeaf</code>
* on each node to determine which are leaves.
*
* @see #depthFirstEnumeration
* @see #isLeaf
* @return returns the leaf before this node
*/
public DefaultMutableTreeNode getPreviousLeaf() {
DefaultMutableTreeNode previousSibling;
DefaultMutableTreeNode myParent = (DefaultMutableTreeNode)getParent();
if (myParent == null)
return null;
previousSibling = getPreviousSibling(); // linear search
if (previousSibling != null)
return previousSibling.getLastLeaf();
return myParent.getPreviousLeaf(); // tail recursion
}
/** {@collect.stats}
* Returns the total number of leaves that are descendants of this node.
* If this node is a leaf, returns <code>1</code>. This method is O(n)
* where n is the number of descendants of this node.
*
* @see #isNodeAncestor
* @return the number of leaves beneath this node
*/
public int getLeafCount() {
int count = 0;
TreeNode node;
Enumeration enum_ = breadthFirstEnumeration(); // order matters not
while (enum_.hasMoreElements()) {
node = (TreeNode)enum_.nextElement();
if (node.isLeaf()) {
count++;
}
}
if (count < 1) {
throw new Error("tree has zero leaves");
}
return count;
}
//
// Overrides
//
/** {@collect.stats}
* Returns the result of sending <code>toString()</code> to this node's
* user object, or null if this node has no user object.
*
* @see #getUserObject
*/
public String toString() {
if (userObject == null) {
return null;
} else {
return userObject.toString();
}
}
/** {@collect.stats}
* Overridden to make clone public. Returns a shallow copy of this node;
* the new node has no parent or children and has a reference to the same
* user object, if any.
*
* @return a copy of this node
*/
public Object clone() {
DefaultMutableTreeNode newNode = null;
try {
newNode = (DefaultMutableTreeNode)super.clone();
// shallow copy -- the new node has no parent or children
newNode.children = null;
newNode.parent = null;
} catch (CloneNotSupportedException e) {
// Won't happen because we implement Cloneable
throw new Error(e.toString());
}
return newNode;
}
// Serialization support.
private void writeObject(ObjectOutputStream s) throws IOException {
Object[] tValues;
s.defaultWriteObject();
// Save the userObject, if its Serializable.
if(userObject != null && userObject instanceof Serializable) {
tValues = new Object[2];
tValues[0] = "userObject";
tValues[1] = userObject;
}
else
tValues = new Object[0];
s.writeObject(tValues);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
Object[] tValues;
s.defaultReadObject();
tValues = (Object[])s.readObject();
if(tValues.length > 0 && tValues[0].equals("userObject"))
userObject = tValues[1];
}
final class PreorderEnumeration implements Enumeration<TreeNode> {
protected Stack stack;
public PreorderEnumeration(TreeNode rootNode) {
super();
Vector v = new Vector(1);
v.addElement(rootNode); // PENDING: don't really need a vector
stack = new Stack();
stack.push(v.elements());
}
public boolean hasMoreElements() {
return (!stack.empty() &&
((Enumeration)stack.peek()).hasMoreElements());
}
public TreeNode nextElement() {
Enumeration enumer = (Enumeration)stack.peek();
TreeNode node = (TreeNode)enumer.nextElement();
Enumeration children = node.children();
if (!enumer.hasMoreElements()) {
stack.pop();
}
if (children.hasMoreElements()) {
stack.push(children);
}
return node;
}
} // End of class PreorderEnumeration
final class PostorderEnumeration implements Enumeration<TreeNode> {
protected TreeNode root;
protected Enumeration<TreeNode> children;
protected Enumeration<TreeNode> subtree;
public PostorderEnumeration(TreeNode rootNode) {
super();
root = rootNode;
children = root.children();
subtree = EMPTY_ENUMERATION;
}
public boolean hasMoreElements() {
return root != null;
}
public TreeNode nextElement() {
TreeNode retval;
if (subtree.hasMoreElements()) {
retval = subtree.nextElement();
} else if (children.hasMoreElements()) {
subtree = new PostorderEnumeration(
(TreeNode)children.nextElement());
retval = subtree.nextElement();
} else {
retval = root;
root = null;
}
return retval;
}
} // End of class PostorderEnumeration
final class BreadthFirstEnumeration implements Enumeration<TreeNode> {
protected Queue queue;
public BreadthFirstEnumeration(TreeNode rootNode) {
super();
Vector v = new Vector(1);
v.addElement(rootNode); // PENDING: don't really need a vector
queue = new Queue();
queue.enqueue(v.elements());
}
public boolean hasMoreElements() {
return (!queue.isEmpty() &&
((Enumeration)queue.firstObject()).hasMoreElements());
}
public TreeNode nextElement() {
Enumeration enumer = (Enumeration)queue.firstObject();
TreeNode node = (TreeNode)enumer.nextElement();
Enumeration children = node.children();
if (!enumer.hasMoreElements()) {
queue.dequeue();
}
if (children.hasMoreElements()) {
queue.enqueue(children);
}
return node;
}
// A simple queue with a linked list data structure.
final class Queue {
QNode head; // null if empty
QNode tail;
final class QNode {
public Object object;
public QNode next; // null if end
public QNode(Object object, QNode next) {
this.object = object;
this.next = next;
}
}
public void enqueue(Object anObject) {
if (head == null) {
head = tail = new QNode(anObject, null);
} else {
tail.next = new QNode(anObject, null);
tail = tail.next;
}
}
public Object dequeue() {
if (head == null) {
throw new NoSuchElementException("No more elements");
}
Object retval = head.object;
QNode oldHead = head;
head = head.next;
if (head == null) {
tail = null;
} else {
oldHead.next = null;
}
return retval;
}
public Object firstObject() {
if (head == null) {
throw new NoSuchElementException("No more elements");
}
return head.object;
}
public boolean isEmpty() {
return head == null;
}
} // End of class Queue
} // End of class BreadthFirstEnumeration
final class PathBetweenNodesEnumeration implements Enumeration<TreeNode> {
protected Stack<TreeNode> stack;
public PathBetweenNodesEnumeration(TreeNode ancestor,
TreeNode descendant)
{
super();
if (ancestor == null || descendant == null) {
throw new IllegalArgumentException("argument is null");
}
TreeNode current;
stack = new Stack<TreeNode>();
stack.push(descendant);
current = descendant;
while (current != ancestor) {
current = current.getParent();
if (current == null && descendant != ancestor) {
throw new IllegalArgumentException("node " + ancestor +
" is not an ancestor of " + descendant);
}
stack.push(current);
}
}
public boolean hasMoreElements() {
return stack.size() > 0;
}
public TreeNode nextElement() {
try {
return stack.pop();
} catch (EmptyStackException e) {
throw new NoSuchElementException("No more elements");
}
}
} // End of class PathBetweenNodesEnumeration
} // End of class DefaultMutableTreeNode
|
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.tree;
import java.io.*;
import java.util.Vector;
/** {@collect.stats}
* Represents a path to a node. A TreePath is an array of Objects that are
* vended from a TreeModel. The elements of the array are ordered such
* that the root is always the first element (index 0) of the array.
* TreePath is Serializable, but if any
* components of the path are not serializable, it will not be written
* out.
* <p>
* For further information and examples of using tree paths,
* see <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Trees</a>
* 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 Scott Violet
* @author Philip Milne
*/
public class TreePath extends Object implements Serializable {
/** {@collect.stats} Path representing the parent, null if lastPathComponent represents
* the root. */
private TreePath parentPath;
/** {@collect.stats} Last path component. */
transient private Object lastPathComponent;
/** {@collect.stats}
* Constructs a path from an array of Objects, uniquely identifying
* the path from the root of the tree to a specific node, as returned
* by the tree's data model.
* <p>
* The model is free to return an array of any Objects it needs to
* represent the path. The DefaultTreeModel returns an array of
* TreeNode objects. The first TreeNode in the path is the root of the
* tree, the last TreeNode is the node identified by the path.
*
* @param path an array of Objects representing the path to a node
*/
public TreePath(Object[] path) {
if(path == null || path.length == 0)
throw new IllegalArgumentException("path in TreePath must be non null and not empty.");
lastPathComponent = path[path.length - 1];
if(path.length > 1)
parentPath = new TreePath(path, path.length - 1);
}
/** {@collect.stats}
* Constructs a TreePath containing only a single element. This is
* usually used to construct a TreePath for the the root of the TreeModel.
* <p>
* @param singlePath an Object representing the path to a node
* @see #TreePath(Object[])
*/
public TreePath(Object singlePath) {
if(singlePath == null)
throw new IllegalArgumentException("path in TreePath must be non null.");
lastPathComponent = singlePath;
parentPath = null;
}
/** {@collect.stats}
* Constructs a new TreePath, which is the path identified by
* <code>parent</code> ending in <code>lastElement</code>.
*/
protected TreePath(TreePath parent, Object lastElement) {
if(lastElement == null)
throw new IllegalArgumentException("path in TreePath must be non null.");
parentPath = parent;
lastPathComponent = lastElement;
}
/** {@collect.stats}
* Constructs a new TreePath with the identified path components of
* length <code>length</code>.
*/
protected TreePath(Object[] path, int length) {
lastPathComponent = path[length - 1];
if(length > 1)
parentPath = new TreePath(path, length - 1);
}
/** {@collect.stats}
* Primarily provided for subclasses
* that represent paths in a different manner.
* If a subclass uses this constructor, it should also override
* the <code>getPath</code>,
* <code>getPathCount</code>, and
* <code>getPathComponent</code> methods,
* and possibly the <code>equals</code> method.
*/
protected TreePath() {
}
/** {@collect.stats}
* Returns an ordered array of Objects containing the components of this
* TreePath. The first element (index 0) is the root.
*
* @return an array of Objects representing the TreePath
* @see #TreePath(Object[])
*/
public Object[] getPath() {
int i = getPathCount();
Object[] result = new Object[i--];
for(TreePath path = this; path != null; path = path.parentPath) {
result[i--] = path.lastPathComponent;
}
return result;
}
/** {@collect.stats}
* Returns the last component of this path. For a path returned by
* DefaultTreeModel this will return an instance of TreeNode.
*
* @return the Object at the end of the path
* @see #TreePath(Object[])
*/
public Object getLastPathComponent() {
return lastPathComponent;
}
/** {@collect.stats}
* Returns the number of elements in the path.
*
* @return an int giving a count of items the path
*/
public int getPathCount() {
int result = 0;
for(TreePath path = this; path != null; path = path.parentPath) {
result++;
}
return result;
}
/** {@collect.stats}
* Returns the path component at the specified index.
*
* @param element an int specifying an element in the path, where
* 0 is the first element in the path
* @return the Object at that index location
* @throws IllegalArgumentException if the index is beyond the length
* of the path
* @see #TreePath(Object[])
*/
public Object getPathComponent(int element) {
int pathLength = getPathCount();
if(element < 0 || element >= pathLength)
throw new IllegalArgumentException("Index " + element + " is out of the specified range");
TreePath path = this;
for(int i = pathLength-1; i != element; i--) {
path = path.parentPath;
}
return path.lastPathComponent;
}
/** {@collect.stats}
* Tests two TreePaths for equality by checking each element of the
* paths for equality. Two paths are considered equal if they are of
* the same length, and contain
* the same elements (<code>.equals</code>).
*
* @param o the Object to compare
*/
public boolean equals(Object o) {
if(o == this)
return true;
if(o instanceof TreePath) {
TreePath oTreePath = (TreePath)o;
if(getPathCount() != oTreePath.getPathCount())
return false;
for(TreePath path = this; path != null; path = path.parentPath) {
if (!(path.lastPathComponent.equals
(oTreePath.lastPathComponent))) {
return false;
}
oTreePath = oTreePath.parentPath;
}
return true;
}
return false;
}
/** {@collect.stats}
* Returns the hashCode for the object. The hash code of a TreePath
* is defined to be the hash code of the last component in the path.
*
* @return the hashCode for the object
*/
public int hashCode() {
return lastPathComponent.hashCode();
}
/** {@collect.stats}
* Returns true if <code>aTreePath</code> is a
* descendant of this
* TreePath. A TreePath P1 is a descendant of a TreePath P2
* if P1 contains all of the components that make up
* P2's path.
* For example, if this object has the path [a, b],
* and <code>aTreePath</code> has the path [a, b, c],
* then <code>aTreePath</code> is a descendant of this object.
* However, if <code>aTreePath</code> has the path [a],
* then it is not a descendant of this object. By this definition
* a TreePath is always considered a descendant of itself. That is,
* <code>aTreePath.isDescendant(aTreePath)</code> returns true.
*
* @return true if <code>aTreePath</code> is a descendant of this path
*/
public boolean isDescendant(TreePath aTreePath) {
if(aTreePath == this)
return true;
if(aTreePath != null) {
int pathLength = getPathCount();
int oPathLength = aTreePath.getPathCount();
if(oPathLength < pathLength)
// Can't be a descendant, has fewer components in the path.
return false;
while(oPathLength-- > pathLength)
aTreePath = aTreePath.getParentPath();
return equals(aTreePath);
}
return false;
}
/** {@collect.stats}
* Returns a new path containing all the elements of this object
* plus <code>child</code>. <code>child</code> will be the last element
* of the newly created TreePath.
* This will throw a NullPointerException
* if child is null.
*/
public TreePath pathByAddingChild(Object child) {
if(child == null)
throw new NullPointerException("Null child not allowed");
return new TreePath(this, child);
}
/** {@collect.stats}
* Returns a path containing all the elements of this object, except
* the last path component.
*/
public TreePath getParentPath() {
return parentPath;
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public String toString() {
StringBuffer tempSpot = new StringBuffer("[");
for(int counter = 0, maxCounter = getPathCount();counter < maxCounter;
counter++) {
if(counter > 0)
tempSpot.append(", ");
tempSpot.append(getPathComponent(counter));
}
tempSpot.append("]");
return tempSpot.toString();
}
// Serialization support.
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
Vector values = new Vector();
boolean writePath = true;
if(lastPathComponent != null &&
(lastPathComponent instanceof Serializable)) {
values.addElement("lastPathComponent");
values.addElement(lastPathComponent);
}
s.writeObject(values);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
Vector values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("lastPathComponent")) {
lastPathComponent = values.elementAt(++indexCounter);
indexCounter++;
}
}
}
|
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.tree;
import java.awt.Component;
import javax.swing.CellEditor;
import javax.swing.JTree;
/** {@collect.stats}
* Adds to CellEditor the extensions necessary to configure an editor
* in a tree.
*
* @see javax.swing.JTree
*
* @author Scott Violet
*/
public interface TreeCellEditor extends CellEditor
{
/** {@collect.stats}
* Sets an initial <I>value</I> for the editor. This will cause
* the editor to stopEditing and lose any partially edited value
* if the editor is editing when this method is called. <p>
*
* Returns the component that should be added to the client's
* Component hierarchy. Once installed in the client's hierarchy
* this component will then be able to draw and receive user input.
*
* @param tree the JTree that is asking the editor to edit;
* this parameter can be null
* @param value the value of the cell to be edited
* @param isSelected true if the cell is to be rendered with
* selection highlighting
* @param expanded true if the node is expanded
* @param leaf true if the node is a leaf node
* @param row the row index of the node being edited
* @return the component for editing
*/
Component getTreeCellEditorComponent(JTree tree, Object value,
boolean isSelected, boolean expanded,
boolean leaf, int row);
}
|
Java
|
/*
* Copyright (c) 1997, 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.tree;
import javax.swing.event.*;
/** {@collect.stats}
* The model used by <code>JTree</code>.
* <p>
* <code>JTree</code> and its related classes make extensive use of
* <code>TreePath</code>s for indentifying nodes in the <code>TreeModel</code>.
* If a <code>TreeModel</code> returns the same object, as compared by
* <code>equals</code>, at two different indices under the same parent
* than the resulting <code>TreePath</code> objects will be considered equal
* as well. Some implementations may assume that if two
* <code>TreePath</code>s are equal, they identify the same node. If this
* condition is not met, painting problems and other oddities may result.
* In other words, if <code>getChild</code> for a given parent returns
* the same Object (as determined by <code>equals</code>) problems may
* result, and it is recommended you avoid doing this.
* <p>
* Similarly <code>JTree</code> and its related classes place
* <code>TreePath</code>s in <code>Map</code>s. As such if
* a node is requested twice, the return values must be equal
* (using the <code>equals</code> method) and have the same
* <code>hashCode</code>.
* <p>
* For further information on tree models,
* including an example of a custom implementation,
* see <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Trees</a>
* in <em>The Java Tutorial.</em>
*
* @see TreePath
*
* @author Rob Davis
* @author Ray Ryan
*/
public interface TreeModel
{
/** {@collect.stats}
* Returns the root of the tree. Returns <code>null</code>
* only if the tree has no nodes.
*
* @return the root of the tree
*/
public Object getRoot();
/** {@collect.stats}
* Returns the child of <code>parent</code> at index <code>index</code>
* in the parent's
* child array. <code>parent</code> must be a node previously obtained
* from this data source. This should not return <code>null</code>
* if <code>index</code>
* is a valid index for <code>parent</code> (that is <code>index >= 0 &&
* index < getChildCount(parent</code>)).
*
* @param parent a node in the tree, obtained from this data source
* @return the child of <code>parent</code> at index <code>index</code>
*/
public Object getChild(Object parent, int index);
/** {@collect.stats}
* Returns the number of children of <code>parent</code>.
* Returns 0 if the node
* is a leaf or if it has no children. <code>parent</code> must be a node
* previously obtained from this data source.
*
* @param parent a node in the tree, obtained from this data source
* @return the number of children of the node <code>parent</code>
*/
public int getChildCount(Object parent);
/** {@collect.stats}
* Returns <code>true</code> if <code>node</code> is a leaf.
* It is possible for this method to return <code>false</code>
* even if <code>node</code> has no children.
* A directory in a filesystem, for example,
* may contain no files; the node representing
* the directory is not a leaf, but it also has no children.
*
* @param node a node in the tree, obtained from this data source
* @return true if <code>node</code> is a leaf
*/
public boolean isLeaf(Object node);
/** {@collect.stats}
* Messaged when the user has altered the value for the item identified
* by <code>path</code> to <code>newValue</code>.
* If <code>newValue</code> signifies a truly new value
* the model should post a <code>treeNodesChanged</code> event.
*
* @param path path to the node that the user has altered
* @param newValue the new value from the TreeCellEditor
*/
public void valueForPathChanged(TreePath path, Object newValue);
/** {@collect.stats}
* Returns the index of child in parent. If either <code>parent</code>
* or <code>child</code> is <code>null</code>, returns -1.
* If either <code>parent</code> or <code>child</code> don't
* belong to this tree model, returns -1.
*
* @param parent a node in the tree, obtained from this data source
* @param child the node we are interested in
* @return the index of the child in the parent, or -1 if either
* <code>child</code> or <code>parent</code> are <code>null</code>
* or don't belong to this tree model
*/
public int getIndexOfChild(Object parent, Object child);
//
// Change Events
//
/** {@collect.stats}
* Adds a listener for the <code>TreeModelEvent</code>
* posted after the tree changes.
*
* @param l the listener to add
* @see #removeTreeModelListener
*/
void addTreeModelListener(TreeModelListener l);
/** {@collect.stats}
* Removes a listener previously added with
* <code>addTreeModelListener</code>.
*
* @see #addTreeModelListener
* @param l the listener to remove
*/
void removeTreeModelListener(TreeModelListener l);
}
|
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.HashSet;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
import java.util.EventListener;
import java.util.Set;
import java.awt.*;
import java.awt.event.*;
import java.awt.peer.LightweightPeer;
import java.beans.*;
import java.applet.Applet;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.ObjectInputValidation;
import java.io.InvalidObjectException;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import static javax.swing.ClientPropertyKey.*;
import javax.accessibility.*;
import sun.swing.SwingUtilities2;
import sun.swing.UIClientPropertyKey;
/** {@collect.stats}
* The base class for all Swing components except top-level containers.
* To use a component that inherits from <code>JComponent</code>,
* you must place the component in a containment hierarchy
* whose root is a top-level Swing container.
* Top-level Swing containers --
* such as <code>JFrame</code>, <code>JDialog</code>,
* and <code>JApplet</code> --
* are specialized components
* that provide a place for other Swing components to paint themselves.
* For an explanation of containment hierarchies, see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/overview/hierarchy.html">Swing Components and the Containment Hierarchy</a>,
* a section in <em>The Java Tutorial</em>.
*
* <p>
* The <code>JComponent</code> class provides:
* <ul>
* <li>The base class for both standard and custom components
* that use the Swing architecture.
* <li>A "pluggable look and feel" (L&F) that can be specified by the
* programmer or (optionally) selected by the user at runtime.
* The look and feel for each component is provided by a
* <em>UI delegate</em> -- an object that descends from
* {@link javax.swing.plaf.ComponentUI}.
* See <a
* href="http://java.sun.com/docs/books/tutorial/uiswing/misc/plaf.html">How
* to Set the Look and Feel</a>
* in <em>The Java Tutorial</em>
* for more information.
* <li>Comprehensive keystroke handling.
* See the document <a
* href="http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html">Keyboard
* Bindings in Swing</a>,
* an article in <em>The Swing Connection</em>,
* for more information.
* <li>Support for tool tips --
* short descriptions that pop up when the cursor lingers
* over a component.
* See <a
* href="http://java.sun.com/docs/books/tutorial/uiswing/components/tooltip.html">How
* to Use Tool Tips</a>
* in <em>The Java Tutorial</em>
* for more information.
* <li>Support for accessibility.
* <code>JComponent</code> contains all of the methods in the
* <code>Accessible</code> interface,
* but it doesn't actually implement the interface. That is the
* responsibility of the individual classes
* that extend <code>JComponent</code>.
* <li>Support for component-specific properties.
* With the {@link #putClientProperty}
* and {@link #getClientProperty} methods,
* you can associate name-object pairs
* with any object that descends from <code>JComponent</code>.
* <li>An infrastructure for painting
* that includes double buffering and support for borders.
* For more information see <a
* href="http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html">Painting</a> and
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/border.html">How
* to Use Borders</a>,
* both of which are sections in <em>The Java Tutorial</em>.
* </ul>
* For more information on these subjects, see the
* <a href="package-summary.html#package_description">Swing package description</a>
* and <em>The Java Tutorial</em> section
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/jcomponent.html">The JComponent Class</a>.
* <p>
* <code>JComponent</code> and its subclasses document default values
* for certain properties. For example, <code>JTable</code> documents the
* default row height as 16. Each <code>JComponent</code> subclass
* that has a <code>ComponentUI</code> will create the
* <code>ComponentUI</code> as part of its constructor. In order
* to provide a particular look and feel each
* <code>ComponentUI</code> may set properties back on the
* <code>JComponent</code> that created it. For example, a custom
* look and feel may require <code>JTable</code>s to have a row
* height of 24. The documented defaults are the value of a property
* BEFORE the <code>ComponentUI</code> has been installed. If you
* need a specific value for a particular property you should
* explicitly set it.
* <p>
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</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 KeyStroke
* @see Action
* @see #setBorder
* @see #registerKeyboardAction
* @see JOptionPane
* @see #setDebugGraphicsOptions
* @see #setToolTipText
* @see #setAutoscrolls
*
* @author Hans Muller
* @author Arnaud Weber
*/
public abstract class JComponent extends Container implements Serializable,
TransferHandler.HasGetTransferHandler
{
/** {@collect.stats}
* @see #getUIClassID
* @see #writeObject
*/
private static final String uiClassID = "ComponentUI";
/** {@collect.stats}
* @see #readObject
*/
private static final Hashtable readObjectCallbacks = new Hashtable(1);
/** {@collect.stats}
* Keys to use for forward focus traversal when the JComponent is
* managing focus.
*/
private static Set<KeyStroke> managingFocusForwardTraversalKeys;
/** {@collect.stats}
* Keys to use for backward focus traversal when the JComponent is
* managing focus.
*/
private static Set<KeyStroke> managingFocusBackwardTraversalKeys;
// Following are the possible return values from getObscuredState.
private static final int NOT_OBSCURED = 0;
private static final int PARTIALLY_OBSCURED = 1;
private static final int COMPLETELY_OBSCURED = 2;
/** {@collect.stats}
* Set to true when DebugGraphics has been loaded.
*/
static boolean DEBUG_GRAPHICS_LOADED;
/** {@collect.stats}
* Key used to look up a value from the AppContext to determine the
* JComponent the InputVerifier is running for. That is, if
* AppContext.get(INPUT_VERIFIER_SOURCE_KEY) returns non-null, it
* indicates the EDT is calling into the InputVerifier from the
* returned component.
*/
private static final Object INPUT_VERIFIER_SOURCE_KEY = new Object(); // InputVerifierSourceKey
/* The following fields support set methods for the corresponding
* java.awt.Component properties.
*/
private boolean isAlignmentXSet;
private float alignmentX;
private boolean isAlignmentYSet;
private float alignmentY;
/** {@collect.stats}
* Backing store for JComponent properties and listeners
*/
/** {@collect.stats} The look and feel delegate for this component. */
protected transient ComponentUI ui;
/** {@collect.stats} A list of event listeners for this component. */
protected EventListenerList listenerList = new EventListenerList();
private transient ArrayTable clientProperties;
private VetoableChangeSupport vetoableChangeSupport;
/** {@collect.stats}
* Whether or not autoscroll has been enabled.
*/
private boolean autoscrolls;
private Border border;
private int flags;
/* Input verifier for this component */
private InputVerifier inputVerifier = null;
private boolean verifyInputWhenFocusTarget = true;
/** {@collect.stats}
* Set in <code>_paintImmediately</code>.
* Will indicate the child that initiated the painting operation.
* If <code>paintingChild</code> is opaque, no need to paint
* any child components after <code>paintingChild</code>.
* Test used in <code>paintChildren</code>.
*/
transient Component paintingChild;
/** {@collect.stats}
* Constant used for <code>registerKeyboardAction</code> that
* means that the command should be invoked when
* the component has the focus.
*/
public static final int WHEN_FOCUSED = 0;
/** {@collect.stats}
* Constant used for <code>registerKeyboardAction</code> that
* means that the command should be invoked when the receiving
* component is an ancestor of the focused component or is
* itself the focused component.
*/
public static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT = 1;
/** {@collect.stats}
* Constant used for <code>registerKeyboardAction</code> that
* means that the command should be invoked when
* the receiving component is in the window that has the focus
* or is itself the focused component.
*/
public static final int WHEN_IN_FOCUSED_WINDOW = 2;
/** {@collect.stats}
* Constant used by some of the APIs to mean that no condition is defined.
*/
public static final int UNDEFINED_CONDITION = -1;
/** {@collect.stats}
* The key used by <code>JComponent</code> to access keyboard bindings.
*/
private static final String KEYBOARD_BINDINGS_KEY = "_KeyboardBindings";
/** {@collect.stats}
* An array of <code>KeyStroke</code>s used for
* <code>WHEN_IN_FOCUSED_WINDOW</code> are stashed
* in the client properties under this string.
*/
private static final String WHEN_IN_FOCUSED_WINDOW_BINDINGS = "_WhenInFocusedWindow";
/** {@collect.stats}
* The comment to display when the cursor is over the component,
* also known as a "value tip", "flyover help", or "flyover label".
*/
public static final String TOOL_TIP_TEXT_KEY = "ToolTipText";
private static final String NEXT_FOCUS = "nextFocus";
/** {@collect.stats}
* <code>JPopupMenu</code> assigned to this component
* and all of its childrens
*/
private JPopupMenu popupMenu;
/** {@collect.stats} Private flags **/
private static final int IS_DOUBLE_BUFFERED = 0;
private static final int ANCESTOR_USING_BUFFER = 1;
private static final int IS_PAINTING_TILE = 2;
private static final int IS_OPAQUE = 3;
private static final int KEY_EVENTS_ENABLED = 4;
private static final int FOCUS_INPUTMAP_CREATED = 5;
private static final int ANCESTOR_INPUTMAP_CREATED = 6;
private static final int WIF_INPUTMAP_CREATED = 7;
private static final int ACTIONMAP_CREATED = 8;
private static final int CREATED_DOUBLE_BUFFER = 9;
// bit 10 is free
private static final int IS_PRINTING = 11;
private static final int IS_PRINTING_ALL = 12;
private static final int IS_REPAINTING = 13;
/** {@collect.stats} Bits 14-21 are used to handle nested writeObject calls. **/
private static final int WRITE_OBJ_COUNTER_FIRST = 14;
private static final int RESERVED_1 = 15;
private static final int RESERVED_2 = 16;
private static final int RESERVED_3 = 17;
private static final int RESERVED_4 = 18;
private static final int RESERVED_5 = 19;
private static final int RESERVED_6 = 20;
private static final int WRITE_OBJ_COUNTER_LAST = 21;
private static final int REQUEST_FOCUS_DISABLED = 22;
private static final int INHERITS_POPUP_MENU = 23;
private static final int OPAQUE_SET = 24;
private static final int AUTOSCROLLS_SET = 25;
private static final int FOCUS_TRAVERSAL_KEYS_FORWARD_SET = 26;
private static final int FOCUS_TRAVERSAL_KEYS_BACKWARD_SET = 27;
private static final int REVALIDATE_RUNNABLE_SCHEDULED = 28;
/** {@collect.stats}
* Temporary rectangles.
*/
private static java.util.List tempRectangles = new java.util.ArrayList(11);
/** {@collect.stats} Used for <code>WHEN_FOCUSED</code> bindings. */
private InputMap focusInputMap;
/** {@collect.stats} Used for <code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code> bindings. */
private InputMap ancestorInputMap;
/** {@collect.stats} Used for <code>WHEN_IN_FOCUSED_KEY</code> bindings. */
private ComponentInputMap windowInputMap;
/** {@collect.stats} ActionMap. */
private ActionMap actionMap;
/** {@collect.stats} Key used to store the default locale in an AppContext **/
private static final String defaultLocale = "JComponent.defaultLocale";
private static Component componentObtainingGraphicsFrom;
private static Object componentObtainingGraphicsFromLock = new Object(); // componentObtainingGraphicsFrom
/** {@collect.stats}
* AA text hints.
*/
transient private Object aaTextInfo;
static Graphics safelyGetGraphics(Component c) {
return safelyGetGraphics(c, SwingUtilities.getRoot(c));
}
static Graphics safelyGetGraphics(Component c, Component root) {
synchronized(componentObtainingGraphicsFromLock) {
componentObtainingGraphicsFrom = root;
Graphics g = c.getGraphics();
componentObtainingGraphicsFrom = null;
return g;
}
}
static void getGraphicsInvoked(Component root) {
if (!JComponent.isComponentObtainingGraphicsFrom(root)) {
JRootPane rootPane = ((RootPaneContainer)root).getRootPane();
if (rootPane != null) {
rootPane.disableTrueDoubleBuffering();
}
}
}
/** {@collect.stats}
* Returns true if {@code c} is the component the graphics is being
* requested of. This is intended for use when getGraphics is invoked.
*/
private static boolean isComponentObtainingGraphicsFrom(Component c) {
synchronized(componentObtainingGraphicsFromLock) {
return (componentObtainingGraphicsFrom == c);
}
}
/** {@collect.stats}
* Returns the Set of <code>KeyStroke</code>s to use if the component
* is managing focus for forward focus traversal.
*/
static Set<KeyStroke> getManagingFocusForwardTraversalKeys() {
synchronized(JComponent.class) {
if (managingFocusForwardTraversalKeys == null) {
managingFocusForwardTraversalKeys = new HashSet<KeyStroke>(1);
managingFocusForwardTraversalKeys.add(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
InputEvent.CTRL_MASK));
}
}
return managingFocusForwardTraversalKeys;
}
/** {@collect.stats}
* Returns the Set of <code>KeyStroke</code>s to use if the component
* is managing focus for backward focus traversal.
*/
static Set<KeyStroke> getManagingFocusBackwardTraversalKeys() {
synchronized(JComponent.class) {
if (managingFocusBackwardTraversalKeys == null) {
managingFocusBackwardTraversalKeys = new HashSet<KeyStroke>(1);
managingFocusBackwardTraversalKeys.add(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
InputEvent.SHIFT_MASK |
InputEvent.CTRL_MASK));
}
}
return managingFocusBackwardTraversalKeys;
}
private static Rectangle fetchRectangle() {
synchronized(tempRectangles) {
Rectangle rect;
int size = tempRectangles.size();
if (size > 0) {
rect = (Rectangle)tempRectangles.remove(size - 1);
}
else {
rect = new Rectangle(0, 0, 0, 0);
}
return rect;
}
}
private static void recycleRectangle(Rectangle rect) {
synchronized(tempRectangles) {
tempRectangles.add(rect);
}
}
/** {@collect.stats}
* Sets whether or not <code>getComponentPopupMenu</code> should delegate
* to the parent if this component does not have a <code>JPopupMenu</code>
* assigned to it.
* <p>
* The default value for this is false, but some <code>JComponent</code>
* subclasses that are implemented as a number of <code>JComponent</code>s
* may set this to true.
* <p>
* This is a bound property.
*
* @param value whether or not the JPopupMenu is inherited
* @see #setComponentPopupMenu
* @beaninfo
* bound: true
* description: Whether or not the JPopupMenu is inherited
* @since 1.5
*/
public void setInheritsPopupMenu(boolean value) {
boolean oldValue = getFlag(INHERITS_POPUP_MENU);
setFlag(INHERITS_POPUP_MENU, value);
firePropertyChange("inheritsPopupMenu", oldValue, value);
}
/** {@collect.stats}
* Returns true if the JPopupMenu should be inherited from the parent.
*
* @see #setComponentPopupMenu
* @since 1.5
*/
public boolean getInheritsPopupMenu() {
return getFlag(INHERITS_POPUP_MENU);
}
/** {@collect.stats}
* Sets the <code>JPopupMenu</code> for this <code>JComponent</code>.
* The UI is responsible for registering bindings and adding the necessary
* listeners such that the <code>JPopupMenu</code> will be shown at
* the appropriate time. When the <code>JPopupMenu</code> is shown
* depends upon the look and feel: some may show it on a mouse event,
* some may enable a key binding.
* <p>
* If <code>popup</code> is null, and <code>getInheritsPopupMenu</code>
* returns true, then <code>getComponentPopupMenu</code> will be delegated
* to the parent. This provides for a way to make all child components
* inherit the popupmenu of the parent.
* <p>
* This is a bound property.
*
* @param popup - the popup that will be assigned to this component
* may be null
* @see #getComponentPopupMenu
* @beaninfo
* bound: true
* preferred: true
* description: Popup to show
* @since 1.5
*/
public void setComponentPopupMenu(JPopupMenu popup) {
if(popup != null) {
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
JPopupMenu oldPopup = this.popupMenu;
this.popupMenu = popup;
firePropertyChange("componentPopupMenu", oldPopup, popup);
}
/** {@collect.stats}
* Returns <code>JPopupMenu</code> that assigned for this component.
* If this component does not have a <code>JPopupMenu</code> assigned
* to it and <code>getInheritsPopupMenu</code> is true, this
* will return <code>getParent().getComponentPopupMenu()</code> (assuming
* the parent is valid.)
*
* @return <code>JPopupMenu</code> assigned for this component
* or <code>null</code> if no popup assigned
* @see #setComponentPopupMenu
* @since 1.5
*/
public JPopupMenu getComponentPopupMenu() {
if(!getInheritsPopupMenu()) {
return popupMenu;
}
if(popupMenu == null) {
// Search parents for its popup
Container parent = getParent();
while (parent != null) {
if(parent instanceof JComponent) {
return ((JComponent)parent).getComponentPopupMenu();
}
if(parent instanceof Window ||
parent instanceof Applet) {
// Reached toplevel, break and return null
break;
}
parent = parent.getParent();
}
return null;
}
return popupMenu;
}
/** {@collect.stats}
* Default <code>JComponent</code> constructor. This constructor does
* very little initialization beyond calling the <code>Container</code>
* constructor. For example, the initial layout manager is
* <code>null</code>. It does, however, set the component's locale
* property to the value returned by
* <code>JComponent.getDefaultLocale</code>.
*
* @see #getDefaultLocale
*/
public JComponent() {
super();
// We enable key events on all JComponents so that accessibility
// bindings will work everywhere. This is a partial fix to BugID
// 4282211.
enableEvents(AWTEvent.KEY_EVENT_MASK);
if (isManagingFocus()) {
LookAndFeel.installProperty(this,
"focusTraversalKeysForward",
getManagingFocusForwardTraversalKeys());
LookAndFeel.installProperty(this,
"focusTraversalKeysBackward",
getManagingFocusBackwardTraversalKeys());
}
super.setLocale( JComponent.getDefaultLocale() );
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
* <code>JComponent</code> subclasses must override this method
* like this:
* <pre>
* public void updateUI() {
* setUI((SliderUI)UIManager.getUI(this);
* }
* </pre>
*
* @see #setUI
* @see UIManager#getLookAndFeel
* @see UIManager#getUI
*/
public void updateUI() {}
/** {@collect.stats}
* Sets the look and feel delegate for this component.
* <code>JComponent</code> subclasses generally override this method
* to narrow the argument type. For example, in <code>JSlider</code>:
* <pre>
* public void setUI(SliderUI newUI) {
* super.setUI(newUI);
* }
* </pre>
* <p>
* Additionally <code>JComponent</code> subclasses must provide a
* <code>getUI</code> method that returns the correct type. For example:
* <pre>
* public SliderUI getUI() {
* return (SliderUI)ui;
* }
* </pre>
*
* @param newUI the new UI delegate
* @see #updateUI
* @see UIManager#getLookAndFeel
* @see UIManager#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The component's look and feel delegate.
*/
protected void setUI(ComponentUI newUI) {
/* We do not check that the UI instance is different
* before allowing the switch in order to enable the
* same UI instance *with different default settings*
* to be installed.
*/
uninstallUIAndProperties();
// aaText shouldn't persist between look and feels, reset it.
aaTextInfo =
UIManager.getDefaults().get(SwingUtilities2.AA_TEXT_PROPERTY_KEY);
ComponentUI oldUI = ui;
ui = newUI;
if (ui != null) {
ui.installUI(this);
}
firePropertyChange("UI", oldUI, newUI);
revalidate();
repaint();
}
/** {@collect.stats}
* Uninstalls the UI, if any, and any client properties designated
* as being specific to the installed UI - instances of
* {@code UIClientPropertyKey}.
*/
private void uninstallUIAndProperties() {
if (ui != null) {
ui.uninstallUI(this);
//clean UIClientPropertyKeys from client properties
if (clientProperties != null) {
synchronized(clientProperties) {
Object[] clientPropertyKeys =
clientProperties.getKeys(null);
if (clientPropertyKeys != null) {
for (Object key : clientPropertyKeys) {
if (key instanceof UIClientPropertyKey) {
putClientProperty(key, null);
}
}
}
}
}
}
}
/** {@collect.stats}
* Returns the <code>UIDefaults</code> key used to
* look up the name of the <code>swing.plaf.ComponentUI</code>
* class that defines the look and feel
* for this component. Most applications will never need to
* call this method. Subclasses of <code>JComponent</code> that support
* pluggable look and feel should override this method to
* return a <code>UIDefaults</code> key that maps to the
* <code>ComponentUI</code> subclass that defines their look and feel.
*
* @return the <code>UIDefaults</code> key for a
* <code>ComponentUI</code> subclass
* @see UIDefaults#getUI
* @beaninfo
* expert: true
* description: UIClassID
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns the graphics object used to paint this component.
* If <code>DebugGraphics</code> is turned on we create a new
* <code>DebugGraphics</code> object if necessary.
* Otherwise we just configure the
* specified graphics object's foreground and font.
*
* @param g the original <code>Graphics</code> object
* @return a <code>Graphics</code> object configured for this component
*/
protected Graphics getComponentGraphics(Graphics g) {
Graphics componentGraphics = g;
if (ui != null && DEBUG_GRAPHICS_LOADED) {
if ((DebugGraphics.debugComponentCount() != 0) &&
(shouldDebugGraphics() != 0) &&
!(g instanceof DebugGraphics)) {
componentGraphics = new DebugGraphics(g,this);
}
}
componentGraphics.setColor(getForeground());
componentGraphics.setFont(getFont());
return componentGraphics;
}
/** {@collect.stats}
* Calls the UI delegate's paint method, if the UI delegate
* is non-<code>null</code>. We pass the delegate a copy of the
* <code>Graphics</code> object to protect the rest of the
* paint code from irrevocable changes
* (for example, <code>Graphics.translate</code>).
* <p>
* If you override this in a subclass you should not make permanent
* changes to the passed in <code>Graphics</code>. For example, you
* should not alter the clip <code>Rectangle</code> or modify the
* transform. If you need to do these operations you may find it
* easier to create a new <code>Graphics</code> from the passed in
* <code>Graphics</code> and manipulate it. Further, if you do not
* invoker super's implementation you must honor the opaque property,
* that is
* if this component is opaque, you must completely fill in the background
* in a non-opaque color. If you do not honor the opaque property you
* will likely see visual artifacts.
* <p>
* The passed in <code>Graphics</code> object might
* have a transform other than the identify transform
* installed on it. In this case, you might get
* unexpected results if you cumulatively apply
* another transform.
*
* @param g the <code>Graphics</code> object to protect
* @see #paint
* @see ComponentUI
*/
protected void paintComponent(Graphics g) {
if (ui != null) {
Graphics scratchGraphics = (g == null) ? null : g.create();
try {
ui.update(scratchGraphics, this);
}
finally {
scratchGraphics.dispose();
}
}
}
/** {@collect.stats}
* Paints this component's children.
* If <code>shouldUseBuffer</code> is true,
* no component ancestor has a buffer and
* the component children can use a buffer if they have one.
* Otherwise, one ancestor has a buffer currently in use and children
* should not use a buffer to paint.
* @param g the <code>Graphics</code> context in which to paint
* @see #paint
* @see java.awt.Container#paint
*/
protected void paintChildren(Graphics g) {
boolean isJComponent;
Graphics sg = g;
synchronized(getTreeLock()) {
int i = getComponentCount() - 1;
if (i < 0) {
return;
}
// If we are only to paint to a specific child, determine
// its index.
if (paintingChild != null &&
(paintingChild instanceof JComponent) &&
((JComponent)paintingChild).isOpaque()) {
for (; i >= 0; i--) {
if (getComponent(i) == paintingChild){
break;
}
}
}
Rectangle tmpRect = fetchRectangle();
boolean checkSiblings = (!isOptimizedDrawingEnabled() &&
checkIfChildObscuredBySibling());
Rectangle clipBounds = null;
if (checkSiblings) {
clipBounds = sg.getClipBounds();
if (clipBounds == null) {
clipBounds = new Rectangle(0, 0, getWidth(),
getHeight());
}
}
boolean printing = getFlag(IS_PRINTING);
for (; i >= 0 ; i--) {
Component comp = getComponent(i);
isJComponent = (comp instanceof JComponent);
if (comp != null &&
(isJComponent || isLightweightComponent(comp)) &&
(comp.isVisible() == true)) {
Rectangle cr;
cr = comp.getBounds(tmpRect);
boolean hitClip = g.hitClip(cr.x, cr.y, cr.width,
cr.height);
if (hitClip) {
if (checkSiblings && i > 0) {
int x = cr.x;
int y = cr.y;
int width = cr.width;
int height = cr.height;
SwingUtilities.computeIntersection
(clipBounds.x, clipBounds.y,
clipBounds.width, clipBounds.height, cr);
if(getObscuredState(i, cr.x, cr.y, cr.width,
cr.height) == COMPLETELY_OBSCURED) {
continue;
}
cr.x = x;
cr.y = y;
cr.width = width;
cr.height = height;
}
Graphics cg = sg.create(cr.x, cr.y, cr.width,
cr.height);
cg.setColor(comp.getForeground());
cg.setFont(comp.getFont());
boolean shouldSetFlagBack = false;
try {
if(isJComponent) {
if(getFlag(ANCESTOR_USING_BUFFER)) {
((JComponent)comp).setFlag(
ANCESTOR_USING_BUFFER,true);
shouldSetFlagBack = true;
}
if(getFlag(IS_PAINTING_TILE)) {
((JComponent)comp).setFlag(
IS_PAINTING_TILE,true);
shouldSetFlagBack = true;
}
if(!printing) {
((JComponent)comp).paint(cg);
}
else {
if (!getFlag(IS_PRINTING_ALL)) {
comp.print(cg);
}
else {
comp.printAll(cg);
}
}
} else {
if (!printing) {
comp.paint(cg);
}
else {
if (!getFlag(IS_PRINTING_ALL)) {
comp.print(cg);
}
else {
comp.printAll(cg);
}
}
}
} finally {
cg.dispose();
if(shouldSetFlagBack) {
((JComponent)comp).setFlag(
ANCESTOR_USING_BUFFER,false);
((JComponent)comp).setFlag(
IS_PAINTING_TILE,false);
}
}
}
}
}
recycleRectangle(tmpRect);
}
}
/** {@collect.stats}
* Paints the component's border.
* <p>
* If you override this in a subclass you should not make permanent
* changes to the passed in <code>Graphics</code>. For example, you
* should not alter the clip <code>Rectangle</code> or modify the
* transform. If you need to do these operations you may find it
* easier to create a new <code>Graphics</code> from the passed in
* <code>Graphics</code> and manipulate it.
*
* @param g the <code>Graphics</code> context in which to paint
*
* @see #paint
* @see #setBorder
*/
protected void paintBorder(Graphics g) {
Border border = getBorder();
if (border != null) {
border.paintBorder(this, g, 0, 0, getWidth(), getHeight());
}
}
/** {@collect.stats}
* Calls <code>paint</code>. Doesn't clear the background but see
* <code>ComponentUI.update</code>, which is called by
* <code>paintComponent</code>.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #paint
* @see #paintComponent
* @see javax.swing.plaf.ComponentUI
*/
public void update(Graphics g) {
paint(g);
}
/** {@collect.stats}
* Invoked by Swing to draw components.
* Applications should not invoke <code>paint</code> directly,
* but should instead use the <code>repaint</code> method to
* schedule the component for redrawing.
* <p>
* This method actually delegates the work of painting to three
* protected methods: <code>paintComponent</code>,
* <code>paintBorder</code>,
* and <code>paintChildren</code>. They're called in the order
* listed to ensure that children appear on top of component itself.
* Generally speaking, the component and its children should not
* paint in the insets area allocated to the border. Subclasses can
* just override this method, as always. A subclass that just
* wants to specialize the UI (look and feel) delegate's
* <code>paint</code> method should just override
* <code>paintComponent</code>.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #paintComponent
* @see #paintBorder
* @see #paintChildren
* @see #getComponentGraphics
* @see #repaint
*/
public void paint(Graphics g) {
boolean shouldClearPaintFlags = false;
if ((getWidth() <= 0) || (getHeight() <= 0)) {
return;
}
Graphics componentGraphics = getComponentGraphics(g);
Graphics co = componentGraphics.create();
try {
RepaintManager repaintManager = RepaintManager.currentManager(this);
Rectangle clipRect = co.getClipBounds();
int clipX;
int clipY;
int clipW;
int clipH;
if (clipRect == null) {
clipX = clipY = 0;
clipW = getWidth();
clipH = getHeight();
}
else {
clipX = clipRect.x;
clipY = clipRect.y;
clipW = clipRect.width;
clipH = clipRect.height;
}
if(clipW > getWidth()) {
clipW = getWidth();
}
if(clipH > getHeight()) {
clipH = getHeight();
}
if(getParent() != null && !(getParent() instanceof JComponent)) {
adjustPaintFlags();
shouldClearPaintFlags = true;
}
int bw,bh;
boolean printing = getFlag(IS_PRINTING);
if(!printing && repaintManager.isDoubleBufferingEnabled() &&
!getFlag(ANCESTOR_USING_BUFFER) && isDoubleBuffered()) {
repaintManager.beginPaint();
try {
repaintManager.paint(this, this, co, clipX, clipY, clipW,
clipH);
} finally {
repaintManager.endPaint();
}
}
else {
// Will ocassionaly happen in 1.2, especially when printing.
if (clipRect == null) {
co.setClip(clipX, clipY, clipW, clipH);
}
if (!rectangleIsObscured(clipX,clipY,clipW,clipH)) {
if (!printing) {
paintComponent(co);
paintBorder(co);
}
else {
printComponent(co);
printBorder(co);
}
}
if (!printing) {
paintChildren(co);
}
else {
printChildren(co);
}
}
} finally {
co.dispose();
if(shouldClearPaintFlags) {
setFlag(ANCESTOR_USING_BUFFER,false);
setFlag(IS_PAINTING_TILE,false);
setFlag(IS_PRINTING,false);
setFlag(IS_PRINTING_ALL,false);
}
}
}
// paint forcing use of the double buffer. This is used for historical
// reasons: JViewport, when scrolling, previously directly invoked paint
// while turning off double buffering at the RepaintManager level, this
// codes simulates that.
void paintForceDoubleBuffered(Graphics g) {
RepaintManager rm = RepaintManager.currentManager(this);
Rectangle clip = g.getClipBounds();
rm.beginPaint();
setFlag(IS_REPAINTING, true);
try {
rm.paint(this, this, g, clip.x, clip.y, clip.width, clip.height);
} finally {
rm.endPaint();
setFlag(IS_REPAINTING, false);
}
}
/** {@collect.stats}
* Returns true if this component, or any of its ancestors, are in
* the processing of painting.
*/
boolean isPainting() {
Container component = this;
while (component != null) {
if (component instanceof JComponent &&
((JComponent)component).getFlag(ANCESTOR_USING_BUFFER)) {
return true;
}
component = component.getParent();
}
return false;
}
private void adjustPaintFlags() {
JComponent jparent = null;
Container parent;
for(parent = getParent() ; parent != null ; parent =
parent.getParent()) {
if(parent instanceof JComponent) {
jparent = (JComponent) parent;
if(jparent.getFlag(ANCESTOR_USING_BUFFER))
setFlag(ANCESTOR_USING_BUFFER, true);
if(jparent.getFlag(IS_PAINTING_TILE))
setFlag(IS_PAINTING_TILE, true);
if(jparent.getFlag(IS_PRINTING))
setFlag(IS_PRINTING, true);
if(jparent.getFlag(IS_PRINTING_ALL))
setFlag(IS_PRINTING_ALL, true);
break;
}
}
}
/** {@collect.stats}
* Invoke this method to print the component. This method invokes
* <code>print</code> on the component.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #print
* @see #printComponent
* @see #printBorder
* @see #printChildren
*/
public void printAll(Graphics g) {
setFlag(IS_PRINTING_ALL, true);
try {
print(g);
}
finally {
setFlag(IS_PRINTING_ALL, false);
}
}
/** {@collect.stats}
* Invoke this method to print the component to the specified
* <code>Graphics</code>. This method will result in invocations
* of <code>printComponent</code>, <code>printBorder</code> and
* <code>printChildren</code>. It is recommended that you override
* one of the previously mentioned methods rather than this one if
* your intention is to customize the way printing looks. However,
* it can be useful to override this method should you want to prepare
* state before invoking the superclass behavior. As an example,
* if you wanted to change the component's background color before
* printing, you could do the following:
* <pre>
* public void print(Graphics g) {
* Color orig = getBackground();
* setBackground(Color.WHITE);
*
* // wrap in try/finally so that we always restore the state
* try {
* super.print(g);
* } finally {
* setBackground(orig);
* }
* }
* </pre>
* <p>
* Alternatively, or for components that delegate painting to other objects,
* you can query during painting whether or not the component is in the
* midst of a print operation. The <code>isPaintingForPrint</code> method provides
* this ability and its return value will be changed by this method: to
* <code>true</code> immediately before rendering and to <code>false</code>
* immediately after. With each change a property change event is fired on
* this component with the name <code>"paintingForPrint"</code>.
* <p>
* This method sets the component's state such that the double buffer
* will not be used: painting will be done directly on the passed in
* <code>Graphics</code>.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #printComponent
* @see #printBorder
* @see #printChildren
* @see #isPaintingForPrint
*/
public void print(Graphics g) {
setFlag(IS_PRINTING, true);
firePropertyChange("paintingForPrint", false, true);
try {
paint(g);
}
finally {
setFlag(IS_PRINTING, false);
firePropertyChange("paintingForPrint", true, false);
}
}
/** {@collect.stats}
* This is invoked during a printing operation. This is implemented to
* invoke <code>paintComponent</code> on the component. Override this
* if you wish to add special painting behavior when printing.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #print
* @since 1.3
*/
protected void printComponent(Graphics g) {
paintComponent(g);
}
/** {@collect.stats}
* Prints this component's children. This is implemented to invoke
* <code>paintChildren</code> on the component. Override this if you
* wish to print the children differently than painting.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #print
* @since 1.3
*/
protected void printChildren(Graphics g) {
paintChildren(g);
}
/** {@collect.stats}
* Prints the component's border. This is implemented to invoke
* <code>paintBorder</code> on the component. Override this if you
* wish to print the border differently that it is painted.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #print
* @since 1.3
*/
protected void printBorder(Graphics g) {
paintBorder(g);
}
/** {@collect.stats}
* Returns true if the component is currently painting a tile.
* If this method returns true, paint will be called again for another
* tile. This method returns false if you are not painting a tile or
* if the last tile is painted.
* Use this method to keep some state you might need between tiles.
*
* @return true if the component is currently painting a tile,
* false otherwise
*/
public boolean isPaintingTile() {
return getFlag(IS_PAINTING_TILE);
}
/** {@collect.stats}
* Returns <code>true</code> if the current painting operation on this
* component is part of a <code>print</code> operation. This method is
* useful when you want to customize what you print versus what you show
* on the screen.
* <p>
* You can detect changes in the value of this property by listening for
* property change events on this component with name
* <code>"paintingForPrint"</code>.
* <p>
* Note: This method provides complimentary functionality to that provided
* by other high level Swing printing APIs. However, it deals strictly with
* painting and should not be confused as providing information on higher
* level print processes. For example, a {@link javax.swing.JTable#print()}
* operation doesn't necessarily result in a continuous rendering of the
* full component, and the return value of this method can change multiple
* times during that operation. It is even possible for the component to be
* painted to the screen while the printing process is ongoing. In such a
* case, the return value of this method is <code>true</code> when, and only
* when, the table is being painted as part of the printing process.
*
* @return true if the current painting operation on this component
* is part of a print operation
* @see #print
* @since 1.6
*/
public final boolean isPaintingForPrint() {
return getFlag(IS_PRINTING);
}
/** {@collect.stats}
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* Changes this <code>JComponent</code>'s focus traversal keys to
* CTRL+TAB and CTRL+SHIFT+TAB. Also prevents
* <code>SortingFocusTraversalPolicy</code> from considering descendants
* of this JComponent when computing a focus traversal cycle.
*
* @see java.awt.Component#setFocusTraversalKeys
* @see SortingFocusTraversalPolicy
* @deprecated As of 1.4, replaced by
* <code>Component.setFocusTraversalKeys(int, Set)</code> and
* <code>Container.setFocusCycleRoot(boolean)</code>.
*/
@Deprecated
public boolean isManagingFocus() {
return false;
}
private void registerNextFocusableComponent() {
registerNextFocusableComponent(getNextFocusableComponent());
}
private void registerNextFocusableComponent(Component
nextFocusableComponent) {
if (nextFocusableComponent == null) {
return;
}
Container nearestRoot =
(isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
FocusTraversalPolicy policy = nearestRoot.getFocusTraversalPolicy();
if (!(policy instanceof LegacyGlueFocusTraversalPolicy)) {
policy = new LegacyGlueFocusTraversalPolicy(policy);
nearestRoot.setFocusTraversalPolicy(policy);
}
((LegacyGlueFocusTraversalPolicy)policy).
setNextFocusableComponent(this, nextFocusableComponent);
}
private void deregisterNextFocusableComponent() {
Component nextFocusableComponent = getNextFocusableComponent();
if (nextFocusableComponent == null) {
return;
}
Container nearestRoot =
(isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
if (nearestRoot == null) {
return;
}
FocusTraversalPolicy policy = nearestRoot.getFocusTraversalPolicy();
if (policy instanceof LegacyGlueFocusTraversalPolicy) {
((LegacyGlueFocusTraversalPolicy)policy).
unsetNextFocusableComponent(this, nextFocusableComponent);
}
}
/** {@collect.stats}
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* Overrides the default <code>FocusTraversalPolicy</code> for this
* <code>JComponent</code>'s focus traversal cycle by unconditionally
* setting the specified <code>Component</code> as the next
* <code>Component</code> in the cycle, and this <code>JComponent</code>
* as the specified <code>Component</code>'s previous
* <code>Component</code> in the cycle.
*
* @param aComponent the <code>Component</code> that should follow this
* <code>JComponent</code> in the focus traversal cycle
*
* @see #getNextFocusableComponent
* @see java.awt.FocusTraversalPolicy
* @deprecated As of 1.4, replaced by <code>FocusTraversalPolicy</code>
*/
@Deprecated
public void setNextFocusableComponent(Component aComponent) {
boolean displayable = isDisplayable();
if (displayable) {
deregisterNextFocusableComponent();
}
putClientProperty(NEXT_FOCUS, aComponent);
if (displayable) {
registerNextFocusableComponent(aComponent);
}
}
/** {@collect.stats}
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* Returns the <code>Component</code> set by a prior call to
* <code>setNextFocusableComponent(Component)</code> on this
* <code>JComponent</code>.
*
* @return the <code>Component</code> that will follow this
* <code>JComponent</code> in the focus traversal cycle, or
* <code>null</code> if none has been explicitly specified
*
* @see #setNextFocusableComponent
* @deprecated As of 1.4, replaced by <code>FocusTraversalPolicy</code>.
*/
@Deprecated
public Component getNextFocusableComponent() {
return (Component)getClientProperty(NEXT_FOCUS);
}
/** {@collect.stats}
* Provides a hint as to whether or not this <code>JComponent</code>
* should get focus. This is only a hint, and it is up to consumers that
* are requesting focus to honor this property. This is typically honored
* for mouse operations, but not keyboard operations. For example, look
* and feels could verify this property is true before requesting focus
* during a mouse operation. This would often times be used if you did
* not want a mouse press on a <code>JComponent</code> to steal focus,
* but did want the <code>JComponent</code> to be traversable via the
* keyboard. If you do not want this <code>JComponent</code> focusable at
* all, use the <code>setFocusable</code> method instead.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>,
* for more information.
*
* @param requestFocusEnabled indicates whether you want this
* <code>JComponent</code> to be focusable or not
* @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
* @see java.awt.Component#setFocusable
*/
public void setRequestFocusEnabled(boolean requestFocusEnabled) {
setFlag(REQUEST_FOCUS_DISABLED, !requestFocusEnabled);
}
/** {@collect.stats}
* Returns <code>true</code> if this <code>JComponent</code> should
* get focus; otherwise returns <code>false</code>.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>,
* for more information.
*
* @return <code>true</code> if this component should get focus,
* otherwise returns <code>false</code>
* @see #setRequestFocusEnabled
* @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus
* Specification</a>
* @see java.awt.Component#isFocusable
*/
public boolean isRequestFocusEnabled() {
return !getFlag(REQUEST_FOCUS_DISABLED);
}
/** {@collect.stats}
* Requests that this <code>Component</code> gets the input focus.
* Refer to {@link java.awt.Component#requestFocus()
* Component.requestFocus()} for a complete description of
* this method.
* <p>
* Note that the use of this method is discouraged because
* its behavior is platform dependent. Instead we recommend the
* use of {@link #requestFocusInWindow() requestFocusInWindow()}.
* If you would like more information on focus, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
*
* @see java.awt.Component#requestFocusInWindow()
* @see java.awt.Component#requestFocusInWindow(boolean)
* @since 1.4
*/
public void requestFocus() {
super.requestFocus();
}
/** {@collect.stats}
* Requests that this <code>Component</code> gets the input focus.
* Refer to {@link java.awt.Component#requestFocus(boolean)
* Component.requestFocus(boolean)} for a complete description of
* this method.
* <p>
* Note that the use of this method is discouraged because
* its behavior is platform dependent. Instead we recommend the
* use of {@link #requestFocusInWindow(boolean)
* requestFocusInWindow(boolean)}.
* If you would like more information on focus, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
*
* @param temporary boolean indicating if the focus change is temporary
* @return <code>false</code> if the focus change request is guaranteed to
* fail; <code>true</code> if it is likely to succeed
* @see java.awt.Component#requestFocusInWindow()
* @see java.awt.Component#requestFocusInWindow(boolean)
* @since 1.4
*/
public boolean requestFocus(boolean temporary) {
return super.requestFocus(temporary);
}
/** {@collect.stats}
* Requests that this <code>Component</code> gets the input focus.
* Refer to {@link java.awt.Component#requestFocusInWindow()
* Component.requestFocusInWindow()} for a complete description of
* this method.
* <p>
* If you would like more information on focus, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
*
* @return <code>false</code> if the focus change request is guaranteed to
* fail; <code>true</code> if it is likely to succeed
* @see java.awt.Component#requestFocusInWindow()
* @see java.awt.Component#requestFocusInWindow(boolean)
* @since 1.4
*/
public boolean requestFocusInWindow() {
return super.requestFocusInWindow();
}
/** {@collect.stats}
* Requests that this <code>Component</code> gets the input focus.
* Refer to {@link java.awt.Component#requestFocusInWindow(boolean)
* Component.requestFocusInWindow(boolean)} for a complete description of
* this method.
* <p>
* If you would like more information on focus, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
*
* @param temporary boolean indicating if the focus change is temporary
* @return <code>false</code> if the focus change request is guaranteed to
* fail; <code>true</code> if it is likely to succeed
* @see java.awt.Component#requestFocusInWindow()
* @see java.awt.Component#requestFocusInWindow(boolean)
* @since 1.4
*/
protected boolean requestFocusInWindow(boolean temporary) {
return super.requestFocusInWindow(temporary);
}
/** {@collect.stats}
* Requests that this Component get the input focus, and that this
* Component's top-level ancestor become the focused Window. This component
* must be displayable, visible, and focusable for the request to be
* granted.
* <p>
* This method is intended for use by focus implementations. Client code
* should not use this method; instead, it should use
* <code>requestFocusInWindow()</code>.
*
* @see #requestFocusInWindow()
*/
public void grabFocus() {
requestFocus();
}
/** {@collect.stats}
* Sets the value to indicate whether input verifier for the
* current focus owner will be called before this component requests
* focus. The default is true. Set to false on components such as a
* Cancel button or a scrollbar, which should activate even if the
* input in the current focus owner is not "passed" by the input
* verifier for that component.
*
* @param verifyInputWhenFocusTarget value for the
* <code>verifyInputWhenFocusTarget</code> property
* @see InputVerifier
* @see #setInputVerifier
* @see #getInputVerifier
* @see #getVerifyInputWhenFocusTarget
*
* @since 1.3
* @beaninfo
* bound: true
* description: Whether the Component verifies input before accepting
* focus.
*/
public void setVerifyInputWhenFocusTarget(boolean
verifyInputWhenFocusTarget) {
boolean oldVerifyInputWhenFocusTarget =
this.verifyInputWhenFocusTarget;
this.verifyInputWhenFocusTarget = verifyInputWhenFocusTarget;
firePropertyChange("verifyInputWhenFocusTarget",
oldVerifyInputWhenFocusTarget,
verifyInputWhenFocusTarget);
}
/** {@collect.stats}
* Returns the value that indicates whether the input verifier for the
* current focus owner will be called before this component requests
* focus.
*
* @return value of the <code>verifyInputWhenFocusTarget</code> property
*
* @see InputVerifier
* @see #setInputVerifier
* @see #getInputVerifier
* @see #setVerifyInputWhenFocusTarget
*
* @since 1.3
*/
public boolean getVerifyInputWhenFocusTarget() {
return verifyInputWhenFocusTarget;
}
/** {@collect.stats}
* Gets the <code>FontMetrics</code> for the specified <code>Font</code>.
*
* @param font the font for which font metrics is to be
* obtained
* @return the font metrics for <code>font</code>
* @throws NullPointerException if <code>font</code> is null
* @since 1.5
*/
public FontMetrics getFontMetrics(Font font) {
return SwingUtilities2.getFontMetrics(this, font);
}
/** {@collect.stats}
* Sets the preferred size of this component.
* If <code>preferredSize</code> is <code>null</code>, the UI will
* be asked for the preferred size.
* @beaninfo
* preferred: true
* bound: true
* description: The preferred size of the component.
*/
public void setPreferredSize(Dimension preferredSize) {
super.setPreferredSize(preferredSize);
}
/** {@collect.stats}
* If the <code>preferredSize</code> has been set to a
* non-<code>null</code> value just returns it.
* If the UI delegate's <code>getPreferredSize</code>
* method returns a non <code>null</code> value then return that;
* otherwise defer to the component's layout manager.
*
* @return the value of the <code>preferredSize</code> property
* @see #setPreferredSize
* @see ComponentUI
*/
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
Dimension size = null;
if (ui != null) {
size = ui.getPreferredSize(this);
}
return (size != null) ? size : super.getPreferredSize();
}
/** {@collect.stats}
* Sets the maximum size of this component to a constant
* value. Subsequent calls to <code>getMaximumSize</code> will always
* return this value; the component's UI will not be asked
* to compute it. Setting the maximum size to <code>null</code>
* restores the default behavior.
*
* @param maximumSize a <code>Dimension</code> containing the
* desired maximum allowable size
* @see #getMaximumSize
* @beaninfo
* bound: true
* description: The maximum size of the component.
*/
public void setMaximumSize(Dimension maximumSize) {
super.setMaximumSize(maximumSize);
}
/** {@collect.stats}
* If the maximum size has been set to a non-<code>null</code> value
* just returns it. If the UI delegate's <code>getMaximumSize</code>
* method returns a non-<code>null</code> value then return that;
* otherwise defer to the component's layout manager.
*
* @return the value of the <code>maximumSize</code> property
* @see #setMaximumSize
* @see ComponentUI
*/
public Dimension getMaximumSize() {
if (isMaximumSizeSet()) {
return super.getMaximumSize();
}
Dimension size = null;
if (ui != null) {
size = ui.getMaximumSize(this);
}
return (size != null) ? size : super.getMaximumSize();
}
/** {@collect.stats}
* Sets the minimum size of this component to a constant
* value. Subsequent calls to <code>getMinimumSize</code> will always
* return this value; the component's UI will not be asked
* to compute it. Setting the minimum size to <code>null</code>
* restores the default behavior.
*
* @param minimumSize the new minimum size of this component
* @see #getMinimumSize
* @beaninfo
* bound: true
* description: The minimum size of the component.
*/
public void setMinimumSize(Dimension minimumSize) {
super.setMinimumSize(minimumSize);
}
/** {@collect.stats}
* If the minimum size has been set to a non-<code>null</code> value
* just returns it. If the UI delegate's <code>getMinimumSize</code>
* method returns a non-<code>null</code> value then return that; otherwise
* defer to the component's layout manager.
*
* @return the value of the <code>minimumSize</code> property
* @see #setMinimumSize
* @see ComponentUI
*/
public Dimension getMinimumSize() {
if (isMinimumSizeSet()) {
return super.getMinimumSize();
}
Dimension size = null;
if (ui != null) {
size = ui.getMinimumSize(this);
}
return (size != null) ? size : super.getMinimumSize();
}
/** {@collect.stats}
* Gives the UI delegate an opportunity to define the precise
* shape of this component for the sake of mouse processing.
*
* @return true if this component logically contains x,y
* @see java.awt.Component#contains(int, int)
* @see ComponentUI
*/
public boolean contains(int x, int y) {
return (ui != null) ? ui.contains(this, x, y) : super.contains(x, y);
}
/** {@collect.stats}
* Sets the border of this component. The <code>Border</code> object is
* responsible for defining the insets for the component
* (overriding any insets set directly on the component) and
* for optionally rendering any border decorations within the
* bounds of those insets. Borders should be used (rather
* than insets) for creating both decorative and non-decorative
* (such as margins and padding) regions for a swing component.
* Compound borders can be used to nest multiple borders within a
* single component.
* <p>
* Although technically you can set the border on any object
* that inherits from <code>JComponent</code>, the look and
* feel implementation of many standard Swing components
* doesn't work well with user-set borders. In general,
* when you want to set a border on a standard Swing
* component other than <code>JPanel</code> or <code>JLabel</code>,
* we recommend that you put the component in a <code>JPanel</code>
* and set the border on the <code>JPanel</code>.
* <p>
* This is a bound property.
*
* @param border the border to be rendered for this component
* @see Border
* @see CompoundBorder
* @beaninfo
* bound: true
* preferred: true
* attribute: visualUpdate true
* description: The component's border.
*/
public void setBorder(Border border) {
Border oldBorder = this.border;
this.border = border;
firePropertyChange("border", oldBorder, border);
if (border != oldBorder) {
if (border == null || oldBorder == null ||
!(border.getBorderInsets(this).equals(oldBorder.getBorderInsets(this)))) {
revalidate();
}
repaint();
}
}
/** {@collect.stats}
* Returns the border of this component or <code>null</code> if no
* border is currently set.
*
* @return the border object for this component
* @see #setBorder
*/
public Border getBorder() {
return border;
}
/** {@collect.stats}
* If a border has been set on this component, returns the
* border's insets; otherwise calls <code>super.getInsets</code>.
*
* @return the value of the insets property
* @see #setBorder
*/
public Insets getInsets() {
if (border != null) {
return border.getBorderInsets(this);
}
return super.getInsets();
}
/** {@collect.stats}
* Returns an <code>Insets</code> object containing this component's inset
* values. The passed-in <code>Insets</code> object will be reused
* if possible.
* Calling methods cannot assume that the same object will be returned,
* however. All existing values within this object are overwritten.
* If <code>insets</code> is null, this will allocate a new one.
*
* @param insets the <code>Insets</code> object, which can be reused
* @return the <code>Insets</code> object
* @see #getInsets
* @beaninfo
* expert: true
*/
public Insets getInsets(Insets insets) {
if (insets == null) {
insets = new Insets(0, 0, 0, 0);
}
if (border != null) {
if (border instanceof AbstractBorder) {
return ((AbstractBorder)border).getBorderInsets(this, insets);
} else {
// Can't reuse border insets because the Border interface
// can't be enhanced.
return border.getBorderInsets(this);
}
} else {
// super.getInsets() always returns an Insets object with
// all of its value zeroed. No need for a new object here.
insets.left = insets.top = insets.right = insets.bottom = 0;
return insets;
}
}
/** {@collect.stats}
* Overrides <code>Container.getAlignmentY</code> to return
* the horizontal alignment.
*
* @return the value of the <code>alignmentY</code> property
* @see #setAlignmentY
* @see java.awt.Component#getAlignmentY
*/
public float getAlignmentY() {
if (isAlignmentYSet) {
return alignmentY;
}
return super.getAlignmentY();
}
/** {@collect.stats}
* Sets the the horizontal alignment.
*
* @param alignmentY the new horizontal alignment
* @see #getAlignmentY
* @beaninfo
* description: The preferred vertical alignment of the component.
*/
public void setAlignmentY(float alignmentY) {
this.alignmentY = alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY;
isAlignmentYSet = true;
}
/** {@collect.stats}
* Overrides <code>Container.getAlignmentX</code> to return
* the vertical alignment.
*
* @return the value of the <code>alignmentX</code> property
* @see #setAlignmentX
* @see java.awt.Component#getAlignmentX
*/
public float getAlignmentX() {
if (isAlignmentXSet) {
return alignmentX;
}
return super.getAlignmentX();
}
/** {@collect.stats}
* Sets the the vertical alignment.
*
* @param alignmentX the new vertical alignment
* @see #getAlignmentX
* @beaninfo
* description: The preferred horizontal alignment of the component.
*/
public void setAlignmentX(float alignmentX) {
this.alignmentX = alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX;
isAlignmentXSet = true;
}
/** {@collect.stats}
* Sets the input verifier for this component.
*
* @param inputVerifier the new input verifier
* @since 1.3
* @see InputVerifier
* @beaninfo
* bound: true
* description: The component's input verifier.
*/
public void setInputVerifier(InputVerifier inputVerifier) {
InputVerifier oldInputVerifier = (InputVerifier)getClientProperty(
JComponent_INPUT_VERIFIER);
putClientProperty(JComponent_INPUT_VERIFIER, inputVerifier);
firePropertyChange("inputVerifier", oldInputVerifier, inputVerifier);
}
/** {@collect.stats}
* Returns the input verifier for this component.
*
* @return the <code>inputVerifier</code> property
* @since 1.3
* @see InputVerifier
*/
public InputVerifier getInputVerifier() {
return (InputVerifier)getClientProperty(JComponent_INPUT_VERIFIER);
}
/** {@collect.stats}
* Returns this component's graphics context, which lets you draw
* on a component. Use this method to get a <code>Graphics</code> object and
* then invoke operations on that object to draw on the component.
* @return this components graphics context
*/
public Graphics getGraphics() {
if (DEBUG_GRAPHICS_LOADED && shouldDebugGraphics() != 0) {
DebugGraphics graphics = new DebugGraphics(super.getGraphics(),
this);
return graphics;
}
return super.getGraphics();
}
/** {@collect.stats} Enables or disables diagnostic information about every graphics
* operation performed within the component or one of its children.
*
* @param debugOptions determines how the component should display
* the information; one of the following options:
* <ul>
* <li>DebugGraphics.LOG_OPTION - causes a text message to be printed.
* <li>DebugGraphics.FLASH_OPTION - causes the drawing to flash several
* times.
* <li>DebugGraphics.BUFFERED_OPTION - creates an
* <code>ExternalWindow</code> that displays the operations
* performed on the View's offscreen buffer.
* <li>DebugGraphics.NONE_OPTION disables debugging.
* <li>A value of 0 causes no changes to the debugging options.
* </ul>
* <code>debugOptions</code> is bitwise OR'd into the current value
*
* @beaninfo
* preferred: true
* enum: NONE_OPTION DebugGraphics.NONE_OPTION
* LOG_OPTION DebugGraphics.LOG_OPTION
* FLASH_OPTION DebugGraphics.FLASH_OPTION
* BUFFERED_OPTION DebugGraphics.BUFFERED_OPTION
* description: Diagnostic options for graphics operations.
*/
public void setDebugGraphicsOptions(int debugOptions) {
DebugGraphics.setDebugOptions(this, debugOptions);
}
/** {@collect.stats} Returns the state of graphics debugging.
*
* @return a bitwise OR'd flag of zero or more of the following options:
* <ul>
* <li>DebugGraphics.LOG_OPTION - causes a text message to be printed.
* <li>DebugGraphics.FLASH_OPTION - causes the drawing to flash several
* times.
* <li>DebugGraphics.BUFFERED_OPTION - creates an
* <code>ExternalWindow</code> that displays the operations
* performed on the View's offscreen buffer.
* <li>DebugGraphics.NONE_OPTION disables debugging.
* <li>A value of 0 causes no changes to the debugging options.
* </ul>
* @see #setDebugGraphicsOptions
*/
public int getDebugGraphicsOptions() {
return DebugGraphics.getDebugOptions(this);
}
/** {@collect.stats}
* Returns true if debug information is enabled for this
* <code>JComponent</code> or one of its parents.
*/
int shouldDebugGraphics() {
return DebugGraphics.shouldComponentDebug(this);
}
/** {@collect.stats}
* This method is now obsolete, please use a combination of
* <code>getActionMap()</code> and <code>getInputMap()</code> for
* similiar behavior. For example, to bind the <code>KeyStroke</code>
* <code>aKeyStroke</code> to the <code>Action</code> <code>anAction</code>
* now use:
* <pre>
* component.getInputMap().put(aKeyStroke, aCommand);
* component.getActionMap().put(aCommmand, anAction);
* </pre>
* The above assumes you want the binding to be applicable for
* <code>WHEN_FOCUSED</code>. To register bindings for other focus
* states use the <code>getInputMap</code> method that takes an integer.
* <p>
* Register a new keyboard action.
* <code>anAction</code> will be invoked if a key event matching
* <code>aKeyStroke</code> occurs and <code>aCondition</code> is verified.
* The <code>KeyStroke</code> object defines a
* particular combination of a keyboard key and one or more modifiers
* (alt, shift, ctrl, meta).
* <p>
* The <code>aCommand</code> will be set in the delivered event if
* specified.
* <p>
* The <code>aCondition</code> can be one of:
* <blockquote>
* <DL>
* <DT>WHEN_FOCUSED
* <DD>The action will be invoked only when the keystroke occurs
* while the component has the focus.
* <DT>WHEN_IN_FOCUSED_WINDOW
* <DD>The action will be invoked when the keystroke occurs while
* the component has the focus or if the component is in the
* window that has the focus. Note that the component need not
* be an immediate descendent of the window -- it can be
* anywhere in the window's containment hierarchy. In other
* words, whenever <em>any</em> component in the window has the focus,
* the action registered with this component is invoked.
* <DT>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
* <DD>The action will be invoked when the keystroke occurs while the
* component has the focus or if the component is an ancestor of
* the component that has the focus.
* </DL>
* </blockquote>
* <p>
* The combination of keystrokes and conditions lets you define high
* level (semantic) action events for a specified keystroke+modifier
* combination (using the KeyStroke class) and direct to a parent or
* child of a component that has the focus, or to the component itself.
* In other words, in any hierarchical structure of components, an
* arbitrary key-combination can be immediately directed to the
* appropriate component in the hierarchy, and cause a specific method
* to be invoked (usually by way of adapter objects).
* <p>
* If an action has already been registered for the receiving
* container, with the same charCode and the same modifiers,
* <code>anAction</code> will replace the action.
*
* @param anAction the <code>Action</code> to be registered
* @param aCommand the command to be set in the delivered event
* @param aKeyStroke the <code>KeyStroke</code> to bind to the action
* @param aCondition the condition that needs to be met, see above
* @see KeyStroke
*/
public void registerKeyboardAction(ActionListener anAction,String aCommand,KeyStroke aKeyStroke,int aCondition) {
InputMap inputMap = getInputMap(aCondition, true);
if (inputMap != null) {
ActionMap actionMap = getActionMap(true);
ActionStandin action = new ActionStandin(anAction, aCommand);
inputMap.put(aKeyStroke, action);
if (actionMap != null) {
actionMap.put(action, action);
}
}
}
/** {@collect.stats}
* Registers any bound <code>WHEN_IN_FOCUSED_WINDOW</code> actions with
* the <code>KeyboardManager</code>. If <code>onlyIfNew</code>
* is true only actions that haven't been registered are pushed
* to the <code>KeyboardManager</code>;
* otherwise all actions are pushed to the <code>KeyboardManager</code>.
*
* @param onlyIfNew if true, only actions that haven't been registered
* are pushed to the <code>KeyboardManager</code>
*/
private void registerWithKeyboardManager(boolean onlyIfNew) {
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
KeyStroke[] strokes;
Hashtable registered = (Hashtable)getClientProperty
(WHEN_IN_FOCUSED_WINDOW_BINDINGS);
if (inputMap != null) {
// Push any new KeyStrokes to the KeyboardManager.
strokes = inputMap.allKeys();
if (strokes != null) {
for (int counter = strokes.length - 1; counter >= 0;
counter--) {
if (!onlyIfNew || registered == null ||
registered.get(strokes[counter]) == null) {
registerWithKeyboardManager(strokes[counter]);
}
if (registered != null) {
registered.remove(strokes[counter]);
}
}
}
}
else {
strokes = null;
}
// Remove any old ones.
if (registered != null && registered.size() > 0) {
Enumeration keys = registered.keys();
while (keys.hasMoreElements()) {
KeyStroke ks = (KeyStroke)keys.nextElement();
unregisterWithKeyboardManager(ks);
}
registered.clear();
}
// Updated the registered Hashtable.
if (strokes != null && strokes.length > 0) {
if (registered == null) {
registered = new Hashtable(strokes.length);
putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, registered);
}
for (int counter = strokes.length - 1; counter >= 0; counter--) {
registered.put(strokes[counter], strokes[counter]);
}
}
else {
putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, null);
}
}
/** {@collect.stats}
* Unregisters all the previously registered
* <code>WHEN_IN_FOCUSED_WINDOW</code> <code>KeyStroke</code> bindings.
*/
private void unregisterWithKeyboardManager() {
Hashtable registered = (Hashtable)getClientProperty
(WHEN_IN_FOCUSED_WINDOW_BINDINGS);
if (registered != null && registered.size() > 0) {
Enumeration keys = registered.keys();
while (keys.hasMoreElements()) {
KeyStroke ks = (KeyStroke)keys.nextElement();
unregisterWithKeyboardManager(ks);
}
}
putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, null);
}
/** {@collect.stats}
* Invoked from <code>ComponentInputMap</code> when its bindings change.
* If <code>inputMap</code> is the current <code>windowInputMap</code>
* (or a parent of the window <code>InputMap</code>)
* the <code>KeyboardManager</code> is notified of the new bindings.
*
* @param inputMap the map containing the new bindings
*/
void componentInputMapChanged(ComponentInputMap inputMap) {
InputMap km = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
while (km != inputMap && km != null) {
km = (ComponentInputMap)km.getParent();
}
if (km != null) {
registerWithKeyboardManager(false);
}
}
private void registerWithKeyboardManager(KeyStroke aKeyStroke) {
KeyboardManager.getCurrentManager().registerKeyStroke(aKeyStroke,this);
}
private void unregisterWithKeyboardManager(KeyStroke aKeyStroke) {
KeyboardManager.getCurrentManager().unregisterKeyStroke(aKeyStroke,
this);
}
/** {@collect.stats}
* This method is now obsolete, please use a combination of
* <code>getActionMap()</code> and <code>getInputMap()</code> for
* similiar behavior.
*/
public void registerKeyboardAction(ActionListener anAction,KeyStroke aKeyStroke,int aCondition) {
registerKeyboardAction(anAction,null,aKeyStroke,aCondition);
}
/** {@collect.stats}
* This method is now obsolete. To unregister an existing binding
* you can either remove the binding from the
* <code>ActionMap/InputMap</code>, or place a dummy binding the
* <code>InputMap</code>. Removing the binding from the
* <code>InputMap</code> allows bindings in parent <code>InputMap</code>s
* to be active, whereas putting a dummy binding in the
* <code>InputMap</code> effectively disables
* the binding from ever happening.
* <p>
* Unregisters a keyboard action.
* This will remove the binding from the <code>ActionMap</code>
* (if it exists) as well as the <code>InputMap</code>s.
*/
public void unregisterKeyboardAction(KeyStroke aKeyStroke) {
ActionMap am = getActionMap(false);
for (int counter = 0; counter < 3; counter++) {
InputMap km = getInputMap(counter, false);
if (km != null) {
Object actionID = km.get(aKeyStroke);
if (am != null && actionID != null) {
am.remove(actionID);
}
km.remove(aKeyStroke);
}
}
}
/** {@collect.stats}
* Returns the <code>KeyStrokes</code> that will initiate
* registered actions.
*
* @return an array of <code>KeyStroke</code> objects
* @see #registerKeyboardAction
*/
public KeyStroke[] getRegisteredKeyStrokes() {
int[] counts = new int[3];
KeyStroke[][] strokes = new KeyStroke[3][];
for (int counter = 0; counter < 3; counter++) {
InputMap km = getInputMap(counter, false);
strokes[counter] = (km != null) ? km.allKeys() : null;
counts[counter] = (strokes[counter] != null) ?
strokes[counter].length : 0;
}
KeyStroke[] retValue = new KeyStroke[counts[0] + counts[1] +
counts[2]];
for (int counter = 0, last = 0; counter < 3; counter++) {
if (counts[counter] > 0) {
System.arraycopy(strokes[counter], 0, retValue, last,
counts[counter]);
last += counts[counter];
}
}
return retValue;
}
/** {@collect.stats}
* Returns the condition that determines whether a registered action
* occurs in response to the specified keystroke.
* <p>
* For Java 2 platform v1.3, a <code>KeyStroke</code> can be associated
* with more than one condition.
* For example, 'a' could be bound for the two
* conditions <code>WHEN_FOCUSED</code> and
* <code>WHEN_IN_FOCUSED_WINDOW</code> condition.
*
* @return the action-keystroke condition
*/
public int getConditionForKeyStroke(KeyStroke aKeyStroke) {
for (int counter = 0; counter < 3; counter++) {
InputMap inputMap = getInputMap(counter, false);
if (inputMap != null && inputMap.get(aKeyStroke) != null) {
return counter;
}
}
return UNDEFINED_CONDITION;
}
/** {@collect.stats}
* Returns the object that will perform the action registered for a
* given keystroke.
*
* @return the <code>ActionListener</code>
* object invoked when the keystroke occurs
*/
public ActionListener getActionForKeyStroke(KeyStroke aKeyStroke) {
ActionMap am = getActionMap(false);
if (am == null) {
return null;
}
for (int counter = 0; counter < 3; counter++) {
InputMap inputMap = getInputMap(counter, false);
if (inputMap != null) {
Object actionBinding = inputMap.get(aKeyStroke);
if (actionBinding != null) {
Action action = am.get(actionBinding);
if (action instanceof ActionStandin) {
return ((ActionStandin)action).actionListener;
}
return action;
}
}
}
return null;
}
/** {@collect.stats}
* Unregisters all the bindings in the first tier <code>InputMaps</code>
* and <code>ActionMap</code>. This has the effect of removing any
* local bindings, and allowing the bindings defined in parent
* <code>InputMap/ActionMaps</code>
* (the UI is usually defined in the second tier) to persist.
*/
public void resetKeyboardActions() {
// Keys
for (int counter = 0; counter < 3; counter++) {
InputMap inputMap = getInputMap(counter, false);
if (inputMap != null) {
inputMap.clear();
}
}
// Actions
ActionMap am = getActionMap(false);
if (am != null) {
am.clear();
}
}
/** {@collect.stats}
* Sets the <code>InputMap</code> to use under the condition
* <code>condition</code> to
* <code>map</code>. A <code>null</code> value implies you
* do not want any bindings to be used, even from the UI. This will
* not reinstall the UI <code>InputMap</code> (if there was one).
* <code>condition</code> has one of the following values:
* <ul>
* <li><code>WHEN_IN_FOCUSED_WINDOW</code>
* <li><code>WHEN_FOCUSED</code>
* <li><code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code>
* </ul>
* If <code>condition</code> is <code>WHEN_IN_FOCUSED_WINDOW</code>
* and <code>map</code> is not a <code>ComponentInputMap</code>, an
* <code>IllegalArgumentException</code> will be thrown.
* Similarly, if <code>condition</code> is not one of the values
* listed, an <code>IllegalArgumentException</code> will be thrown.
*
* @param condition one of the values listed above
* @param map the <code>InputMap</code> to use for the given condition
* @exception IllegalArgumentException if <code>condition</code> is
* <code>WHEN_IN_FOCUSED_WINDOW</code> and <code>map</code>
* is not an instance of <code>ComponentInputMap</code>; or
* if <code>condition</code> is not one of the legal values
* specified above
* @since 1.3
*/
public final void setInputMap(int condition, InputMap map) {
switch (condition) {
case WHEN_IN_FOCUSED_WINDOW:
if (map != null && !(map instanceof ComponentInputMap)) {
throw new IllegalArgumentException("WHEN_IN_FOCUSED_WINDOW InputMaps must be of type ComponentInputMap");
}
windowInputMap = (ComponentInputMap)map;
setFlag(WIF_INPUTMAP_CREATED, true);
registerWithKeyboardManager(false);
break;
case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
ancestorInputMap = map;
setFlag(ANCESTOR_INPUTMAP_CREATED, true);
break;
case WHEN_FOCUSED:
focusInputMap = map;
setFlag(FOCUS_INPUTMAP_CREATED, true);
break;
default:
throw new IllegalArgumentException("condition must be one of JComponent.WHEN_IN_FOCUSED_WINDOW, JComponent.WHEN_FOCUSED or JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
}
}
/** {@collect.stats}
* Returns the <code>InputMap</code> that is used during
* <code>condition</code>.
*
* @param condition one of WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED,
* WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
* @return the <code>InputMap</code> for the specified
* <code>condition</code>
* @since 1.3
*/
public final InputMap getInputMap(int condition) {
return getInputMap(condition, true);
}
/** {@collect.stats}
* Returns the <code>InputMap</code> that is used when the
* component has focus.
* This is convenience method for <code>getInputMap(WHEN_FOCUSED)</code>.
*
* @return the <code>InputMap</code> used when the component has focus
* @since 1.3
*/
public final InputMap getInputMap() {
return getInputMap(WHEN_FOCUSED, true);
}
/** {@collect.stats}
* Sets the <code>ActionMap</code> to <code>am</code>. This does not set
* the parent of the <code>am</code> to be the <code>ActionMap</code>
* from the UI (if there was one), it is up to the caller to have done this.
*
* @param am the new <code>ActionMap</code>
* @since 1.3
*/
public final void setActionMap(ActionMap am) {
actionMap = am;
setFlag(ACTIONMAP_CREATED, true);
}
/** {@collect.stats}
* Returns the <code>ActionMap</code> used to determine what
* <code>Action</code> to fire for particular <code>KeyStroke</code>
* binding. The returned <code>ActionMap</code>, unless otherwise
* set, will have the <code>ActionMap</code> from the UI set as the parent.
*
* @return the <code>ActionMap</code> containing the key/action bindings
* @since 1.3
*/
public final ActionMap getActionMap() {
return getActionMap(true);
}
/** {@collect.stats}
* Returns the <code>InputMap</code> to use for condition
* <code>condition</code>. If the <code>InputMap</code> hasn't
* been created, and <code>create</code> is
* true, it will be created.
*
* @param condition one of the following values:
* <ul>
* <li>JComponent.FOCUS_INPUTMAP_CREATED
* <li>JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
* <li>JComponent.WHEN_IN_FOCUSED_WINDOW
* </ul>
* @param create if true, create the <code>InputMap</code> if it
* is not already created
* @return the <code>InputMap</code> for the given <code>condition</code>;
* if <code>create</code> is false and the <code>InputMap</code>
* hasn't been created, returns <code>null</code>
* @exception IllegalArgumentException if <code>condition</code>
* is not one of the legal values listed above
*/
final InputMap getInputMap(int condition, boolean create) {
switch (condition) {
case WHEN_FOCUSED:
if (getFlag(FOCUS_INPUTMAP_CREATED)) {
return focusInputMap;
}
// Hasn't been created yet.
if (create) {
InputMap km = new InputMap();
setInputMap(condition, km);
return km;
}
break;
case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
if (getFlag(ANCESTOR_INPUTMAP_CREATED)) {
return ancestorInputMap;
}
// Hasn't been created yet.
if (create) {
InputMap km = new InputMap();
setInputMap(condition, km);
return km;
}
break;
case WHEN_IN_FOCUSED_WINDOW:
if (getFlag(WIF_INPUTMAP_CREATED)) {
return windowInputMap;
}
// Hasn't been created yet.
if (create) {
ComponentInputMap km = new ComponentInputMap(this);
setInputMap(condition, km);
return km;
}
break;
default:
throw new IllegalArgumentException("condition must be one of JComponent.WHEN_IN_FOCUSED_WINDOW, JComponent.WHEN_FOCUSED or JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
}
return null;
}
/** {@collect.stats}
* Finds and returns the appropriate <code>ActionMap</code>.
*
* @param create if true, create the <code>ActionMap</code> if it
* is not already created
* @return the <code>ActionMap</code> for this component; if the
* <code>create</code> flag is false and there is no
* current <code>ActionMap</code>, returns <code>null</code>
*/
final ActionMap getActionMap(boolean create) {
if (getFlag(ACTIONMAP_CREATED)) {
return actionMap;
}
// Hasn't been created.
if (create) {
ActionMap am = new ActionMap();
setActionMap(am);
return am;
}
return null;
}
/** {@collect.stats}
* Returns the baseline. The baseline is measured from the top of
* the component. This method is primarily meant for
* <code>LayoutManager</code>s to align components along their
* baseline. A return value less than 0 indicates this component
* does not have a reasonable baseline and that
* <code>LayoutManager</code>s should not align this component on
* its baseline.
* <p>
* This method calls into the <code>ComponentUI</code> method of the
* same name. If this component does not have a <code>ComponentUI</code>
* -1 will be returned. 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.
*
* @throws IllegalArgumentException {@inheritDoc}
* @see #getBaselineResizeBehavior
* @see java.awt.FontMetrics
* @since 1.6
*/
public int getBaseline(int width, int height) {
// check size.
super.getBaseline(width, height);
if (ui != null) {
return ui.getBaseline(this, width, height);
}
return -1;
}
/** {@collect.stats}
* Returns an enum indicating how the baseline of the component
* changes as the size changes. This method is primarily meant for
* layout managers and GUI builders.
* <p>
* This method calls into the <code>ComponentUI</code> method of
* the same name. If this component does not have a
* <code>ComponentUI</code>
* <code>BaselineResizeBehavior.OTHER</code> will be
* returned. 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.
*
* @see #getBaseline(int, int)
* @since 1.6
*/
public BaselineResizeBehavior getBaselineResizeBehavior() {
if (ui != null) {
return ui.getBaselineResizeBehavior(this);
}
return BaselineResizeBehavior.OTHER;
}
/** {@collect.stats}
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* Requests focus on this <code>JComponent</code>'s
* <code>FocusTraversalPolicy</code>'s default <code>Component</code>.
* If this <code>JComponent</code> is a focus cycle root, then its
* <code>FocusTraversalPolicy</code> is used. Otherwise, the
* <code>FocusTraversalPolicy</code> of this <code>JComponent</code>'s
* focus-cycle-root ancestor is used.
*
* @see java.awt.FocusTraversalPolicy#getDefaultComponent
* @deprecated As of 1.4, replaced by
* <code>FocusTraversalPolicy.getDefaultComponent(Container).requestFocus()</code>
*/
@Deprecated
public boolean requestDefaultFocus() {
Container nearestRoot =
(isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
if (nearestRoot == null) {
return false;
}
Component comp = nearestRoot.getFocusTraversalPolicy().
getDefaultComponent(nearestRoot);
if (comp != null) {
comp.requestFocus();
return true;
} else {
return false;
}
}
/** {@collect.stats}
* Makes the component visible or invisible.
* Overrides <code>Component.setVisible</code>.
*
* @param aFlag true to make the component visible; false to
* make it invisible
*
* @beaninfo
* attribute: visualUpdate true
*/
public void setVisible(boolean aFlag) {
if(aFlag != isVisible()) {
super.setVisible(aFlag);
Container parent = getParent();
if(parent != null) {
Rectangle r = getBounds();
parent.repaint(r.x,r.y,r.width,r.height);
}
// Some (all should) LayoutManagers do not consider components
// that are not visible. As such we need to revalidate when the
// visible bit changes.
revalidate();
}
}
/** {@collect.stats}
* Sets whether or not this component is enabled.
* A component that is enabled may respond to user input,
* while a component that is not enabled cannot respond to
* user input. Some components may alter their visual
* representation when they are disabled in order to
* provide feedback to the user that they cannot take input.
* <p>Note: Disabling a component does not disable its children.
*
* <p>Note: Disabling a lightweight component does not prevent it from
* receiving MouseEvents.
*
* @param enabled true if this component should be enabled, false otherwise
* @see java.awt.Component#isEnabled
* @see java.awt.Component#isLightweight
*
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: The enabled state of the component.
*/
public void setEnabled(boolean enabled) {
boolean oldEnabled = isEnabled();
super.setEnabled(enabled);
firePropertyChange("enabled", oldEnabled, enabled);
if (enabled != oldEnabled) {
repaint();
}
}
/** {@collect.stats}
* Sets the foreground color of this component. It is up to the
* look and feel to honor this property, some may choose to ignore
* it.
*
* @param fg the desired foreground <code>Color</code>
* @see java.awt.Component#getForeground
*
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: The foreground color of the component.
*/
public void setForeground(Color fg) {
Color oldFg = getForeground();
super.setForeground(fg);
if ((oldFg != null) ? !oldFg.equals(fg) : ((fg != null) && !fg.equals(oldFg))) {
// foreground already bound in AWT1.2
repaint();
}
}
/** {@collect.stats}
* Sets the background color of this component. The background
* color is used only if the component is opaque, and only
* by subclasses of <code>JComponent</code> or
* <code>ComponentUI</code> implementations. Direct subclasses of
* <code>JComponent</code> must override
* <code>paintComponent</code> to honor this property.
* <p>
* It is up to the look and feel to honor this property, some may
* choose to ignore it.
*
* @param bg the desired background <code>Color</code>
* @see java.awt.Component#getBackground
* @see #setOpaque
*
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: The background color of the component.
*/
public void setBackground(Color bg) {
Color oldBg = getBackground();
super.setBackground(bg);
if ((oldBg != null) ? !oldBg.equals(bg) : ((bg != null) && !bg.equals(oldBg))) {
// background already bound in AWT1.2
repaint();
}
}
/** {@collect.stats}
* Sets the font for this component.
*
* @param font the desired <code>Font</code> for this component
* @see java.awt.Component#getFont
*
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: The font for the component.
*/
public void setFont(Font font) {
Font oldFont = getFont();
super.setFont(font);
// font already bound in AWT1.2
if (font != oldFont) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the default locale used to initialize each JComponent's
* locale property upon creation.
*
* The default locale has "AppContext" scope so that applets (and
* potentially multiple lightweight applications running in a single VM)
* can have their own setting. An applet can safely alter its default
* locale because it will have no affect on other applets (or the browser).
*
* @return the default <code>Locale</code>.
* @see #setDefaultLocale
* @see java.awt.Component#getLocale
* @see #setLocale
* @since 1.4
*/
static public Locale getDefaultLocale() {
Locale l = (Locale) SwingUtilities.appContextGet(defaultLocale);
if( l == null ) {
//REMIND(bcb) choosing the default value is more complicated
//than this.
l = Locale.getDefault();
JComponent.setDefaultLocale( l );
}
return l;
}
/** {@collect.stats}
* Sets the default locale used to initialize each JComponent's locale
* property upon creation. The initial value is the VM's default locale.
*
* The default locale has "AppContext" scope so that applets (and
* potentially multiple lightweight applications running in a single VM)
* can have their own setting. An applet can safely alter its default
* locale because it will have no affect on other applets (or the browser).
*
* @param l the desired default <code>Locale</code> for new components.
* @see #getDefaultLocale
* @see java.awt.Component#getLocale
* @see #setLocale
* @since 1.4
*/
static public void setDefaultLocale( Locale l ) {
SwingUtilities.appContextPut(defaultLocale, l);
}
/** {@collect.stats}
* Processes any key events that the component itself
* recognizes. This is called after the focus
* manager and any interested listeners have been
* given a chance to steal away the event. This
* method is called only if the event has not
* yet been consumed. This method is called prior
* to the keyboard UI logic.
* <p>
* This method is implemented to do nothing. Subclasses would
* normally override this method if they process some
* key events themselves. If the event is processed,
* it should be consumed.
*/
protected void processComponentKeyEvent(KeyEvent e) {
}
/** {@collect.stats} Overrides <code>processKeyEvent</code> to process events. **/
protected void processKeyEvent(KeyEvent e) {
boolean result;
boolean shouldProcessKey;
// This gives the key event listeners a crack at the event
super.processKeyEvent(e);
// give the component itself a crack at the event
if (! e.isConsumed()) {
processComponentKeyEvent(e);
}
shouldProcessKey = KeyboardState.shouldProcess(e);
if(e.isConsumed()) {
return;
}
if (shouldProcessKey && processKeyBindings(e, e.getID() ==
KeyEvent.KEY_PRESSED)) {
e.consume();
}
}
/** {@collect.stats}
* Invoked to process the key bindings for <code>ks</code> as the result
* of the <code>KeyEvent</code> <code>e</code>. This obtains
* the appropriate <code>InputMap</code>,
* gets the binding, gets the action from the <code>ActionMap</code>,
* and then (if the action is found and the component
* is enabled) invokes <code>notifyAction</code> to notify the action.
*
* @param ks the <code>KeyStroke</code> queried
* @param e the <code>KeyEvent</code>
* @param condition one of the following values:
* <ul>
* <li>JComponent.WHEN_FOCUSED
* <li>JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
* <li>JComponent.WHEN_IN_FOCUSED_WINDOW
* </ul>
* @param pressed true if the key is pressed
* @return true if there was a binding to an action, and the action
* was enabled
*
* @since 1.3
*/
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
int condition, boolean pressed) {
InputMap map = getInputMap(condition, false);
ActionMap am = getActionMap(false);
if(map != null && am != null && isEnabled()) {
Object binding = map.get(ks);
Action action = (binding == null) ? null : am.get(binding);
if (action != null) {
return SwingUtilities.notifyAction(action, ks, e, this,
e.getModifiers());
}
}
return false;
}
/** {@collect.stats}
* This is invoked as the result of a <code>KeyEvent</code>
* that was not consumed by the <code>FocusManager</code>,
* <code>KeyListeners</code>, or the component. It will first try
* <code>WHEN_FOCUSED</code> bindings,
* then <code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code> bindings,
* and finally <code>WHEN_IN_FOCUSED_WINDOW</code> bindings.
*
* @param e the unconsumed <code>KeyEvent</code>
* @param pressed true if the key is pressed
* @return true if there is a key binding for <code>e</code>
*/
boolean processKeyBindings(KeyEvent e, boolean pressed) {
if (!SwingUtilities.isValidKeyEventForKeyBindings(e)) {
return false;
}
// Get the KeyStroke
KeyStroke ks;
if (e.getID() == KeyEvent.KEY_TYPED) {
ks = KeyStroke.getKeyStroke(e.getKeyChar());
}
else {
ks = KeyStroke.getKeyStroke(e.getKeyCode(),e.getModifiers(),
(pressed ? false:true));
}
/* Do we have a key binding for e? */
if(processKeyBinding(ks, e, WHEN_FOCUSED, pressed))
return true;
/* We have no key binding. Let's try the path from our parent to the
* window excluded. We store the path components so we can avoid
* asking the same component twice.
*/
Container parent = this;
while (parent != null && !(parent instanceof Window) &&
!(parent instanceof Applet)) {
if(parent instanceof JComponent) {
if(((JComponent)parent).processKeyBinding(ks, e,
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, pressed))
return true;
}
// This is done so that the children of a JInternalFrame are
// given precedence for WHEN_IN_FOCUSED_WINDOW bindings before
// other components WHEN_IN_FOCUSED_WINDOW bindings. This also gives
// more precedence to the WHEN_IN_FOCUSED_WINDOW bindings of the
// JInternalFrame's children vs the
// WHEN_ANCESTOR_OF_FOCUSED_COMPONENT bindings of the parents.
// maybe generalize from JInternalFrame (like isFocusCycleRoot).
if ((parent instanceof JInternalFrame) &&
JComponent.processKeyBindingsForAllComponents(e,parent,pressed)){
return true;
}
parent = parent.getParent();
}
/* No components between the focused component and the window is
* actually interested by the key event. Let's try the other
* JComponent in this window.
*/
if(parent != null) {
return JComponent.processKeyBindingsForAllComponents(e,parent,pressed);
}
return false;
}
static boolean processKeyBindingsForAllComponents(KeyEvent e,
Container container, boolean pressed) {
while (true) {
if (KeyboardManager.getCurrentManager().fireKeyboardAction(
e, pressed, container)) {
return true;
}
if (container instanceof Popup.HeavyWeightWindow) {
container = ((Window)container).getOwner();
}
else {
return false;
}
}
}
/** {@collect.stats}
* Registers the text to display in a tool tip.
* The text displays when the cursor lingers over the component.
* <p>
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tooltip.html">How to Use Tool Tips</a>
* in <em>The Java Tutorial</em>
* for further documentation.
*
* @param text the string to display; if the text is <code>null</code>,
* the tool tip is turned off for this component
* @see #TOOL_TIP_TEXT_KEY
* @beaninfo
* preferred: true
* description: The text to display in a tool tip.
*/
public void setToolTipText(String text) {
String oldText = getToolTipText();
putClientProperty(TOOL_TIP_TEXT_KEY, text);
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
if (text != null) {
if (oldText == null) {
toolTipManager.registerComponent(this);
}
} else {
toolTipManager.unregisterComponent(this);
}
}
/** {@collect.stats}
* Returns the tooltip string that has been set with
* <code>setToolTipText</code>.
*
* @return the text of the tool tip
* @see #TOOL_TIP_TEXT_KEY
*/
public String getToolTipText() {
return (String)getClientProperty(TOOL_TIP_TEXT_KEY);
}
/** {@collect.stats}
* Returns the string to be used as the tooltip for <i>event</i>.
* By default this returns any string set using
* <code>setToolTipText</code>. If a component provides
* more extensive API to support differing tooltips at different locations,
* this method should be overridden.
*/
public String getToolTipText(MouseEvent event) {
return getToolTipText();
}
/** {@collect.stats}
* Returns the tooltip location in this component's coordinate system.
* If <code>null</code> is returned, Swing will choose a location.
* The default implementation returns <code>null</code>.
*
* @param event the <code>MouseEvent</code> that caused the
* <code>ToolTipManager</code> to show the tooltip
* @return always returns <code>null</code>
*/
public Point getToolTipLocation(MouseEvent event) {
return null;
}
/** {@collect.stats}
* Returns the preferred location to display the popup menu in this
* component's coordinate system. It is up to the look and feel to
* honor this property, some may choose to ignore it.
* If {@code null}, the look and feel will choose a suitable location.
*
* @param event the {@code MouseEvent} that triggered the popup to be
* shown, or {@code null} if the popup is not being shown as the
* result of a mouse event
* @return location to display the {@code JPopupMenu}, or {@code null}
* @since 1.5
*/
public Point getPopupLocation(MouseEvent event) {
return null;
}
/** {@collect.stats}
* Returns the instance of <code>JToolTip</code> that should be used
* to display the tooltip.
* Components typically would not override this method,
* but it can be used to
* cause different tooltips to be displayed differently.
*
* @return the <code>JToolTip</code> used to display this toolTip
*/
public JToolTip createToolTip() {
JToolTip tip = new JToolTip();
tip.setComponent(this);
return tip;
}
/** {@collect.stats}
* Forwards the <code>scrollRectToVisible()</code> message to the
* <code>JComponent</code>'s parent. Components that can service
* the request, such as <code>JViewport</code>,
* override this method and perform the scrolling.
*
* @param aRect the visible <code>Rectangle</code>
* @see JViewport
*/
public void scrollRectToVisible(Rectangle aRect) {
Container parent;
int dx = getX(), dy = getY();
for (parent = getParent();
!(parent == null) &&
!(parent instanceof JComponent) &&
!(parent instanceof CellRendererPane);
parent = parent.getParent()) {
Rectangle bounds = parent.getBounds();
dx += bounds.x;
dy += bounds.y;
}
if (!(parent == null) && !(parent instanceof CellRendererPane)) {
aRect.x += dx;
aRect.y += dy;
((JComponent)parent).scrollRectToVisible(aRect);
aRect.x -= dx;
aRect.y -= dy;
}
}
/** {@collect.stats}
* Sets the <code>autoscrolls</code> property.
* If <code>true</code> mouse dragged events will be
* synthetically generated when the mouse is dragged
* outside of the component's bounds and mouse motion
* has paused (while the button continues to be held
* down). The synthetic events make it appear that the
* drag gesture has resumed in the direction established when
* the component's boundary was crossed. Components that
* support autoscrolling must handle <code>mouseDragged</code>
* events by calling <code>scrollRectToVisible</code> with a
* rectangle that contains the mouse event's location. All of
* the Swing components that support item selection and are
* typically displayed in a <code>JScrollPane</code>
* (<code>JTable</code>, <code>JList</code>, <code>JTree</code>,
* <code>JTextArea</code>, and <code>JEditorPane</code>)
* already handle mouse dragged events in this way. To enable
* autoscrolling in any other component, add a mouse motion
* listener that calls <code>scrollRectToVisible</code>.
* For example, given a <code>JPanel</code>, <code>myPanel</code>:
* <pre>
* MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
* public void mouseDragged(MouseEvent e) {
* Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
* ((JPanel)e.getSource()).scrollRectToVisible(r);
* }
* };
* myPanel.addMouseMotionListener(doScrollRectToVisible);
* </pre>
* The default value of the <code>autoScrolls</code>
* property is <code>false</code>.
*
* @param autoscrolls if true, synthetic mouse dragged events
* are generated when the mouse is dragged outside of a component's
* bounds and the mouse button continues to be held down; otherwise
* false
* @see #getAutoscrolls
* @see JViewport
* @see JScrollPane
*
* @beaninfo
* expert: true
* description: Determines if this component automatically scrolls its contents when dragged.
*/
public void setAutoscrolls(boolean autoscrolls) {
setFlag(AUTOSCROLLS_SET, true);
if (this.autoscrolls != autoscrolls) {
this.autoscrolls = autoscrolls;
if (autoscrolls) {
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
else {
Autoscroller.stop(this);
}
}
}
/** {@collect.stats}
* Gets the <code>autoscrolls</code> property.
*
* @return the value of the <code>autoscrolls</code> property
* @see JViewport
* @see #setAutoscrolls
*/
public boolean getAutoscrolls() {
return autoscrolls;
}
/** {@collect.stats}
* Sets the <code>transferHandler</code> property,
* which is <code>null</code> if the component does
* not support data transfer operations.
* <p>
* If <code>newHandler</code> is not <code>null</code>,
* and the system property
* <code>suppressSwingDropSupport</code> is not true, this will
* install a <code>DropTarget</code> on the <code>JComponent</code>.
* The default for the system property is false, so that a
* <code>DropTarget</code> will be added.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html">
* How to Use Drag and Drop and Data Transfer</a>,
* a section in <em>The Java Tutorial</em>, for more information.
*
* @param newHandler mechanism for transfer of data to
* and from the component
*
* @see TransferHandler
* @see #getTransferHandler
* @since 1.4
* @beaninfo
* bound: true
* hidden: true
* description: Mechanism for transfer of data to and from the component
*/
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)getClientProperty(
JComponent_TRANSFER_HANDLER);
putClientProperty(JComponent_TRANSFER_HANDLER, newHandler);
SwingUtilities.installSwingDropTargetAsNecessary(this, newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
/** {@collect.stats}
* Gets the <code>transferHandler</code> property.
*
* @return the value of the <code>transferHandler</code> property
*
* @see TransferHandler
* @see #setTransferHandler
* @since 1.4
*/
public TransferHandler getTransferHandler() {
return (TransferHandler)getClientProperty(JComponent_TRANSFER_HANDLER);
}
/** {@collect.stats}
* Calculates a custom drop location for this type of component,
* representing where a drop at the given point should insert data.
* <code>null</code> is returned if this component doesn't calculate
* custom drop locations. In this case, <code>TransferHandler</code>
* will provide a default <code>DropLocation</code> containing just
* the point.
*
* @param p the point to calculate a drop location for
* @return the drop location, or <code>null</code>
*/
TransferHandler.DropLocation dropLocationForPoint(Point p) {
return null;
}
/** {@collect.stats}
* Called to set or clear the drop location during a DnD operation.
* In some cases, the component may need to use its internal selection
* temporarily to indicate the drop location. To help facilitate this,
* this method returns and accepts as a parameter a state object.
* This state object can be used to store, and later restore, the selection
* state. Whatever this method returns will be passed back to it in
* future calls, as the state parameter. If it wants the DnD system to
* continue storing the same state, it must pass it back every time.
* Here's how this is used:
* <p>
* Let's say that on the first call to this method the component decides
* to save some state (because it is about to use the selection to show
* a drop index). It can return a state object to the caller encapsulating
* any saved selection state. On a second call, let's say the drop location
* is being changed to something else. The component doesn't need to
* restore anything yet, so it simply passes back the same state object
* to have the DnD system continue storing it. Finally, let's say this
* method is messaged with <code>null</code>. This means DnD
* is finished with this component for now, meaning it should restore
* state. At this point, it can use the state parameter to restore
* said state, and of course return <code>null</code> since there's
* no longer anything to store.
*
* @param location the drop location (as calculated by
* <code>dropLocationForPoint</code>) or <code>null</code>
* if there's no longer a valid drop location
* @param state the state object saved earlier for this component,
* or <code>null</code>
* @param forDrop whether or not the method is being called because an
* actual drop occurred
* @return any saved state for this component, or <code>null</code> if none
*/
Object setDropLocation(TransferHandler.DropLocation location,
Object state,
boolean forDrop) {
return null;
}
/** {@collect.stats}
* Called to indicate to this component that DnD is done.
* Needed by <code>JTree</code>.
*/
void dndDone() {
}
/** {@collect.stats}
* Processes mouse events occurring on this component by
* dispatching them to any registered
* <code>MouseListener</code> objects, refer to
* {@link java.awt.Component#processMouseEvent(MouseEvent)}
* for a complete description of this method.
*
* @param e the mouse event
* @see java.awt.Component#processMouseEvent
* @since 1.5
*/
protected void processMouseEvent(MouseEvent e) {
if (autoscrolls && e.getID() == MouseEvent.MOUSE_RELEASED) {
Autoscroller.stop(this);
}
super.processMouseEvent(e);
}
/** {@collect.stats}
* Processes mouse motion events, such as MouseEvent.MOUSE_DRAGGED.
*
* @param e the <code>MouseEvent</code>
* @see MouseEvent
*/
protected void processMouseMotionEvent(MouseEvent e) {
boolean dispatch = true;
if (autoscrolls && e.getID() == MouseEvent.MOUSE_DRAGGED) {
// We don't want to do the drags when the mouse moves if we're
// autoscrolling. It makes it feel spastic.
dispatch = !Autoscroller.isRunning(this);
Autoscroller.processMouseDragged(e);
}
if (dispatch) {
super.processMouseMotionEvent(e);
}
}
// Inner classes can't get at this method from a super class
void superProcessMouseMotionEvent(MouseEvent e) {
super.processMouseMotionEvent(e);
}
/** {@collect.stats}
* This is invoked by the <code>RepaintManager</code> if
* <code>createImage</code> is called on the component.
*
* @param newValue true if the double buffer image was created from this component
*/
void setCreatedDoubleBuffer(boolean newValue) {
setFlag(CREATED_DOUBLE_BUFFER, newValue);
}
/** {@collect.stats}
* Returns true if the <code>RepaintManager</code>
* created the double buffer image from the component.
*
* @return true if this component had a double buffer image, false otherwise
*/
boolean getCreatedDoubleBuffer() {
return getFlag(CREATED_DOUBLE_BUFFER);
}
/** {@collect.stats}
* <code>ActionStandin</code> is used as a standin for
* <code>ActionListeners</code> that are
* added via <code>registerKeyboardAction</code>.
*/
final class ActionStandin implements Action {
private final ActionListener actionListener;
private final String command;
// This will be non-null if actionListener is an Action.
private final Action action;
ActionStandin(ActionListener actionListener, String command) {
this.actionListener = actionListener;
if (actionListener instanceof Action) {
this.action = (Action)actionListener;
}
else {
this.action = null;
}
this.command = command;
}
public Object getValue(String key) {
if (key != null) {
if (key.equals(Action.ACTION_COMMAND_KEY)) {
return command;
}
if (action != null) {
return action.getValue(key);
}
if (key.equals(NAME)) {
return "ActionStandin";
}
}
return null;
}
public boolean isEnabled() {
if (actionListener == null) {
// This keeps the old semantics where
// registerKeyboardAction(null) would essentialy remove
// the binding. We don't remove the binding from the
// InputMap as that would still allow parent InputMaps
// bindings to be accessed.
return false;
}
if (action == null) {
return true;
}
return action.isEnabled();
}
public void actionPerformed(ActionEvent ae) {
if (actionListener != null) {
actionListener.actionPerformed(ae);
}
}
// We don't allow any values to be added.
public void putValue(String key, Object value) {}
// Does nothing, our enabledness is determiend from our asociated
// action.
public void setEnabled(boolean b) { }
public void addPropertyChangeListener
(PropertyChangeListener listener) {}
public void removePropertyChangeListener
(PropertyChangeListener listener) {}
}
// This class is used by the KeyboardState class to provide a single
// instance that can be stored in the AppContext.
static final class IntVector {
int array[] = null;
int count = 0;
int capacity = 0;
int size() {
return count;
}
int elementAt(int index) {
return array[index];
}
void addElement(int value) {
if (count == capacity) {
capacity = (capacity + 2) * 2;
int[] newarray = new int[capacity];
if (count > 0) {
System.arraycopy(array, 0, newarray, 0, count);
}
array = newarray;
}
array[count++] = value;
}
void setElementAt(int value, int index) {
array[index] = value;
}
}
static class KeyboardState implements Serializable {
private static final Object keyCodesKey =
JComponent.KeyboardState.class;
// Get the array of key codes from the AppContext.
static IntVector getKeyCodeArray() {
IntVector iv =
(IntVector)SwingUtilities.appContextGet(keyCodesKey);
if (iv == null) {
iv = new IntVector();
SwingUtilities.appContextPut(keyCodesKey, iv);
}
return iv;
}
static void registerKeyPressed(int keyCode) {
IntVector kca = getKeyCodeArray();
int count = kca.size();
int i;
for(i=0;i<count;i++) {
if(kca.elementAt(i) == -1){
kca.setElementAt(keyCode, i);
return;
}
}
kca.addElement(keyCode);
}
static void registerKeyReleased(int keyCode) {
IntVector kca = getKeyCodeArray();
int count = kca.size();
int i;
for(i=0;i<count;i++) {
if(kca.elementAt(i) == keyCode) {
kca.setElementAt(-1, i);
return;
}
}
}
static boolean keyIsPressed(int keyCode) {
IntVector kca = getKeyCodeArray();
int count = kca.size();
int i;
for(i=0;i<count;i++) {
if(kca.elementAt(i) == keyCode) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Updates internal state of the KeyboardState and returns true
* if the event should be processed further.
*/
static boolean shouldProcess(KeyEvent e) {
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
if (!keyIsPressed(e.getKeyCode())) {
registerKeyPressed(e.getKeyCode());
}
return true;
case KeyEvent.KEY_RELEASED:
// We are forced to process VK_PRINTSCREEN separately because
// the Windows doesn't generate the key pressed event for
// printscreen and it block the processing of key release
// event for printscreen.
if (keyIsPressed(e.getKeyCode()) || e.getKeyCode()==KeyEvent.VK_PRINTSCREEN) {
registerKeyReleased(e.getKeyCode());
return true;
}
return false;
case KeyEvent.KEY_TYPED:
return true;
default:
// Not a known KeyEvent type, bail.
return false;
}
}
}
static final sun.awt.RequestFocusController focusController =
new sun.awt.RequestFocusController() {
public boolean acceptRequestFocus(Component from, Component to,
boolean temporary, boolean focusedWindowChangeAllowed,
sun.awt.CausedFocusEvent.Cause cause)
{
if ((to == null) || !(to instanceof JComponent)) {
return true;
}
if ((from == null) || !(from instanceof JComponent)) {
return true;
}
JComponent target = (JComponent) to;
if (!target.getVerifyInputWhenFocusTarget()) {
return true;
}
JComponent jFocusOwner = (JComponent)from;
InputVerifier iv = jFocusOwner.getInputVerifier();
if (iv == null) {
return true;
} else {
Object currentSource = SwingUtilities.appContextGet(
INPUT_VERIFIER_SOURCE_KEY);
if (currentSource == jFocusOwner) {
// We're currently calling into the InputVerifier
// for this component, so allow the focus change.
return true;
}
SwingUtilities.appContextPut(INPUT_VERIFIER_SOURCE_KEY,
jFocusOwner);
try {
return iv.shouldYieldFocus(jFocusOwner);
} finally {
if (currentSource != null) {
// We're already in the InputVerifier for
// currentSource. By resetting the currentSource
// we ensure that if the InputVerifier for
// currentSource does a requestFocus, we don't
// try and run the InputVerifier again.
SwingUtilities.appContextPut(
INPUT_VERIFIER_SOURCE_KEY, currentSource);
} else {
SwingUtilities.appContextRemove(
INPUT_VERIFIER_SOURCE_KEY);
}
}
}
}
};
/*
* --- Accessibility Support ---
*/
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>java.awt.Component.setEnabled(boolean)</code>.
*/
@Deprecated
public void enable() {
if (isEnabled() != true) {
super.enable();
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.ENABLED);
}
}
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>java.awt.Component.setEnabled(boolean)</code>.
*/
@Deprecated
public void disable() {
if (isEnabled() != false) {
super.disable();
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.ENABLED, null);
}
}
}
/** {@collect.stats}
* The <code>AccessibleContext</code> associated with this
* <code>JComponent</code>.
*/
protected AccessibleContext accessibleContext = null;
/** {@collect.stats}
* Returns the <code>AccessibleContext</code> associated with this
* <code>JComponent</code>. The method implemented by this base
* class returns null. Classes that extend <code>JComponent</code>
* should implement this method to return the
* <code>AccessibleContext</code> associated with the subclass.
*
* @return the <code>AccessibleContext</code> of this
* <code>JComponent</code>
*/
public AccessibleContext getAccessibleContext() {
return accessibleContext;
}
/** {@collect.stats}
* Inner class of JComponent used to provide default support for
* accessibility. This class is not meant to be used directly by
* application developers, but is instead meant only to be
* subclassed by component developers.
* <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}.
*/
public abstract class AccessibleJComponent extends AccessibleAWTContainer
implements AccessibleExtendedComponent
{
/** {@collect.stats}
* Though the class is abstract, this should be called by
* all sub-classes.
*/
protected AccessibleJComponent() {
super();
}
protected ContainerListener accessibleContainerHandler = null;
protected FocusListener accessibleFocusHandler = null;
/** {@collect.stats}
* Fire PropertyChange listener, if one is registered,
* when children added/removed.
*/
protected class AccessibleContainerHandler
implements ContainerListener {
public void componentAdded(ContainerEvent e) {
Component c = e.getChild();
if (c != null && c instanceof Accessible) {
AccessibleJComponent.this.firePropertyChange(
AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
null, ((Accessible) c).getAccessibleContext());
}
}
public void componentRemoved(ContainerEvent e) {
Component c = e.getChild();
if (c != null && c instanceof Accessible) {
AccessibleJComponent.this.firePropertyChange(
AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
((Accessible) c).getAccessibleContext(), null);
}
}
}
/** {@collect.stats}
* Fire PropertyChange listener, if one is registered,
* when focus events happen
* @since 1.3
*/
protected class AccessibleFocusHandler implements FocusListener {
public void focusGained(FocusEvent event) {
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.FOCUSED);
}
}
public void focusLost(FocusEvent event) {
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.FOCUSED, null);
}
}
} // inner class AccessibleFocusHandler
/** {@collect.stats}
* Adds a PropertyChangeListener to the listener list.
*
* @param listener the PropertyChangeListener to be added
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
if (accessibleFocusHandler == null) {
accessibleFocusHandler = new AccessibleFocusHandler();
JComponent.this.addFocusListener(accessibleFocusHandler);
}
if (accessibleContainerHandler == null) {
accessibleContainerHandler = new AccessibleContainerHandler();
JComponent.this.addContainerListener(accessibleContainerHandler);
}
super.addPropertyChangeListener(listener);
}
/** {@collect.stats}
* Removes a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param listener the PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
if (accessibleFocusHandler != null) {
JComponent.this.removeFocusListener(accessibleFocusHandler);
accessibleFocusHandler = null;
}
super.removePropertyChangeListener(listener);
}
/** {@collect.stats}
* Recursively search through the border hierarchy (if it exists)
* for a TitledBorder with a non-null title. This does a depth
* first search on first the inside borders then the outside borders.
* The assumption is that titles make really pretty inside borders
* but not very pretty outside borders in compound border situations.
* It's rather arbitrary, but hopefully decent UI programmers will
* not create multiple titled borders for the same component.
*/
protected String getBorderTitle(Border b) {
String s;
if (b instanceof TitledBorder) {
return ((TitledBorder) b).getTitle();
} else if (b instanceof CompoundBorder) {
s = getBorderTitle(((CompoundBorder) b).getInsideBorder());
if (s == null) {
s = getBorderTitle(((CompoundBorder) b).getOutsideBorder());
}
return s;
} else {
return null;
}
}
// AccessibleContext methods
//
/** {@collect.stats}
* Gets the accessible name of this object. This should almost never
* return java.awt.Component.getName(), as that generally isn't
* a localized name, and doesn't have meaning for the user. If the
* object is fundamentally a text object (such as a menu item), the
* accessible name should be the text of the object (for example,
* "save").
* If the object has a tooltip, the tooltip text may also be an
* appropriate String to return.
*
* @return the localized name of the object -- can be null if this
* object does not have a name
* @see AccessibleContext#setAccessibleName
*/
public String getAccessibleName() {
String name = accessibleName;
// fallback to the client name property
//
if (name == null) {
name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
// fallback to the titled border if it exists
//
if (name == null) {
name = getBorderTitle(getBorder());
}
// fallback to the label labeling us if it exists
//
if (name == null) {
Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
if (o instanceof Accessible) {
AccessibleContext ac = ((Accessible) o).getAccessibleContext();
if (ac != null) {
name = ac.getAccessibleName();
}
}
}
return name;
}
/** {@collect.stats}
* Gets the accessible description of this object. This should be
* a concise, localized description of what this object is - what
* is its meaning to the user. If the object has a tooltip, the
* tooltip text may be an appropriate string to return, assuming
* it contains a concise description of the object (instead of just
* the name of the object - for example a "Save" icon on a toolbar that
* had "save" as the tooltip text shouldn't return the tooltip
* text as the description, but something like "Saves the current
* text document" instead).
*
* @return the localized description of the object -- can be null if
* this object does not have a description
* @see AccessibleContext#setAccessibleDescription
*/
public String getAccessibleDescription() {
String description = accessibleDescription;
// fallback to the client description property
//
if (description == null) {
description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY);
}
// fallback to the tool tip text if it exists
//
if (description == null) {
try {
description = getToolTipText();
} catch (Exception e) {
// Just in case the subclass overrode the
// getToolTipText method and actually
// requires a MouseEvent.
// [[[FIXME: WDW - we probably should require this
// method to take a MouseEvent and just pass it on
// to getToolTipText. The swing-feedback traffic
// leads me to believe getToolTipText might change,
// though, so I was hesitant to make this change at
// this time.]]]
}
}
// fallback to the label labeling us if it exists
//
if (description == null) {
Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
if (o instanceof Accessible) {
AccessibleContext ac = ((Accessible) o).getAccessibleContext();
if (ac != null) {
description = ac.getAccessibleDescription();
}
}
}
return description;
}
/** {@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.SWING_COMPONENT;
}
/** {@collect.stats}
* Gets the state of this object.
*
* @return an instance of AccessibleStateSet containing the current
* state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (JComponent.this.isOpaque()) {
states.add(AccessibleState.OPAQUE);
}
return states;
}
/** {@collect.stats}
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
return super.getAccessibleChildrenCount();
}
/** {@collect.stats}
* Returns the nth Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
return super.getAccessibleChild(i);
}
// ----- AccessibleExtendedComponent
/** {@collect.stats}
* Returns the AccessibleExtendedComponent
*
* @return the AccessibleExtendedComponent
*/
AccessibleExtendedComponent getAccessibleExtendedComponent() {
return this;
}
/** {@collect.stats}
* Returns the tool tip text
*
* @return the tool tip text, if supported, of the object;
* otherwise, null
* @since 1.4
*/
public String getToolTipText() {
return JComponent.this.getToolTipText();
}
/** {@collect.stats}
* Returns the titled border text
*
* @return the titled border text, if supported, of the object;
* otherwise, null
* @since 1.4
*/
public String getTitledBorderText() {
Border border = JComponent.this.getBorder();
if (border instanceof TitledBorder) {
return ((TitledBorder)border).getTitle();
} else {
return null;
}
}
/** {@collect.stats}
* Returns key bindings associated with this object
*
* @return the key bindings, if supported, of the object;
* otherwise, null
* @see AccessibleKeyBinding
* @since 1.4
*/
public AccessibleKeyBinding getAccessibleKeyBinding() {
return null;
}
} // inner class AccessibleJComponent
/** {@collect.stats}
* Returns an <code>ArrayTable</code> used for
* key/value "client properties" for this component. If the
* <code>clientProperties</code> table doesn't exist, an empty one
* will be created.
*
* @return an ArrayTable
* @see #putClientProperty
* @see #getClientProperty
*/
private ArrayTable getClientProperties() {
if (clientProperties == null) {
clientProperties = new ArrayTable();
}
return clientProperties;
}
/** {@collect.stats}
* Returns the value of the property with the specified key. Only
* properties added with <code>putClientProperty</code> will return
* a non-<code>null</code> value.
*
* @param key the being queried
* @return the value of this property or <code>null</code>
* @see #putClientProperty
*/
public final Object getClientProperty(Object key) {
if (key == SwingUtilities2.AA_TEXT_PROPERTY_KEY) {
return aaTextInfo;
} else if (key == SwingUtilities2.COMPONENT_UI_PROPERTY_KEY) {
return ui;
}
if(clientProperties == null) {
return null;
} else {
synchronized(clientProperties) {
return clientProperties.get(key);
}
}
}
/** {@collect.stats}
* Adds an arbitrary key/value "client property" to this component.
* <p>
* The <code>get/putClientProperty</code> methods provide access to
* a small per-instance hashtable. Callers can use get/putClientProperty
* to annotate components that were created by another module.
* For example, a
* layout manager might store per child constraints this way. For example:
* <pre>
* componentA.putClientProperty("to the left of", componentB);
* </pre>
* If value is <code>null</code> this method will remove the property.
* Changes to client properties are reported with
* <code>PropertyChange</code> events.
* The name of the property (for the sake of PropertyChange
* events) is <code>key.toString()</code>.
* <p>
* The <code>clientProperty</code> dictionary is not intended to
* support large
* scale extensions to JComponent nor should be it considered an
* alternative to subclassing when designing a new component.
*
* @param key the new client property key
* @param value the new client property value; if <code>null</code>
* this method will remove the property
* @see #getClientProperty
* @see #addPropertyChangeListener
*/
public final void putClientProperty(Object key, Object value) {
if (key == SwingUtilities2.AA_TEXT_PROPERTY_KEY) {
aaTextInfo = value;
return;
}
if (value == null && clientProperties == null) {
// Both the value and ArrayTable are null, implying we don't
// have to do anything.
return;
}
ArrayTable clientProperties = getClientProperties();
Object oldValue;
synchronized(clientProperties) {
oldValue = clientProperties.get(key);
if (value != null) {
clientProperties.put(key, value);
} else if (oldValue != null) {
clientProperties.remove(key);
} else {
// old == new == null
return;
}
}
clientPropertyChanged(key, oldValue, value);
firePropertyChange(key.toString(), oldValue, value);
}
// Invoked from putClientProperty. This is provided for subclasses
// in Swing.
void clientPropertyChanged(Object key, Object oldValue,
Object newValue) {
}
/*
* Sets the property with the specified name to the specified value if
* the property has not already been set by the client program.
* This method is used primarily to set UI defaults for properties
* with primitive types, where the values cannot be marked with
* UIResource.
* @see LookAndFeel#installProperty
* @param propertyName String containing the name of the property
* @param value Object containing the property value
*/
void setUIProperty(String propertyName, Object value) {
if (propertyName == "opaque") {
if (!getFlag(OPAQUE_SET)) {
setOpaque(((Boolean)value).booleanValue());
setFlag(OPAQUE_SET, false);
}
} else if (propertyName == "autoscrolls") {
if (!getFlag(AUTOSCROLLS_SET)) {
setAutoscrolls(((Boolean)value).booleanValue());
setFlag(AUTOSCROLLS_SET, false);
}
} else if (propertyName == "focusTraversalKeysForward") {
if (!getFlag(FOCUS_TRAVERSAL_KEYS_FORWARD_SET)) {
super.setFocusTraversalKeys(KeyboardFocusManager.
FORWARD_TRAVERSAL_KEYS,
(Set)value);
}
} else if (propertyName == "focusTraversalKeysBackward") {
if (!getFlag(FOCUS_TRAVERSAL_KEYS_BACKWARD_SET)) {
super.setFocusTraversalKeys(KeyboardFocusManager.
BACKWARD_TRAVERSAL_KEYS,
(Set)value);
}
} else {
throw new IllegalArgumentException("property \""+
propertyName+ "\" cannot be set using this method");
}
}
/** {@collect.stats}
* Sets the focus traversal keys for a given traversal operation for this
* Component.
* Refer to
* {@link java.awt.Component#setFocusTraversalKeys}
* for a complete description of this method.
*
* @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
* @param keystrokes the Set of AWTKeyStroke for the specified operation
* @see java.awt.KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
* @see java.awt.KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
* @see java.awt.KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
* @throws IllegalArgumentException if id is not one of
* KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes
* contains null, or if any Object in keystrokes is not an
* AWTKeyStroke, or if any keystroke represents a KEY_TYPED event,
* or if any keystroke already maps to another focus traversal
* operation for this Component
* @since 1.5
* @beaninfo
* bound: true
*/
public void
setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)
{
if (id == KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS) {
setFlag(FOCUS_TRAVERSAL_KEYS_FORWARD_SET,true);
} else if (id == KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS) {
setFlag(FOCUS_TRAVERSAL_KEYS_BACKWARD_SET,true);
}
super.setFocusTraversalKeys(id,keystrokes);
}
/* --- Transitional java.awt.Component Support ---
* The methods and fields in this section will migrate to
* java.awt.Component in the next JDK release.
*/
/** {@collect.stats}
* Returns true if this component is lightweight, that is, if it doesn't
* have a native window system peer.
*
* @return true if this component is lightweight
*/
public static boolean isLightweightComponent(Component c) {
return c.getPeer() instanceof LightweightPeer;
}
/** {@collect.stats}
* @deprecated As of JDK 5,
* replaced by <code>Component.setBounds(int, int, int, int)</code>.
* <p>
* Moves and resizes this component.
*
* @param x the new horizontal location
* @param y the new vertical location
* @param w the new width
* @param h the new height
* @see java.awt.Component#setBounds
*/
@Deprecated
public void reshape(int x, int y, int w, int h) {
super.reshape(x, y, w, h);
}
/** {@collect.stats}
* Stores the bounds of this component into "return value"
* <code>rv</code> and returns <code>rv</code>.
* If <code>rv</code> is <code>null</code> a new <code>Rectangle</code>
* is allocated. This version of <code>getBounds</code> is useful
* if the caller wants to avoid allocating a new <code>Rectangle</code>
* object on the heap.
*
* @param rv the return value, modified to the component's bounds
* @return <code>rv</code>; if <code>rv</code> is <code>null</code>
* return a newly created <code>Rectangle</code> with this
* component's bounds
*/
public Rectangle getBounds(Rectangle rv) {
if (rv == null) {
return new Rectangle(getX(), getY(), getWidth(), getHeight());
}
else {
rv.setBounds(getX(), getY(), getWidth(), getHeight());
return rv;
}
}
/** {@collect.stats}
* Stores the width/height of this component into "return value"
* <code>rv</code> and returns <code>rv</code>.
* If <code>rv</code> is <code>null</code> a new <code>Dimension</code>
* object is allocated. This version of <code>getSize</code>
* is useful if the caller wants to avoid allocating a new
* <code>Dimension</code> object on the heap.
*
* @param rv the return value, modified to the component's size
* @return <code>rv</code>
*/
public Dimension getSize(Dimension rv) {
if (rv == null) {
return new Dimension(getWidth(), getHeight());
}
else {
rv.setSize(getWidth(), getHeight());
return rv;
}
}
/** {@collect.stats}
* Stores the x,y origin of this component into "return value"
* <code>rv</code> and returns <code>rv</code>.
* If <code>rv</code> is <code>null</code> a new <code>Point</code>
* is allocated. This version of <code>getLocation</code> is useful
* if the caller wants to avoid allocating a new <code>Point</code>
* object on the heap.
*
* @param rv the return value, modified to the component's location
* @return <code>rv</code>
*/
public Point getLocation(Point rv) {
if (rv == null) {
return new Point(getX(), getY());
}
else {
rv.setLocation(getX(), getY());
return rv;
}
}
/** {@collect.stats}
* Returns the current x coordinate of the component's origin.
* This method is preferable to writing
* <code>component.getBounds().x</code>, or
* <code>component.getLocation().x</code> because it doesn't cause any
* heap allocations.
*
* @return the current x coordinate of the component's origin
*/
public int getX() { return super.getX(); }
/** {@collect.stats}
* Returns the current y coordinate of the component's origin.
* This method is preferable to writing
* <code>component.getBounds().y</code>, or
* <code>component.getLocation().y</code> because it doesn't cause any
* heap allocations.
*
* @return the current y coordinate of the component's origin
*/
public int getY() { return super.getY(); }
/** {@collect.stats}
* Returns the current width of this component.
* This method is preferable to writing
* <code>component.getBounds().width</code>, or
* <code>component.getSize().width</code> because it doesn't cause any
* heap allocations.
*
* @return the current width of this component
*/
public int getWidth() { return super.getWidth(); }
/** {@collect.stats}
* Returns the current height of this component.
* This method is preferable to writing
* <code>component.getBounds().height</code>, or
* <code>component.getSize().height</code> because it doesn't cause any
* heap allocations.
*
* @return the current height of this component
*/
public int getHeight() { return super.getHeight(); }
/** {@collect.stats}
* Returns true if this component is completely opaque.
* <p>
* An opaque component paints every pixel within its
* rectangular bounds. A non-opaque component paints only a subset of
* its pixels or none at all, allowing the pixels underneath it to
* "show through". Therefore, a component that does not fully paint
* its pixels provides a degree of transparency.
* <p>
* Subclasses that guarantee to always completely paint their contents
* should override this method and return true.
*
* @return true if this component is completely opaque
* @see #setOpaque
*/
public boolean isOpaque() {
return getFlag(IS_OPAQUE);
}
/** {@collect.stats}
* If true the component paints every pixel within its bounds.
* Otherwise, the component may not paint some or all of its
* pixels, allowing the underlying pixels to show through.
* <p>
* The default value of this property is false for <code>JComponent</code>.
* However, the default value for this property on most standard
* <code>JComponent</code> subclasses (such as <code>JButton</code> and
* <code>JTree</code>) is look-and-feel dependent.
*
* @param isOpaque true if this component should be opaque
* @see #isOpaque
* @beaninfo
* bound: true
* expert: true
* description: The component's opacity
*/
public void setOpaque(boolean isOpaque) {
boolean oldValue = getFlag(IS_OPAQUE);
setFlag(IS_OPAQUE, isOpaque);
setFlag(OPAQUE_SET, true);
firePropertyChange("opaque", oldValue, isOpaque);
}
/** {@collect.stats}
* If the specified rectangle is completely obscured by any of this
* component's opaque children then returns true. Only direct children
* are considered, more distant descendants are ignored. A
* <code>JComponent</code> is opaque if
* <code>JComponent.isOpaque()</code> returns true, other lightweight
* components are always considered transparent, and heavyweight components
* are always considered opaque.
*
* @param x x value of specified rectangle
* @param y y value of specified rectangle
* @param width width of specified rectangle
* @param height height of specified rectangle
* @return true if the specified rectangle is obscured by an opaque child
*/
boolean rectangleIsObscured(int x,int y,int width,int height)
{
int numChildren = getComponentCount();
for(int i = 0; i < numChildren; i++) {
Component child = getComponent(i);
int cx, cy, cw, ch;
cx = child.getX();
cy = child.getY();
cw = child.getWidth();
ch = child.getHeight();
if (x >= cx && (x + width) <= (cx + cw) &&
y >= cy && (y + height) <= (cy + ch) && child.isVisible()) {
if(child instanceof JComponent) {
// System.out.println("A) checking opaque: " + ((JComponent)child).isOpaque() + " " + child);
// System.out.print("B) ");
// Thread.dumpStack();
return ((JComponent)child).isOpaque();
} else {
/** {@collect.stats} Sometimes a heavy weight can have a bound larger than its peer size
* so we should always draw under heavy weights
*/
return false;
}
}
}
return false;
}
/** {@collect.stats}
* Returns the <code>Component</code>'s "visible rect rectangle" - the
* intersection of the visible rectangles for the component <code>c</code>
* and all of its ancestors. The return value is stored in
* <code>visibleRect</code>.
*
* @param c the component
* @param visibleRect a <code>Rectangle</code> computed as the
* intersection of all visible rectangles for the component
* <code>c</code> and all of its ancestors -- this is the
* return value for this method
* @see #getVisibleRect
*/
static final void computeVisibleRect(Component c, Rectangle visibleRect) {
Container p = c.getParent();
Rectangle bounds = c.getBounds();
if (p == null || p instanceof Window || p instanceof Applet) {
visibleRect.setBounds(0, 0, bounds.width, bounds.height);
} else {
computeVisibleRect(p, visibleRect);
visibleRect.x -= bounds.x;
visibleRect.y -= bounds.y;
SwingUtilities.computeIntersection(0,0,bounds.width,bounds.height,visibleRect);
}
}
/** {@collect.stats}
* Returns the <code>Component</code>'s "visible rect rectangle" - the
* intersection of the visible rectangles for this component
* and all of its ancestors. The return value is stored in
* <code>visibleRect</code>.
*
* @param visibleRect a <code>Rectangle</code> computed as the
* intersection of all visible rectangles for this
* component and all of its ancestors -- this is the return
* value for this method
* @see #getVisibleRect
*/
public void computeVisibleRect(Rectangle visibleRect) {
computeVisibleRect(this, visibleRect);
}
/** {@collect.stats}
* Returns the <code>Component</code>'s "visible rectangle" - the
* intersection of this component's visible rectangle,
* <code>new Rectangle(0, 0, getWidth(), getHeight())</code>,
* and all of its ancestors' visible rectangles.
*
* @return the visible rectangle
*/
public Rectangle getVisibleRect() {
Rectangle visibleRect = new Rectangle();
computeVisibleRect(visibleRect);
return visibleRect;
}
/** {@collect.stats}
* Support for reporting bound property changes for boolean properties.
* This method can be called when a bound property has changed and it will
* send the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
*
* @param propertyName the property whose value has changed
* @param oldValue the property's previous value
* @param newValue the property's new value
*/
public void firePropertyChange(String propertyName,
boolean oldValue, boolean newValue) {
super.firePropertyChange(propertyName, oldValue, newValue);
}
/** {@collect.stats}
* Support for reporting bound property changes for integer properties.
* This method can be called when a bound property has changed and it will
* send the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
*
* @param propertyName the property whose value has changed
* @param oldValue the property's previous value
* @param newValue the property's new value
*/
public void firePropertyChange(String propertyName,
int oldValue, int newValue) {
super.firePropertyChange(propertyName, oldValue, newValue);
}
// XXX This method is implemented as a workaround to a JLS issue with ambiguous
// methods. This should be removed once 4758654 is resolved.
public void firePropertyChange(String propertyName, char oldValue, char newValue) {
super.firePropertyChange(propertyName, oldValue, newValue);
}
/** {@collect.stats}
* Supports reporting constrained property changes.
* This method can be called when a constrained property has changed
* and it will send the appropriate <code>PropertyChangeEvent</code>
* to any registered <code>VetoableChangeListeners</code>.
*
* @param propertyName the name of the property that was listened on
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @exception PropertyVetoException when the attempt to set the
* property is vetoed by the component
*/
protected void fireVetoableChange(String propertyName, Object oldValue, Object newValue)
throws java.beans.PropertyVetoException
{
if (vetoableChangeSupport == null) {
return;
}
vetoableChangeSupport.fireVetoableChange(propertyName, oldValue, newValue);
}
/** {@collect.stats}
* Adds a <code>VetoableChangeListener</code> to the listener list.
* The listener is registered for all properties.
*
* @param listener the <code>VetoableChangeListener</code> to be added
*/
public synchronized void addVetoableChangeListener(VetoableChangeListener listener) {
if (vetoableChangeSupport == null) {
vetoableChangeSupport = new java.beans.VetoableChangeSupport(this);
}
vetoableChangeSupport.addVetoableChangeListener(listener);
}
/** {@collect.stats}
* Removes a <code>VetoableChangeListener</code> from the listener list.
* This removes a <code>VetoableChangeListener</code> that was registered
* for all properties.
*
* @param listener the <code>VetoableChangeListener</code> to be removed
*/
public synchronized void removeVetoableChangeListener(VetoableChangeListener listener) {
if (vetoableChangeSupport == null) {
return;
}
vetoableChangeSupport.removeVetoableChangeListener(listener);
}
/** {@collect.stats}
* Returns an array of all the vetoable change listeners
* registered on this component.
*
* @return all of the component's <code>VetoableChangeListener</code>s
* or an empty
* array if no vetoable change listeners are currently registered
*
* @see #addVetoableChangeListener
* @see #removeVetoableChangeListener
*
* @since 1.4
*/
public synchronized VetoableChangeListener[] getVetoableChangeListeners() {
if (vetoableChangeSupport == null) {
return new VetoableChangeListener[0];
}
return vetoableChangeSupport.getVetoableChangeListeners();
}
/** {@collect.stats}
* Returns the top-level ancestor of this component (either the
* containing <code>Window</code> or <code>Applet</code>),
* or <code>null</code> if this component has not
* been added to any container.
*
* @return the top-level <code>Container</code> that this component is in,
* or <code>null</code> if not in any container
*/
public Container getTopLevelAncestor() {
for(Container p = this; p != null; p = p.getParent()) {
if(p instanceof Window || p instanceof Applet) {
return p;
}
}
return null;
}
private AncestorNotifier getAncestorNotifier() {
return (AncestorNotifier)
getClientProperty(JComponent_ANCESTOR_NOTIFIER);
}
/** {@collect.stats}
* Registers <code>listener</code> so that it will receive
* <code>AncestorEvents</code> when it or any of its ancestors
* move or are made visible or invisible.
* Events are also sent when the component or its ancestors are added
* or removed from the containment hierarchy.
*
* @param listener the <code>AncestorListener</code> to register
* @see AncestorEvent
*/
public void addAncestorListener(AncestorListener listener) {
AncestorNotifier ancestorNotifier = getAncestorNotifier();
if (ancestorNotifier == null) {
ancestorNotifier = new AncestorNotifier(this);
putClientProperty(JComponent_ANCESTOR_NOTIFIER,
ancestorNotifier);
}
ancestorNotifier.addAncestorListener(listener);
}
/** {@collect.stats}
* Unregisters <code>listener</code> so that it will no longer receive
* <code>AncestorEvents</code>.
*
* @param listener the <code>AncestorListener</code> to be removed
* @see #addAncestorListener
*/
public void removeAncestorListener(AncestorListener listener) {
AncestorNotifier ancestorNotifier = getAncestorNotifier();
if (ancestorNotifier == null) {
return;
}
ancestorNotifier.removeAncestorListener(listener);
if (ancestorNotifier.listenerList.getListenerList().length == 0) {
ancestorNotifier.removeAllListeners();
putClientProperty(JComponent_ANCESTOR_NOTIFIER, null);
}
}
/** {@collect.stats}
* Returns an array of all the ancestor listeners
* registered on this component.
*
* @return all of the component's <code>AncestorListener</code>s
* or an empty
* array if no ancestor listeners are currently registered
*
* @see #addAncestorListener
* @see #removeAncestorListener
*
* @since 1.4
*/
public AncestorListener[] getAncestorListeners() {
AncestorNotifier ancestorNotifier = getAncestorNotifier();
if (ancestorNotifier == null) {
return new AncestorListener[0];
}
return ancestorNotifier.getAncestorListeners();
}
/** {@collect.stats}
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this <code>JComponent</code>.
* <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>JComponent</code> <code>c</code>
* for its mouse listeners with the following code:
* <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.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 component,
* 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>
*
* @since 1.3
*
* @see #getVetoableChangeListeners
* @see #getAncestorListeners
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
T[] result;
if (listenerType == AncestorListener.class) {
// AncestorListeners are handled by the AncestorNotifier
result = (T[])getAncestorListeners();
}
else if (listenerType == VetoableChangeListener.class) {
// VetoableChangeListeners are handled by VetoableChangeSupport
result = (T[])getVetoableChangeListeners();
}
else if (listenerType == PropertyChangeListener.class) {
// PropertyChangeListeners are handled by PropertyChangeSupport
result = (T[])getPropertyChangeListeners();
}
else {
result = (T[])listenerList.getListeners(listenerType);
}
if (result.length == 0) {
return super.getListeners(listenerType);
}
return result;
}
/** {@collect.stats}
* Notifies this component that it now has a parent component.
* When this method is invoked, the chain of parent components is
* set up with <code>KeyboardAction</code> event listeners.
*
* @see #registerKeyboardAction
*/
public void addNotify() {
super.addNotify();
firePropertyChange("ancestor", null, getParent());
registerWithKeyboardManager(false);
registerNextFocusableComponent();
}
/** {@collect.stats}
* Notifies this component that it no longer has a parent component.
* When this method is invoked, any <code>KeyboardAction</code>s
* set up in the the chain of parent components are removed.
*
* @see #registerKeyboardAction
*/
public void removeNotify() {
super.removeNotify();
// This isn't strictly correct. The event shouldn't be
// fired until *after* the parent is set to null. But
// we only get notified before that happens
firePropertyChange("ancestor", getParent(), null);
unregisterWithKeyboardManager();
deregisterNextFocusableComponent();
if (getCreatedDoubleBuffer()) {
RepaintManager.currentManager(this).resetDoubleBuffer();
setCreatedDoubleBuffer(false);
}
if (autoscrolls) {
Autoscroller.stop(this);
}
}
/** {@collect.stats}
* Adds the specified region to the dirty region list if the component
* is showing. The component will be repainted after all of the
* currently pending events have been dispatched.
*
* @param tm this parameter is not used
* @param x the x value of the dirty region
* @param y the y value of the dirty region
* @param width the width of the dirty region
* @param height the height of the dirty region
* @see java.awt.Component#isShowing
* @see RepaintManager#addDirtyRegion
*/
public void repaint(long tm, int x, int y, int width, int height) {
RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width, height);
}
/** {@collect.stats}
* Adds the specified region to the dirty region list if the component
* is showing. The component will be repainted after all of the
* currently pending events have been dispatched.
*
* @param r a <code>Rectangle</code> containing the dirty region
* @see java.awt.Component#isShowing
* @see RepaintManager#addDirtyRegion
*/
public void repaint(Rectangle r) {
repaint(0,r.x,r.y,r.width,r.height);
}
/** {@collect.stats}
* Supports deferred automatic layout.
* <p>
* Calls <code>invalidate</code> and then adds this component's
* <code>validateRoot</code> to a list of components that need to be
* validated. Validation will occur after all currently pending
* events have been dispatched. In other words after this method
* is called, the first validateRoot (if any) found when walking
* up the containment hierarchy of this component will be validated.
* By default, <code>JRootPane</code>, <code>JScrollPane</code>,
* and <code>JTextField</code> return true
* from <code>isValidateRoot</code>.
* <p>
* This method will automatically be called on this component
* when a property value changes such that size, location, or
* internal layout of this component has been affected. This automatic
* updating differs from the AWT because programs generally no
* longer need to invoke <code>validate</code> to get the contents of the
* GUI to update.
* <p>
*
* @see java.awt.Component#invalidate
* @see java.awt.Container#validate
* @see #isValidateRoot
* @see RepaintManager#addInvalidComponent
*/
public void revalidate() {
if (getParent() == null) {
// Note: We don't bother invalidating here as once added
// to a valid parent invalidate will be invoked (addImpl
// invokes addNotify which will invoke invalidate on the
// new Component). Also, if we do add a check to isValid
// here it can potentially be called before the constructor
// which was causing some people grief.
return;
}
if (SwingUtilities.isEventDispatchThread()) {
invalidate();
RepaintManager.currentManager(this).addInvalidComponent(this);
}
else {
// To avoid a flood of Runnables when constructing GUIs off
// the EDT, a flag is maintained as to whether or not
// a Runnable has been scheduled.
synchronized(this) {
if (getFlag(REVALIDATE_RUNNABLE_SCHEDULED)) {
return;
}
setFlag(REVALIDATE_RUNNABLE_SCHEDULED, true);
}
Runnable callRevalidate = new Runnable() {
public void run() {
synchronized(JComponent.this) {
setFlag(REVALIDATE_RUNNABLE_SCHEDULED, false);
}
revalidate();
}
};
SwingUtilities.invokeLater(callRevalidate);
}
}
/** {@collect.stats}
* If this method returns true, <code>revalidate</code> calls by
* descendants of this component will cause the entire tree
* beginning with this root to be validated.
* Returns false by default. <code>JScrollPane</code> overrides
* this method and returns true.
*
* @return always returns false
* @see #revalidate
* @see java.awt.Component#invalidate
* @see java.awt.Container#validate
*/
public boolean isValidateRoot() {
return false;
}
/** {@collect.stats}
* Returns true if this component tiles its children -- that is, if
* it can guarantee that the children will not overlap. The
* repainting system is substantially more efficient in this
* common case. <code>JComponent</code> subclasses that can't make this
* guarantee, such as <code>JLayeredPane</code>,
* should override this method to return false.
*
* @return always returns true
*/
public boolean isOptimizedDrawingEnabled() {
return true;
}
/** {@collect.stats}
* Returns true if a paint triggered on a child component should cause
* painting to originate from this Component, or one of its ancestors.
*
* @return true if painting should originate from this Component or
* one of its ancestors.
*/
boolean isPaintingOrigin() {
return false;
}
/** {@collect.stats}
* Paints the specified region in this component and all of its
* descendants that overlap the region, immediately.
* <p>
* It's rarely necessary to call this method. In most cases it's
* more efficient to call repaint, which defers the actual painting
* and can collapse redundant requests into a single paint call.
* This method is useful if one needs to update the display while
* the current event is being dispatched.
*
* @param x the x value of the region to be painted
* @param y the y value of the region to be painted
* @param w the width of the region to be painted
* @param h the height of the region to be painted
* @see #repaint
*/
public void paintImmediately(int x,int y,int w, int h) {
Component c = this;
Component parent;
if(!isShowing()) {
return;
}
while(!((JComponent)c).isOpaque()) {
parent = c.getParent();
if(parent != null) {
x += c.getX();
y += c.getY();
c = parent;
} else {
break;
}
if(!(c instanceof JComponent)) {
break;
}
}
if(c instanceof JComponent) {
((JComponent)c)._paintImmediately(x,y,w,h);
} else {
c.repaint(x,y,w,h);
}
}
/** {@collect.stats}
* Paints the specified region now.
*
* @param r a <code>Rectangle</code> containing the region to be painted
*/
public void paintImmediately(Rectangle r) {
paintImmediately(r.x,r.y,r.width,r.height);
}
/** {@collect.stats}
* Returns whether this component should be guaranteed to be on top.
* For example, it would make no sense for <code>Menu</code>s to pop up
* under another component, so they would always return true.
* Most components will want to return false, hence that is the default.
*
* @return always returns false
*/
// package private
boolean alwaysOnTop() {
return false;
}
void setPaintingChild(Component paintingChild) {
this.paintingChild = paintingChild;
}
void _paintImmediately(int x, int y, int w, int h) {
Graphics g;
Container c;
Rectangle b;
int tmpX, tmpY, tmpWidth, tmpHeight;
int offsetX=0,offsetY=0;
boolean hasBuffer = false;
JComponent bufferedComponent = null;
JComponent paintingComponent = this;
RepaintManager repaintManager = RepaintManager.currentManager(this);
// parent Container's up to Window or Applet. First container is
// the direct parent. Note that in testing it was faster to
// alloc a new Vector vs keeping a stack of them around, and gc
// seemed to have a minimal effect on this.
java.util.List<Component> path = new java.util.ArrayList<Component>(7);
int pIndex = -1;
int pCount = 0;
tmpX = tmpY = tmpWidth = tmpHeight = 0;
Rectangle paintImmediatelyClip = fetchRectangle();
paintImmediatelyClip.x = x;
paintImmediatelyClip.y = y;
paintImmediatelyClip.width = w;
paintImmediatelyClip.height = h;
// System.out.println("1) ************* in _paintImmediately for " + this);
boolean ontop = alwaysOnTop() && isOpaque();
if (ontop) {
SwingUtilities.computeIntersection(0, 0, getWidth(), getHeight(),
paintImmediatelyClip);
if (paintImmediatelyClip.width == 0) {
recycleRectangle(paintImmediatelyClip);
return;
}
}
Component child;
for (c = this, child = null;
c != null && !(c instanceof Window) && !(c instanceof Applet);
child = c, c = c.getParent()) {
JComponent jc = (c instanceof JComponent) ? (JComponent)c :
null;
path.add(c);
if(!ontop && jc != null && !jc.isOptimizedDrawingEnabled()) {
boolean resetPC;
// Children of c may overlap, three possible cases for the
// painting region:
// . Completely obscured by an opaque sibling, in which
// case there is no need to paint.
// . Partially obscured by a sibling: need to start
// painting from c.
// . Otherwise we aren't obscured and thus don't need to
// start painting from parent.
if (c != this) {
if (jc.isPaintingOrigin()) {
resetPC = true;
}
else {
Component[] children = c.getComponents();
int i = 0;
for (; i<children.length; i++) {
if (children[i] == child) break;
}
switch (jc.getObscuredState(i,
paintImmediatelyClip.x,
paintImmediatelyClip.y,
paintImmediatelyClip.width,
paintImmediatelyClip.height)) {
case NOT_OBSCURED:
resetPC = false;
break;
case COMPLETELY_OBSCURED:
recycleRectangle(paintImmediatelyClip);
return;
default:
resetPC = true;
break;
}
}
}
else {
resetPC = false;
}
if (resetPC) {
// Get rid of any buffer since we draw from here and
// we might draw something larger
paintingComponent = jc;
pIndex = pCount;
offsetX = offsetY = 0;
hasBuffer = false;
}
}
pCount++;
// look to see if the parent (and therefor this component)
// is double buffered
if(repaintManager.isDoubleBufferingEnabled() && jc != null &&
jc.isDoubleBuffered()) {
hasBuffer = true;
bufferedComponent = jc;
}
// if we aren't on top, include the parent's clip
if (!ontop) {
int bx = c.getX();
int by = c.getY();
tmpWidth = c.getWidth();
tmpHeight = c.getHeight();
SwingUtilities.computeIntersection(tmpX,tmpY,tmpWidth,tmpHeight,paintImmediatelyClip);
paintImmediatelyClip.x += bx;
paintImmediatelyClip.y += by;
offsetX += bx;
offsetY += by;
}
}
// If the clip width or height is negative, don't bother painting
if(c == null || c.getPeer() == null ||
paintImmediatelyClip.width <= 0 ||
paintImmediatelyClip.height <= 0) {
recycleRectangle(paintImmediatelyClip);
return;
}
paintingComponent.setFlag(IS_REPAINTING, true);
paintImmediatelyClip.x -= offsetX;
paintImmediatelyClip.y -= offsetY;
// Notify the Components that are going to be painted of the
// child component to paint to.
if(paintingComponent != this) {
Component comp;
int i = pIndex;
for(; i > 0 ; i--) {
comp = path.get(i);
if(comp instanceof JComponent) {
((JComponent)comp).setPaintingChild(path.get(i-1));
}
}
}
try {
g = safelyGetGraphics(paintingComponent, c);
try {
if (hasBuffer) {
RepaintManager rm = RepaintManager.currentManager(
bufferedComponent);
rm.beginPaint();
try {
rm.paint(paintingComponent, bufferedComponent, g,
paintImmediatelyClip.x,
paintImmediatelyClip.y,
paintImmediatelyClip.width,
paintImmediatelyClip.height);
} finally {
rm.endPaint();
}
}
else {
g.setClip(paintImmediatelyClip.x,paintImmediatelyClip.y,
paintImmediatelyClip.width,paintImmediatelyClip.height);
paintingComponent.paint(g);
}
} finally {
g.dispose();
}
}
finally {
// Reset the painting child for the parent components.
if(paintingComponent != this) {
Component comp;
int i = pIndex;
for(; i > 0 ; i--) {
comp = path.get(i);
if(comp instanceof JComponent) {
((JComponent)comp).setPaintingChild(null);
}
}
}
paintingComponent.setFlag(IS_REPAINTING, false);
}
recycleRectangle(paintImmediatelyClip);
}
/** {@collect.stats}
* Paints to the specified graphics. This does not set the clip and it
* does not adjust the Graphics in anyway, callers must do that first.
* This method is package-private for RepaintManager.PaintManager and
* its subclasses to call, it is NOT intended for general use outside
* of that.
*/
void paintToOffscreen(Graphics g, int x, int y, int w, int h, int maxX,
int maxY) {
try {
setFlag(ANCESTOR_USING_BUFFER, true);
if ((y + h) < maxY || (x + w) < maxX) {
setFlag(IS_PAINTING_TILE, true);
}
if (getFlag(IS_REPAINTING)) {
// Called from paintImmediately (RepaintManager) to fill
// repaint request
paint(g);
} else {
// Called from paint() (AWT) to repair damage
if(!rectangleIsObscured(x, y, w, h)) {
paintComponent(g);
paintBorder(g);
}
paintChildren(g);
}
} finally {
setFlag(ANCESTOR_USING_BUFFER, false);
setFlag(IS_PAINTING_TILE, false);
}
}
/** {@collect.stats}
* Returns whether or not the region of the specified component is
* obscured by a sibling.
*
* @return NOT_OBSCURED if non of the siblings above the Component obscure
* it, COMPLETELY_OBSCURED if one of the siblings completely
* obscures the Component or PARTIALLY_OBSCURED if the Comonent is
* only partially obscured.
*/
private int getObscuredState(int compIndex, int x, int y, int width,
int height) {
int retValue = NOT_OBSCURED;
Rectangle tmpRect = fetchRectangle();
for (int i = compIndex - 1 ; i >= 0 ; i--) {
Component sibling = getComponent(i);
if (!sibling.isVisible()) {
continue;
}
Rectangle siblingRect;
boolean opaque;
if (sibling instanceof JComponent) {
opaque = ((JComponent)sibling).isOpaque();
if (!opaque) {
if (retValue == PARTIALLY_OBSCURED) {
continue;
}
}
}
else {
opaque = true;
}
siblingRect = sibling.getBounds(tmpRect);
if (opaque && x >= siblingRect.x && (x + width) <=
(siblingRect.x + siblingRect.width) &&
y >= siblingRect.y && (y + height) <=
(siblingRect.y + siblingRect.height)) {
recycleRectangle(tmpRect);
return COMPLETELY_OBSCURED;
}
else if (retValue == NOT_OBSCURED &&
!((x + width <= siblingRect.x) ||
(y + height <= siblingRect.y) ||
(x >= siblingRect.x + siblingRect.width) ||
(y >= siblingRect.y + siblingRect.height))) {
retValue = PARTIALLY_OBSCURED;
}
}
recycleRectangle(tmpRect);
return retValue;
}
/** {@collect.stats}
* Returns true, which implies that before checking if a child should
* be painted it is first check that the child is not obscured by another
* sibling. This is only checked if <code>isOptimizedDrawingEnabled</code>
* returns false.
*
* @return always returns true
*/
boolean checkIfChildObscuredBySibling() {
return true;
}
private void setFlag(int aFlag, boolean aValue) {
if(aValue) {
flags |= (1 << aFlag);
} else {
flags &= ~(1 << aFlag);
}
}
private boolean getFlag(int aFlag) {
int mask = (1 << aFlag);
return ((flags & mask) == mask);
}
// These functions must be static so that they can be called from
// subclasses inside the package, but whose inheritance hierarhcy includes
// classes outside of the package below JComponent (e.g., JTextArea).
static void setWriteObjCounter(JComponent comp, byte count) {
comp.flags = (comp.flags & ~(0xFF << WRITE_OBJ_COUNTER_FIRST)) |
(count << WRITE_OBJ_COUNTER_FIRST);
}
static byte getWriteObjCounter(JComponent comp) {
return (byte)((comp.flags >> WRITE_OBJ_COUNTER_FIRST) & 0xFF);
}
/** {@collect.stats} Buffering **/
/** {@collect.stats}
* Sets whether this component should use a buffer to paint.
* If set to true, all the drawing from this component will be done
* in an offscreen painting buffer. The offscreen painting buffer will
* the be copied onto the screen.
* If a <code>Component</code> is buffered and one of its ancestor
* is also buffered, the ancestor buffer will be used.
*
* @param aFlag if true, set this component to be double buffered
*/
public void setDoubleBuffered(boolean aFlag) {
setFlag(IS_DOUBLE_BUFFERED,aFlag);
}
/** {@collect.stats}
* Returns whether this component should use a buffer to paint.
*
* @return true if this component is double buffered, otherwise false
*/
public boolean isDoubleBuffered() {
return getFlag(IS_DOUBLE_BUFFERED);
}
/** {@collect.stats}
* Returns the <code>JRootPane</code> ancestor for this component.
*
* @return the <code>JRootPane</code> that contains this component,
* or <code>null</code> if no <code>JRootPane</code> is found
*/
public JRootPane getRootPane() {
return SwingUtilities.getRootPane(this);
}
/** {@collect.stats} Serialization **/
/** {@collect.stats}
* This is called from Component by way of reflection. Do NOT change
* the name unless you change the code in Component as well.
*/
void compWriteObjectNotify() {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, (byte)(count + 1));
if (count != 0) {
return;
}
uninstallUIAndProperties();
/* JTableHeader is in a separate package, which prevents it from
* being able to override this package-private method the way the
* other components can. We don't want to make this method protected
* because it would introduce public-api for a less-than-desirable
* serialization scheme, so we compromise with this 'instanceof' hack
* for now.
*/
if (getToolTipText() != null ||
this instanceof javax.swing.table.JTableHeader) {
ToolTipManager.sharedInstance().unregisterComponent(JComponent.this);
}
}
/** {@collect.stats}
* This object is the <code>ObjectInputStream</code> callback
* that's called after a complete graph of objects (including at least
* one <code>JComponent</code>) has been read.
* It sets the UI property of each Swing component
* that was read to the current default with <code>updateUI</code>.
* <p>
* As each component is read in we keep track of the current set of
* root components here, in the roots vector. Note that there's only one
* <code>ReadObjectCallback</code> per <code>ObjectInputStream</code>,
* they're stored in the static <code>readObjectCallbacks</code>
* hashtable.
*
* @see java.io.ObjectInputStream#registerValidation
* @see SwingUtilities#updateComponentTreeUI
*/
private class ReadObjectCallback implements ObjectInputValidation
{
private final Vector roots = new Vector(1);
private final ObjectInputStream inputStream;
ReadObjectCallback(ObjectInputStream s) throws Exception {
inputStream = s;
s.registerValidation(this, 0);
}
/** {@collect.stats}
* This is the method that's called after the entire graph
* of objects has been read in. It initializes
* the UI property of all of the copmonents with
* <code>SwingUtilities.updateComponentTreeUI</code>.
*/
public void validateObject() throws InvalidObjectException {
try {
for(int i = 0; i < roots.size(); i++) {
JComponent root = (JComponent)(roots.elementAt(i));
SwingUtilities.updateComponentTreeUI(root);
}
}
finally {
readObjectCallbacks.remove(inputStream);
}
}
/** {@collect.stats}
* If <code>c</code> isn't a descendant of a component we've already
* seen, then add it to the roots <code>Vector</code>.
*
* @param c the <code>JComponent</code> to add
*/
private void registerComponent(JComponent c)
{
/* If the Component c is a descendant of one of the
* existing roots (or it IS an existing root), we're done.
*/
for(int i = 0; i < roots.size(); i++) {
JComponent root = (JComponent)roots.elementAt(i);
for(Component p = c; p != null; p = p.getParent()) {
if (p == root) {
return;
}
}
}
/* Otherwise: if Component c is an ancestor of any of the
* existing roots then remove them and add c (the "new root")
* to the roots vector.
*/
for(int i = 0; i < roots.size(); i++) {
JComponent root = (JComponent)roots.elementAt(i);
for(Component p = root.getParent(); p != null; p = p.getParent()) {
if (p == c) {
roots.removeElementAt(i--); // !!
break;
}
}
}
roots.addElement(c);
}
}
/** {@collect.stats}
* We use the <code>ObjectInputStream</code> "registerValidation"
* callback to update the UI for the entire tree of components
* after they've all been read in.
*
* @param s the <code>ObjectInputStream</code> from which to read
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
/* If there's no ReadObjectCallback for this stream yet, that is, if
* this is the first call to JComponent.readObject() for this
* graph of objects, then create a callback and stash it
* in the readObjectCallbacks table. Note that the ReadObjectCallback
* constructor takes care of calling s.registerValidation().
*/
ReadObjectCallback cb = (ReadObjectCallback)(readObjectCallbacks.get(s));
if (cb == null) {
try {
readObjectCallbacks.put(s, cb = new ReadObjectCallback(s));
}
catch (Exception e) {
throw new IOException(e.toString());
}
}
cb.registerComponent(this);
// Read back the client properties.
int cpCount = s.readInt();
if (cpCount > 0) {
clientProperties = new ArrayTable();
for (int counter = 0; counter < cpCount; counter++) {
clientProperties.put(s.readObject(),
s.readObject());
}
}
if (getToolTipText() != null) {
ToolTipManager.sharedInstance().registerComponent(this);
}
setWriteObjCounter(this, (byte)0);
}
/** {@collect.stats}
* Before writing a <code>JComponent</code> to an
* <code>ObjectOutputStream</code> we temporarily uninstall its UI.
* This is tricky to do because we want to uninstall
* the UI before any of the <code>JComponent</code>'s children
* (or its <code>LayoutManager</code> etc.) are written,
* and we don't want to restore the UI until the most derived
* <code>JComponent</code> subclass has been been stored.
*
* @param s the <code>ObjectOutputStream</code> in which to write
*/
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);
}
}
ArrayTable.writeArrayTable(s, clientProperties);
}
/** {@collect.stats}
* Returns a string representation of this <code>JComponent</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>JComponent</code>
*/
protected String paramString() {
String preferredSizeString = (isPreferredSizeSet() ?
getPreferredSize().toString() : "");
String minimumSizeString = (isMinimumSizeSet() ?
getMinimumSize().toString() : "");
String maximumSizeString = (isMaximumSizeSet() ?
getMaximumSize().toString() : "");
String borderString = (border == null ? ""
: (border == this ? "this" : border.toString()));
return super.paramString() +
",alignmentX=" + alignmentX +
",alignmentY=" + alignmentY +
",border=" + borderString +
",flags=" + flags + // should beef this up a bit
",maximumSize=" + maximumSizeString +
",minimumSize=" + minimumSizeString +
",preferredSize=" + preferredSizeString;
}
}
|
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;
import java.awt.*;
import java.awt.image.*;
/** {@collect.stats} ImageObserver for DebugGraphics, used for images only.
*
* @author Dave Karlton
*/
class DebugGraphicsObserver implements ImageObserver {
int lastInfo;
synchronized boolean allBitsPresent() {
return (lastInfo & ImageObserver.ALLBITS) != 0;
}
synchronized boolean imageHasProblem() {
return ((lastInfo & ImageObserver.ERROR) != 0 ||
(lastInfo & ImageObserver.ABORT) != 0);
}
public synchronized boolean imageUpdate(Image img, int infoflags,
int x, int y,
int width, int height) {
lastInfo = infoflags;
return true;
}
}
|
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.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* <code>JSeparator</code> provides a general purpose component for
* implementing divider lines - most commonly used as a divider
* between menu items that breaks them up into logical groupings.
* Instead of using <code>JSeparator</code> directly,
* you can use the <code>JMenu</code> or <code>JPopupMenu</code>
* <code>addSeparator</code> method to create and add a separator.
* <code>JSeparator</code>s may also be used elsewhere in a GUI
* wherever a visual divider is useful.
*
* <p>
*
* For more information and examples 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 false
* description: A divider between menu items.
*
* @author Georges Saab
* @author Jeff Shapiro
*/
public class JSeparator extends JComponent implements SwingConstants, Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "SeparatorUI";
private int orientation = HORIZONTAL;
/** {@collect.stats} Creates a new horizontal separator. */
public JSeparator()
{
this( HORIZONTAL );
}
/** {@collect.stats}
* Creates a new separator with the specified horizontal or
* vertical orientation.
*
* @param orientation an integer specifying
* <code>SwingConstants.HORIZONTAL</code> or
* <code>SwingConstants.VERTICAL</code>
* @exception IllegalArgumentException if <code>orientation</code>
* is neither <code>SwingConstants.HORIZONTAL</code> nor
* <code>SwingConstants.VERTICAL</code>
*/
public JSeparator( int orientation )
{
checkOrientation( orientation );
this.orientation = orientation;
setFocusable(false);
updateUI();
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return the SeparatorUI object that renders this component
*/
public SeparatorUI getUI() {
return (SeparatorUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the SeparatorUI 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(SeparatorUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((SeparatorUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "SeparatorUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@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 the orientation of this separator.
*
* @return The value of the orientation property, one of the
* following constants defined in <code>SwingConstants</code>:
* <code>VERTICAL</code>, or
* <code>HORIZONTAL</code>.
*
* @see SwingConstants
* @see #setOrientation
*/
public int getOrientation() {
return this.orientation;
}
/** {@collect.stats}
* Sets the orientation of the separator.
* The default value of this property is HORIZONTAL.
* @param orientation either <code>SwingConstants.HORIZONTAL</code>
* or <code>SwingConstants.VERTICAL</code>
* @exception IllegalArgumentException if <code>orientation</code>
* is neither <code>SwingConstants.HORIZONTAL</code>
* nor <code>SwingConstants.VERTICAL</code>
*
* @see SwingConstants
* @see #getOrientation
* @beaninfo
* bound: true
* preferred: true
* enum: HORIZONTAL SwingConstants.HORIZONTAL
* VERTICAL SwingConstants.VERTICAL
* attribute: visualUpdate true
* description: The orientation of the separator.
*/
public void setOrientation( int orientation ) {
if (this.orientation == orientation) {
return;
}
int oldValue = this.orientation;
checkOrientation( orientation );
this.orientation = orientation;
firePropertyChange("orientation", oldValue, orientation);
revalidate();
repaint();
}
private void checkOrientation( int orientation )
{
switch ( orientation )
{
case VERTICAL:
case HORIZONTAL:
break;
default:
throw new IllegalArgumentException( "orientation must be one of: VERTICAL, HORIZONTAL" );
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JSeparator</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>JSeparator</code>
*/
protected String paramString() {
String orientationString = (orientation == HORIZONTAL ?
"HORIZONTAL" : "VERTICAL");
return super.paramString() +
",orientation=" + orientationString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JSeparator.
* For separators, the AccessibleContext takes the form of an
* AccessibleJSeparator.
* A new AccessibleJSeparator instance is created if necessary.
*
* @return an AccessibleJSeparator that serves as the
* AccessibleContext of this JSeparator
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJSeparator();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JSeparator</code> class. It provides an implementation of the
* Java Accessibility API appropriate to separator 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 AccessibleJSeparator extends AccessibleJComponent {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.SEPARATOR;
}
}
}
|
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;
import java.awt.Component;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.PaintEvent;
import java.security.AccessController;
import sun.awt.AppContext;
import sun.awt.SunToolkit;
import sun.awt.event.IgnorePaintEvent;
import sun.security.action.GetBooleanAction;
import sun.security.action.GetPropertyAction;
/** {@collect.stats}
* Swing's PaintEventDispatcher. If the component specified by the PaintEvent
* is a top level Swing component (JFrame, JWindow, JDialog, JApplet), this
* will forward the request to the RepaintManager for eventual painting.
*
*/
class SwingPaintEventDispatcher extends sun.awt.PaintEventDispatcher {
private static final boolean SHOW_FROM_DOUBLE_BUFFER;
private static final boolean ERASE_BACKGROUND;
static {
SHOW_FROM_DOUBLE_BUFFER = "true".equals(AccessController.doPrivileged(
new GetPropertyAction("swing.showFromDoubleBuffer", "true")));
ERASE_BACKGROUND = AccessController.doPrivileged(
new GetBooleanAction("swing.nativeErase"));
}
public PaintEvent createPaintEvent(Component component, int x, int y,
int w, int h) {
if (component instanceof RootPaneContainer) {
AppContext appContext = SunToolkit.targetToAppContext(component);
RepaintManager rm = RepaintManager.currentManager(appContext);
if (!SHOW_FROM_DOUBLE_BUFFER ||
!rm.show((Container)component, x, y, w, h)) {
rm.nativeAddDirtyRegion(appContext, (Container)component,
x, y, w, h);
}
// For backward compatibility generate an empty paint
// event. Not doing this broke parts of Netbeans.
return new IgnorePaintEvent(component, PaintEvent.PAINT,
new Rectangle(x, y, w, h));
}
else if (component instanceof SwingHeavyWeight) {
AppContext appContext = SunToolkit.targetToAppContext(component);
RepaintManager rm = RepaintManager.currentManager(appContext);
rm.nativeAddDirtyRegion(appContext, (Container)component,
x, y, w, h);
return new IgnorePaintEvent(component, PaintEvent.PAINT,
new Rectangle(x, y, w, h));
}
return super.createPaintEvent(component, x, y, w, h);
}
public boolean shouldDoNativeBackgroundErase(Component c) {
return ERASE_BACKGROUND || !(c instanceof RootPaneContainer);
}
public boolean queueSurfaceDataReplacing(Component c, Runnable r) {
if (c instanceof RootPaneContainer) {
AppContext appContext = SunToolkit.targetToAppContext(c);
RepaintManager.currentManager(appContext).
nativeQueueSurfaceDataRunnable(appContext, c, r);
return true;
}
return super.queueSurfaceDataReplacing(c, r);
}
}
|
Java
|
/*
* Copyright (c) 2000, 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;
import java.util.*;
import java.io.Serializable;
/** {@collect.stats}
* A <code>SpinnerModel</code> for sequences of numbers.
* The upper and lower bounds of the sequence are defined
* by properties called <code>minimum</code> and
* <code>maximum</code>. The size of the increase or decrease
* computed by the <code>nextValue</code> and
* <code>previousValue</code> methods is defined by a property called
* <code>stepSize</code>. The <code>minimum</code> and
* <code>maximum</code> properties can be <code>null</code>
* to indicate that the sequence has no lower or upper limit.
* All of the properties in this class are defined in terms of two
* generic types: <code>Number</code> and
* <code>Comparable</code>, so that all Java numeric types
* may be accommodated. Internally, there's only support for
* values whose type is one of the primitive <code>Number</code> types:
* <code>Double</code>, <code>Float</code>, <code>Long</code>,
* <code>Integer</code>, <code>Short</code>, or <code>Byte</code>.
* <p>
* To create a <code>SpinnerNumberModel</code> for the integer
* range zero to one hundred, with
* fifty as the initial value, one could write:
* <pre>
* Integer value = new Integer(50);
* Integer min = new Integer(0);
* Integer max = new Integer(100);
* Integer step = new Integer(1);
* SpinnerNumberModel model = new SpinnerNumberModel(value, min, max, step);
* int fifty = model.getNumber().intValue();
* </pre>
* <p>
* Spinners for integers and doubles are common, so special constructors
* for these cases are provided. For example to create the model in
* the previous example, one could also write:
* <pre>
* SpinnerNumberModel model = new SpinnerNumberModel(50, 0, 100, 1);
* </pre>
* <p>
* This model inherits a <code>ChangeListener</code>.
* The <code>ChangeListeners</code> are notified
* whenever the model's <code>value</code>, <code>stepSize</code>,
* <code>minimum</code>, or <code>maximum</code> properties changes.
*
* @see JSpinner
* @see SpinnerModel
* @see AbstractSpinnerModel
* @see SpinnerListModel
* @see SpinnerDateModel
*
* @author Hans Muller
* @since 1.4
*/
public class SpinnerNumberModel extends AbstractSpinnerModel implements Serializable
{
private Number stepSize, value;
private Comparable minimum, maximum;
/** {@collect.stats}
* Constructs a <code>SpinnerModel</code> that represents
* a closed sequence of
* numbers from <code>minimum</code> to <code>maximum</code>. The
* <code>nextValue</code> and <code>previousValue</code> methods
* compute elements of the sequence by adding or subtracting
* <code>stepSize</code> respectively. All of the parameters
* must be mutually <code>Comparable</code>, <code>value</code>
* and <code>stepSize</code> must be instances of <code>Integer</code>
* <code>Long</code>, <code>Float</code>, or <code>Double</code>.
* <p>
* The <code>minimum</code> and <code>maximum</code> parameters
* can be <code>null</code> to indicate that the range doesn't
* have an upper or lower bound.
* If <code>value</code> or <code>stepSize</code> is <code>null</code>,
* or if both <code>minimum</code> and <code>maximum</code>
* are specified and <code>mininum > maximum</code> then an
* <code>IllegalArgumentException</code> is thrown.
* Similarly if <code>(minimum <= value <= maximum</code>) is false,
* an <code>IllegalArgumentException</code> is thrown.
*
* @param value the current (non <code>null</code>) value of the model
* @param minimum the first number in the sequence or <code>null</code>
* @param maximum the last number in the sequence or <code>null</code>
* @param stepSize the difference between elements of the sequence
*
* @throws IllegalArgumentException if stepSize or value is
* <code>null</code> or if the following expression is false:
* <code>minimum <= value <= maximum</code>
*/
public SpinnerNumberModel(Number value, Comparable minimum, Comparable maximum, Number stepSize) {
if ((value == null) || (stepSize == null)) {
throw new IllegalArgumentException("value and stepSize must be non-null");
}
if (!(((minimum == null) || (minimum.compareTo(value) <= 0)) &&
((maximum == null) || (maximum.compareTo(value) >= 0)))) {
throw new IllegalArgumentException("(minimum <= value <= maximum) is false");
}
this.value = value;
this.minimum = minimum;
this.maximum = maximum;
this.stepSize = stepSize;
}
/** {@collect.stats}
* Constructs a <code>SpinnerNumberModel</code> with the specified
* <code>value</code>, <code>minimum</code>/<code>maximum</code> bounds,
* and <code>stepSize</code>.
*
* @param value the current value of the model
* @param minimum the first number in the sequence
* @param maximum the last number in the sequence
* @param stepSize the difference between elements of the sequence
* @throws IllegalArgumentException if the following expression is false:
* <code>minimum <= value <= maximum</code>
*/
public SpinnerNumberModel(int value, int minimum, int maximum, int stepSize) {
this(new Integer(value), new Integer(minimum), new Integer(maximum), new Integer(stepSize));
}
/** {@collect.stats}
* Constructs a <code>SpinnerNumberModel</code> with the specified
* <code>value</code>, <code>minimum</code>/<code>maximum</code> bounds,
* and <code>stepSize</code>.
*
* @param value the current value of the model
* @param minimum the first number in the sequence
* @param maximum the last number in the sequence
* @param stepSize the difference between elements of the sequence
* @throws IllegalArgumentException if the following expression is false:
* <code>minimum <= value <= maximum</code>
*/
public SpinnerNumberModel(double value, double minimum, double maximum, double stepSize) {
this(new Double(value), new Double(minimum), new Double(maximum), new Double(stepSize));
}
/** {@collect.stats}
* Constructs a <code>SpinnerNumberModel</code> with no
* <code>minimum</code> or <code>maximum</code> value,
* <code>stepSize</code> equal to one, and an initial value of zero.
*/
public SpinnerNumberModel() {
this(new Integer(0), null, null, new Integer(1));
}
/** {@collect.stats}
* Changes the lower bound for numbers in this sequence.
* If <code>minimum</code> is <code>null</code>,
* then there is no lower bound. No bounds checking is done here;
* the new <code>minimum</code> value may invalidate the
* <code>(minimum <= value <= maximum)</code>
* invariant enforced by the constructors. This is to simplify updating
* the model, naturally one should ensure that the invariant is true
* before calling the <code>getNextValue</code>,
* <code>getPreviousValue</code>, or <code>setValue</code> methods.
* <p>
* Typically this property is a <code>Number</code> of the same type
* as the <code>value</code> however it's possible to use any
* <code>Comparable</code> with a <code>compareTo</code>
* method for a <code>Number</code> with the same type as the value.
* For example if value was a <code>Long</code>,
* <code>minimum</code> might be a Date subclass defined like this:
* <pre>
* MyDate extends Date { // Date already implements Comparable
* public int compareTo(Long o) {
* long t = getTime();
* return (t < o.longValue() ? -1 : (t == o.longValue() ? 0 : 1));
* }
* }
* </pre>
* <p>
* This method fires a <code>ChangeEvent</code>
* if the <code>minimum</code> has changed.
*
* @param minimum a <code>Comparable</code> that has a
* <code>compareTo</code> method for <code>Number</code>s with
* the same type as <code>value</code>
* @see #getMinimum
* @see #setMaximum
* @see SpinnerModel#addChangeListener
*/
public void setMinimum(Comparable minimum) {
if ((minimum == null) ? (this.minimum != null) : !minimum.equals(this.minimum)) {
this.minimum = minimum;
fireStateChanged();
}
}
/** {@collect.stats}
* Returns the first number in this sequence.
*
* @return the value of the <code>minimum</code> property
* @see #setMinimum
*/
public Comparable getMinimum() {
return minimum;
}
/** {@collect.stats}
* Changes the upper bound for numbers in this sequence.
* If <code>maximum</code> is <code>null</code>, then there
* is no upper bound. No bounds checking is done here; the new
* <code>maximum</code> value may invalidate the
* <code>(minimum <= value < maximum)</code>
* invariant enforced by the constructors. This is to simplify updating
* the model, naturally one should ensure that the invariant is true
* before calling the <code>next</code>, <code>previous</code>,
* or <code>setValue</code> methods.
* <p>
* Typically this property is a <code>Number</code> of the same type
* as the <code>value</code> however it's possible to use any
* <code>Comparable</code> with a <code>compareTo</code>
* method for a <code>Number</code> with the same type as the value.
* See <a href="#setMinimum(java.lang.Comparable)">
* <code>setMinimum</code></a> for an example.
* <p>
* This method fires a <code>ChangeEvent</code> if the
* <code>maximum</code> has changed.
*
* @param maximum a <code>Comparable</code> that has a
* <code>compareTo</code> method for <code>Number</code>s with
* the same type as <code>value</code>
* @see #getMaximum
* @see #setMinimum
* @see SpinnerModel#addChangeListener
*/
public void setMaximum(Comparable maximum) {
if ((maximum == null) ? (this.maximum != null) : !maximum.equals(this.maximum)) {
this.maximum = maximum;
fireStateChanged();
}
}
/** {@collect.stats}
* Returns the last number in the sequence.
*
* @return the value of the <code>maximum</code> property
* @see #setMaximum
*/
public Comparable getMaximum() {
return maximum;
}
/** {@collect.stats}
* Changes the size of the value change computed by the
* <code>getNextValue</code> and <code>getPreviousValue</code>
* methods. An <code>IllegalArgumentException</code>
* is thrown if <code>stepSize</code> is <code>null</code>.
* <p>
* This method fires a <code>ChangeEvent</code> if the
* <code>stepSize</code> has changed.
*
* @param stepSize the size of the value change computed by the
* <code>getNextValue</code> and <code>getPreviousValue</code> methods
* @see #getNextValue
* @see #getPreviousValue
* @see #getStepSize
* @see SpinnerModel#addChangeListener
*/
public void setStepSize(Number stepSize) {
if (stepSize == null) {
throw new IllegalArgumentException("null stepSize");
}
if (!stepSize.equals(this.stepSize)) {
this.stepSize = stepSize;
fireStateChanged();
}
}
/** {@collect.stats}
* Returns the size of the value change computed by the
* <code>getNextValue</code>
* and <code>getPreviousValue</code> methods.
*
* @return the value of the <code>stepSize</code> property
* @see #setStepSize
*/
public Number getStepSize() {
return stepSize;
}
private Number incrValue(int dir)
{
Number newValue;
if ((value instanceof Float) || (value instanceof Double)) {
double v = value.doubleValue() + (stepSize.doubleValue() * (double)dir);
if (value instanceof Double) {
newValue = new Double(v);
}
else {
newValue = new Float(v);
}
}
else {
long v = value.longValue() + (stepSize.longValue() * (long)dir);
if (value instanceof Long) {
newValue = new Long(v);
}
else if (value instanceof Integer) {
newValue = new Integer((int)v);
}
else if (value instanceof Short) {
newValue = new Short((short)v);
}
else {
newValue = new Byte((byte)v);
}
}
if ((maximum != null) && (maximum.compareTo(newValue) < 0)) {
return null;
}
if ((minimum != null) && (minimum.compareTo(newValue) > 0)) {
return null;
}
else {
return newValue;
}
}
/** {@collect.stats}
* Returns the next number in the sequence.
*
* @return <code>value + stepSize</code> or <code>null</code> if the sum
* exceeds <code>maximum</code>.
*
* @see SpinnerModel#getNextValue
* @see #getPreviousValue
* @see #setStepSize
*/
public Object getNextValue() {
return incrValue(+1);
}
/** {@collect.stats}
* Returns the previous number in the sequence.
*
* @return <code>value - stepSize</code>, or
* <code>null</code> if the sum is less
* than <code>minimum</code>.
*
* @see SpinnerModel#getPreviousValue
* @see #getNextValue
* @see #setStepSize
*/
public Object getPreviousValue() {
return incrValue(-1);
}
/** {@collect.stats}
* Returns the value of the current element of the sequence.
*
* @return the value property
* @see #setValue
*/
public Number getNumber() {
return value;
}
/** {@collect.stats}
* Returns the value of the current element of the sequence.
*
* @return the value property
* @see #setValue
* @see #getNumber
*/
public Object getValue() {
return value;
}
/** {@collect.stats}
* Sets the current value for this sequence. If <code>value</code> is
* <code>null</code>, or not a <code>Number</code>, an
* <code>IllegalArgumentException</code> is thrown. No
* bounds checking is done here; the new value may invalidate the
* <code>(minimum <= value <= maximum)</code>
* invariant enforced by the constructors. It's also possible to set
* the value to be something that wouldn't naturally occur in the sequence,
* i.e. a value that's not modulo the <code>stepSize</code>.
* This is to simplify updating the model, and to accommodate
* spinners that don't want to restrict values that have been
* directly entered by the user. Naturally, one should ensure that the
* <code>(minimum <= value <= maximum)</code> invariant is true
* before calling the <code>next</code>, <code>previous</code>, or
* <code>setValue</code> methods.
* <p>
* This method fires a <code>ChangeEvent</code> if the value has changed.
*
* @param value the current (non <code>null</code>) <code>Number</code>
* for this sequence
* @throws IllegalArgumentException if <code>value</code> is
* <code>null</code> or not a <code>Number</code>
* @see #getNumber
* @see #getValue
* @see SpinnerModel#addChangeListener
*/
public void setValue(Object value) {
if ((value == null) || !(value instanceof Number)) {
throw new IllegalArgumentException("illegal value");
}
if (!value.equals(this.value)) {
this.value = (Number)value;
fireStateChanged();
}
}
}
|
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.util.List;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.awt.Component;
import java.awt.Container;
import java.awt.DefaultFocusTraversalPolicy;
import java.awt.FocusTraversalPolicy;
import java.awt.Window;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.beans.PropertyVetoException;
import java.util.Set;
import java.util.TreeSet;
/** {@collect.stats}
* A container used to create a multiple-document interface or a virtual desktop.
* You create <code>JInternalFrame</code> objects and add them to the
* <code>JDesktopPane</code>. <code>JDesktopPane</code> extends
* <code>JLayeredPane</code> to manage the potentially overlapping internal
* frames. It also maintains a reference to an instance of
* <code>DesktopManager</code> that is set by the UI
* class for the current look and feel (L&F). Note that <code>JDesktopPane</code>
* does not support borders.
* <p>
* This class is normally used as the parent of <code>JInternalFrames</code>
* to provide a pluggable <code>DesktopManager</code> object to the
* <code>JInternalFrames</code>. The <code>installUI</code> of the
* L&F specific implementation is responsible for setting the
* <code>desktopManager</code> variable appropriately.
* When the parent of a <code>JInternalFrame</code> is a <code>JDesktopPane</code>,
* it should delegate most of its behavior to the <code>desktopManager</code>
* (closing, resizing, etc).
* <p>
* For further documentation and examples see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/internalframe.html">How to Use Internal Frames</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 JInternalFrame
* @see JInternalFrame.JDesktopIcon
* @see DesktopManager
*
* @author David Kloba
*/
public class JDesktopPane extends JLayeredPane implements Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "DesktopPaneUI";
transient DesktopManager desktopManager;
private transient JInternalFrame selectedFrame = null;
/** {@collect.stats}
* Indicates that the entire contents of the item being dragged
* should appear inside the desktop pane.
*
* @see #OUTLINE_DRAG_MODE
* @see #setDragMode
*/
public static final int LIVE_DRAG_MODE = 0;
/** {@collect.stats}
* Indicates that an outline only of the item being dragged
* should appear inside the desktop pane.
*
* @see #LIVE_DRAG_MODE
* @see #setDragMode
*/
public static final int OUTLINE_DRAG_MODE = 1;
private int dragMode = LIVE_DRAG_MODE;
private boolean dragModeSet = false;
private transient List<JInternalFrame> framesCache;
private boolean componentOrderCheckingEnabled = true;
private boolean componentOrderChanged = false;
/** {@collect.stats}
* Creates a new <code>JDesktopPane</code>.
*/
public JDesktopPane() {
setUIProperty("opaque", Boolean.TRUE);
setFocusCycleRoot(true);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() {
public Component getDefaultComponent(Container c) {
JInternalFrame jifArray[] = getAllFrames();
Component comp = null;
for (int i = 0; i < jifArray.length; i++) {
comp = jifArray[i].getFocusTraversalPolicy().getDefaultComponent(jifArray[i]);
if (comp != null) {
break;
}
}
return comp;
}
});
updateUI();
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return the <code>DesktopPaneUI</code> object that
* renders this component
*/
public DesktopPaneUI getUI() {
return (DesktopPaneUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the DesktopPaneUI 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(DesktopPaneUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Sets the "dragging style" used by the desktop pane.
* You may want to change to one mode or another for
* performance or aesthetic reasons.
*
* @param dragMode the style of drag to use for items in the Desktop
*
* @see #LIVE_DRAG_MODE
* @see #OUTLINE_DRAG_MODE
*
* @beaninfo
* bound: true
* description: Dragging style for internal frame children.
* enum: LIVE_DRAG_MODE JDesktopPane.LIVE_DRAG_MODE
* OUTLINE_DRAG_MODE JDesktopPane.OUTLINE_DRAG_MODE
* @since 1.3
*/
public void setDragMode(int dragMode) {
int oldDragMode = this.dragMode;
this.dragMode = dragMode;
firePropertyChange("dragMode", oldDragMode, this.dragMode);
dragModeSet = true;
}
/** {@collect.stats}
* Gets the current "dragging style" used by the desktop pane.
* @return either <code>Live_DRAG_MODE</code> or
* <code>OUTLINE_DRAG_MODE</code>
* @see #setDragMode
* @since 1.3
*/
public int getDragMode() {
return dragMode;
}
/** {@collect.stats}
* Returns the <code>DesktopManger</code> that handles
* desktop-specific UI actions.
*/
public DesktopManager getDesktopManager() {
return desktopManager;
}
/** {@collect.stats}
* Sets the <code>DesktopManger</code> that will handle
* desktop-specific UI actions.
*
* @param d the <code>DesktopManager</code> to use
*
* @beaninfo
* bound: true
* description: Desktop manager to handle the internal frames in the
* desktop pane.
*/
public void setDesktopManager(DesktopManager d) {
DesktopManager oldValue = desktopManager;
desktopManager = d;
firePropertyChange("desktopManager", oldValue, desktopManager);
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((DesktopPaneUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "DesktopPaneUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns all <code>JInternalFrames</code> currently displayed in the
* desktop. Returns iconified frames as well as expanded frames.
*
* @return an array of <code>JInternalFrame</code> objects
*/
public JInternalFrame[] getAllFrames() {
int i, count;
JInternalFrame[] results;
Vector vResults = new Vector(10);
Object next, tmp;
count = getComponentCount();
for(i = 0; i < count; i++) {
next = getComponent(i);
if(next instanceof JInternalFrame)
vResults.addElement(next);
else if(next instanceof JInternalFrame.JDesktopIcon) {
tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame();
if(tmp != null)
vResults.addElement(tmp);
}
}
results = new JInternalFrame[vResults.size()];
vResults.copyInto(results);
return results;
}
/** {@collect.stats} Returns the currently active <code>JInternalFrame</code>
* in this <code>JDesktopPane</code>, or <code>null</code>
* if no <code>JInternalFrame</code> is currently active.
*
* @return the currently active <code>JInternalFrame</code> or
* <code>null</code>
* @since 1.3
*/
public JInternalFrame getSelectedFrame() {
return selectedFrame;
}
/** {@collect.stats} Sets the currently active <code>JInternalFrame</code>
* in this <code>JDesktopPane</code>. This method is used to bridge
* the package gap between JDesktopPane and the platform implementation
* code and should not be called directly. To visually select the frame
* the client must call JInternalFrame.setSelected(true) to activate
* the frame.
* @see JInternalFrame#setSelected(boolean)
*
* @param f the internal frame that's currently selected
* @since 1.3
*/
public void setSelectedFrame(JInternalFrame f) {
selectedFrame = f;
}
/** {@collect.stats}
* Returns all <code>JInternalFrames</code> currently displayed in the
* specified layer of the desktop. Returns iconified frames as well
* expanded frames.
*
* @param layer an int specifying the desktop layer
* @return an array of <code>JInternalFrame</code> objects
* @see JLayeredPane
*/
public JInternalFrame[] getAllFramesInLayer(int layer) {
int i, count;
JInternalFrame[] results;
Vector vResults = new Vector(10);
Object next, tmp;
count = getComponentCount();
for(i = 0; i < count; i++) {
next = getComponent(i);
if(next instanceof JInternalFrame) {
if(((JInternalFrame)next).getLayer() == layer)
vResults.addElement(next);
} else if(next instanceof JInternalFrame.JDesktopIcon) {
tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame();
if(tmp != null && ((JInternalFrame)tmp).getLayer() == layer)
vResults.addElement(tmp);
}
}
results = new JInternalFrame[vResults.size()];
vResults.copyInto(results);
return results;
}
private List<JInternalFrame> getFrames() {
Component c;
Set<ComponentPosition> set = new TreeSet<ComponentPosition>();
for (int i = 0; i < getComponentCount(); i++) {
c = getComponent(i);
if (c instanceof JInternalFrame) {
set.add(new ComponentPosition((JInternalFrame)c, getLayer(c),
i));
}
else if (c instanceof JInternalFrame.JDesktopIcon) {
c = ((JInternalFrame.JDesktopIcon)c).getInternalFrame();
set.add(new ComponentPosition((JInternalFrame)c, getLayer(c),
i));
}
}
List<JInternalFrame> frames = new ArrayList<JInternalFrame>(
set.size());
for (ComponentPosition position : set) {
frames.add(position.component);
}
return frames;
}
private static class ComponentPosition implements
Comparable<ComponentPosition> {
private final JInternalFrame component;
private final int layer;
private final int zOrder;
ComponentPosition(JInternalFrame component, int layer, int zOrder) {
this.component = component;
this.layer = layer;
this.zOrder = zOrder;
}
public int compareTo(ComponentPosition o) {
int delta = o.layer - layer;
if (delta == 0) {
return zOrder - o.zOrder;
}
return delta;
}
}
private JInternalFrame getNextFrame(JInternalFrame f, boolean forward) {
verifyFramesCache();
if (f == null) {
return getTopInternalFrame();
}
int i = framesCache.indexOf(f);
if (i == -1 || framesCache.size() == 1) {
/* error */
return null;
}
if (forward) {
// navigate to the next frame
if (++i == framesCache.size()) {
/* wrap */
i = 0;
}
}
else {
// navigate to the previous frame
if (--i == -1) {
/* wrap */
i = framesCache.size() - 1;
}
}
return framesCache.get(i);
}
JInternalFrame getNextFrame(JInternalFrame f) {
return getNextFrame(f, true);
}
private JInternalFrame getTopInternalFrame() {
if (framesCache.size() == 0) {
return null;
}
return framesCache.get(0);
}
private void updateFramesCache() {
framesCache = getFrames();
}
private void verifyFramesCache() {
// If framesCache is dirty, then recreate it.
if (componentOrderChanged) {
componentOrderChanged = false;
updateFramesCache();
}
}
/** {@collect.stats}
* Selects the next <code>JInternalFrame</code> in this desktop pane.
*
* @param forward a boolean indicating which direction to select in;
* <code>true</code> for forward, <code>false</code> for
* backward
* @return the JInternalFrame that was selected or <code>null</code>
* if nothing was selected
* @since 1.6
*/
public JInternalFrame selectFrame(boolean forward) {
JInternalFrame selectedFrame = getSelectedFrame();
JInternalFrame frameToSelect = getNextFrame(selectedFrame, forward);
if (frameToSelect == null) {
return null;
}
// Maintain navigation traversal order until an
// external stack change, such as a click on a frame.
setComponentOrderCheckingEnabled(false);
if (forward && selectedFrame != null) {
selectedFrame.moveToBack(); // For Windows MDI fidelity.
}
try { frameToSelect.setSelected(true);
} catch (PropertyVetoException pve) {}
setComponentOrderCheckingEnabled(true);
return frameToSelect;
}
/*
* Sets whether component order checking is enabled.
* @param enable a boolean value, where <code>true</code> means
* a change in component order will cause a change in the keyboard
* navigation order.
* @since 1.6
*/
void setComponentOrderCheckingEnabled(boolean enable) {
componentOrderCheckingEnabled = enable;
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
protected void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
if (componentOrderCheckingEnabled) {
if (comp instanceof JInternalFrame ||
comp instanceof JInternalFrame.JDesktopIcon) {
componentOrderChanged = true;
}
}
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
public void remove(int index) {
if (componentOrderCheckingEnabled) {
Component comp = getComponent(index);
if (comp instanceof JInternalFrame ||
comp instanceof JInternalFrame.JDesktopIcon) {
componentOrderChanged = true;
}
}
super.remove(index);
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
public void removeAll() {
if (componentOrderCheckingEnabled) {
int count = getComponentCount();
for (int i = 0; i < count; i++) {
Component comp = getComponent(i);
if (comp instanceof JInternalFrame ||
comp instanceof JInternalFrame.JDesktopIcon) {
componentOrderChanged = true;
break;
}
}
}
super.removeAll();
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
public void setComponentZOrder(Component comp, int index) {
super.setComponentZOrder(comp, index);
if (componentOrderCheckingEnabled) {
if (comp instanceof JInternalFrame ||
comp instanceof JInternalFrame.JDesktopIcon) {
componentOrderChanged = true;
}
}
}
/** {@collect.stats}
* 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);
}
}
}
void setUIProperty(String propertyName, Object value) {
if (propertyName == "dragMode") {
if (!dragModeSet) {
setDragMode(((Integer)value).intValue());
dragModeSet = false;
}
} else {
super.setUIProperty(propertyName, value);
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JDesktopPane</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>JDesktopPane</code>
*/
protected String paramString() {
String desktopManagerString = (desktopManager != null ?
desktopManager.toString() : "");
return super.paramString() +
",desktopManager=" + desktopManagerString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with this
* <code>JDesktopPane</code>. For desktop panes, the
* <code>AccessibleContext</code> takes the form of an
* <code>AccessibleJDesktopPane</code>.
* A new <code>AccessibleJDesktopPane</code> instance is created if necessary.
*
* @return an <code>AccessibleJDesktopPane</code> that serves as the
* <code>AccessibleContext</code> of this <code>JDesktopPane</code>
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJDesktopPane();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JDesktopPane</code> class. It provides an implementation of the
* Java Accessibility API appropriate to desktop 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 AccessibleJDesktopPane extends AccessibleJComponent {
/** {@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.DESKTOP_PANE;
}
}
}
|
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.event.*;
import javax.swing.event.*;
/** {@collect.stats}
* A model for a potentially unbounded sequence of object values. This model
* is similar to <code>ListModel</code> however there are some important differences:
* <ul>
* <li> The number of sequence elements isn't neccessarily bounded.
* <li> The model doesn't support indexed random access to sequence elements.
* Only three sequence values are accessible at a time: current, next and
* previous.
* <li> The current sequence element, can be set.
* </ul>
* <p>
* A <code>SpinnerModel</code> has three properties, only the first is read/write.
* <dl>
* <dt><code>value</code>
* <dd>The current element of the sequence.
*
* <dt><code>nextValue</code>
* <dd>The following element or null if <code>value</code> is the
* last element of the sequence.
*
* <dt><code>previousValue</code>
* <dd>The preceeding element or null if <code>value</code> is the
* first element of the sequence.
* </dl>
* When the the <code>value</code> property changes,
* <code>ChangeListeners</code> are notified. <code>SpinnerModel</code> may
* choose to notify the <code>ChangeListeners</code> under other circumstances.
*
* @see JSpinner
* @see AbstractSpinnerModel
* @see SpinnerListModel
* @see SpinnerNumberModel
* @see SpinnerDateModel
*
* @author Hans Muller
* @since 1.4
*/
public interface SpinnerModel
{
/** {@collect.stats}
* The <i>current element</i> of the sequence. This element is usually
* displayed by the <code>editor</code> part of a <code>JSpinner</code>.
*
* @return the current spinner value.
* @see #setValue
*/
Object getValue();
/** {@collect.stats}
* Changes current value of the model, typically this value is displayed
* by the <code>editor</code> part of a <code>JSpinner</code>.
* If the <code>SpinnerModel</code> implementation doesn't support
* the specified value then an <code>IllegalArgumentException</code>
* is thrown. For example a <code>SpinnerModel</code> for numbers might
* only support values that are integer multiples of ten. In
* that case, <code>model.setValue(new Number(11))</code>
* would throw an exception.
*
* @throws IllegalArgumentException if <code>value</code> isn't allowed
* @see #getValue
*/
void setValue(Object value);
/** {@collect.stats}
* Return the object in the sequence that comes after the object returned
* by <code>getValue()</code>. If the end of the sequence has been reached
* then return null. Calling this method does not effect <code>value</code>.
*
* @return the next legal value or null if one doesn't exist
* @see #getValue
* @see #getPreviousValue
*/
Object getNextValue();
/** {@collect.stats}
* Return the object in the sequence that comes before the object returned
* by <code>getValue()</code>. If the end of the sequence has been reached then
* return null. Calling this method does not effect <code>value</code>.
*
* @return the previous legal value or null if one doesn't exist
* @see #getValue
* @see #getNextValue
*/
Object getPreviousValue();
/** {@collect.stats}
* Adds a <code>ChangeListener</code> to the model's listener list. The
* <code>ChangeListeners</code> must be notified when models <code>value</code>
* changes.
*
* @param l the ChangeListener to add
* @see #removeChangeListener
*/
void addChangeListener(ChangeListener l);
/** {@collect.stats}
* Removes a <code>ChangeListener</code> from the model's listener list.
*
* @param l the ChangeListener to remove
* @see #addChangeListener
*/
void removeChangeListener(ChangeListener l);
}
|
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.Dimension;
import java.awt.Rectangle;
/** {@collect.stats}
* An interface that provides information to a scrolling container
* like JScrollPane. A complex component that's likely to be used
* as a viewing a JScrollPane viewport (or other scrolling container)
* should implement this interface.
*
* @see JViewport
* @see JScrollPane
* @see JScrollBar
* @author Hans Muller
*/
public interface Scrollable
{
/** {@collect.stats}
* Returns the preferred size of the viewport for a view component.
* For example, the preferred size of a <code>JList</code> component
* is the size required to accommodate all of the cells in its list.
* However, the value of <code>preferredScrollableViewportSize</code>
* is the size required for <code>JList.getVisibleRowCount</code> rows.
* A component without any properties that would affect the viewport
* size should just return <code>getPreferredSize</code> here.
*
* @return the preferredSize of a <code>JViewport</code> whose view
* is this <code>Scrollable</code>
* @see JViewport#getPreferredSize
*/
Dimension getPreferredScrollableViewportSize();
/** {@collect.stats}
* Components that display logical rows or columns should compute
* the scroll increment that will completely expose one new row
* or column, depending on the value of orientation. Ideally,
* components should handle a partially exposed row or column by
* returning the distance required to completely expose the item.
* <p>
* Scrolling containers, like JScrollPane, will use this method
* each time the user requests a unit scroll.
*
* @param visibleRect The view area visible within the viewport
* @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
* @param direction Less than zero to scroll up/left, greater than zero for down/right.
* @return The "unit" increment for scrolling in the specified direction.
* This value should always be positive.
* @see JScrollBar#setUnitIncrement
*/
int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction);
/** {@collect.stats}
* Components that display logical rows or columns should compute
* the scroll increment that will completely expose one block
* of rows or columns, depending on the value of orientation.
* <p>
* Scrolling containers, like JScrollPane, will use this method
* each time the user requests a block scroll.
*
* @param visibleRect The view area visible within the viewport
* @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
* @param direction Less than zero to scroll up/left, greater than zero for down/right.
* @return The "block" increment for scrolling in the specified direction.
* This value should always be positive.
* @see JScrollBar#setBlockIncrement
*/
int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction);
/** {@collect.stats}
* Return true if a viewport should always force the width of this
* <code>Scrollable</code> to match the width of the viewport.
* For example a normal
* text view that supported line wrapping would return true here, since it
* would be undesirable for wrapped lines to disappear beyond the right
* edge of the viewport. Note that returning true for a Scrollable
* whose ancestor is a JScrollPane effectively disables horizontal
* scrolling.
* <p>
* Scrolling containers, like JViewport, will use this method each
* time they are validated.
*
* @return True if a viewport should force the Scrollables width to match its own.
*/
boolean getScrollableTracksViewportWidth();
/** {@collect.stats}
* Return true if a viewport should always force the height of this
* Scrollable to match the height of the viewport. For example a
* columnar text view that flowed text in left to right columns
* could effectively disable vertical scrolling by returning
* true here.
* <p>
* Scrolling containers, like JViewport, will use this method each
* time they are validated.
*
* @return True if a viewport should force the Scrollables height to match its own.
*/
boolean getScrollableTracksViewportHeight();
}
|
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 javax.swing.text.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.util.Collections;
import java.util.Set;
import java.util.StringTokenizer;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* A <code>JTextArea</code> is a multi-line area that displays plain text.
* It is intended to be a lightweight component that provides source
* compatibility with the <code>java.awt.TextArea</code> class where it can
* reasonably do so.
* You can find information and examples of using all the text components 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 has capabilities not found in the
* <code>java.awt.TextArea</code> class. The superclass should be
* consulted for additional capabilities.
* Alternative multi-line text classes with
* more capabilities are <code>JTextPane</code> and <code>JEditorPane</code>.
* <p>
* The <code>java.awt.TextArea</code> internally handles scrolling.
* <code>JTextArea</code> is different in that it doesn't manage scrolling,
* but implements the swing <code>Scrollable</code> interface. This allows it
* to be placed inside a <code>JScrollPane</code> if scrolling
* behavior is desired, and used directly if scrolling is not desired.
* <p>
* The <code>java.awt.TextArea</code> has the ability to do line wrapping.
* This was controlled by the horizontal scrolling policy. Since
* scrolling is not done by <code>JTextArea</code> directly, backward
* compatibility must be provided another way. <code>JTextArea</code> has
* a bound property for line wrapping that controls whether or
* not it will wrap lines. By default, the line wrapping property
* is set to false (not wrapped).
* <p>
* <code>java.awt.TextArea</code> has two properties <code>rows</code>
* and <code>columns</code> that are used to determine the preferred size.
* <code>JTextArea</code> uses these properties to indicate the
* preferred size of the viewport when placed inside a <code>JScrollPane</code>
* to match the functionality provided by <code>java.awt.TextArea</code>.
* <code>JTextArea</code> has a preferred size of what is needed to
* display all of the text, so that it functions properly inside of
* a <code>JScrollPane</code>. If the value for <code>rows</code>
* or <code>columns</code> is equal to zero,
* the preferred size along that axis is used for
* the viewport preferred size along the same axis.
* <p>
* The <code>java.awt.TextArea</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>
* DocumentListener myListener = ??;
* JTextArea myArea = ??;
* myArea.getDocument().addDocumentListener(myListener);
* </pre>
* <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 multi-line area that displays plain text.
*
* @author Timothy Prinzing
* @see JTextPane
* @see JEditorPane
*/
public class JTextArea extends JTextComponent {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "TextAreaUI";
/** {@collect.stats}
* Constructs a new TextArea. A default model is set, the initial string
* is null, and rows/columns are set to 0.
*/
public JTextArea() {
this(null, null, 0, 0);
}
/** {@collect.stats}
* Constructs a new TextArea with the specified text displayed.
* A default model is created and rows/columns are set to 0.
*
* @param text the text to be displayed, or null
*/
public JTextArea(String text) {
this(null, text, 0, 0);
}
/** {@collect.stats}
* Constructs a new empty TextArea with the specified number of
* rows and columns. A default model is created, and the initial
* string is null.
*
* @param rows the number of rows >= 0
* @param columns the number of columns >= 0
* @exception IllegalArgumentException if the rows or columns
* arguments are negative.
*/
public JTextArea(int rows, int columns) {
this(null, null, rows, columns);
}
/** {@collect.stats}
* Constructs a new TextArea with the specified text and number
* of rows and columns. A default model is created.
*
* @param text the text to be displayed, or null
* @param rows the number of rows >= 0
* @param columns the number of columns >= 0
* @exception IllegalArgumentException if the rows or columns
* arguments are negative.
*/
public JTextArea(String text, int rows, int columns) {
this(null, text, rows, columns);
}
/** {@collect.stats}
* Constructs a new JTextArea with the given document model, and defaults
* for all of the other arguments (null, 0, 0).
*
* @param doc the model to use
*/
public JTextArea(Document doc) {
this(doc, null, 0, 0);
}
/** {@collect.stats}
* Constructs a new JTextArea with the specified number of rows
* and columns, and the given model. All of the constructors
* feed through this constructor.
*
* @param doc the model to use, or create a default one if null
* @param text the text to be displayed, null if none
* @param rows the number of rows >= 0
* @param columns the number of columns >= 0
* @exception IllegalArgumentException if the rows or columns
* arguments are negative.
*/
public JTextArea(Document doc, String text, int rows, int columns) {
super();
this.rows = rows;
this.columns = columns;
if (doc == null) {
doc = createDefaultModel();
}
setDocument(doc);
if (text != null) {
setText(text);
select(0, 0);
}
if (rows < 0) {
throw new IllegalArgumentException("rows: " + rows);
}
if (columns < 0) {
throw new IllegalArgumentException("columns: " + columns);
}
LookAndFeel.installProperty(this,
"focusTraversalKeysForward",
JComponent.
getManagingFocusForwardTraversalKeys());
LookAndFeel.installProperty(this,
"focusTraversalKeysBackward",
JComponent.
getManagingFocusBackwardTraversalKeys());
}
/** {@collect.stats}
* Returns the class ID for the UI.
*
* @return the ID ("TextAreaUI")
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Creates the default implementation of the model
* to be used at construction if one isn't explicitly
* given. A new instance of PlainDocument is returned.
*
* @return the default document model
*/
protected Document createDefaultModel() {
return new PlainDocument();
}
/** {@collect.stats}
* Sets the number of characters to expand tabs to.
* This will be multiplied by the maximum advance for
* variable width fonts. A PropertyChange event ("tabSize") is fired
* when the tab size changes.
*
* @param size number of characters to expand to
* @see #getTabSize
* @beaninfo
* preferred: true
* bound: true
* description: the number of characters to expand tabs to
*/
public void setTabSize(int size) {
Document doc = getDocument();
if (doc != null) {
int old = getTabSize();
doc.putProperty(PlainDocument.tabSizeAttribute, new Integer(size));
firePropertyChange("tabSize", old, size);
}
}
/** {@collect.stats}
* Gets the number of characters used to expand tabs. If the document is
* null or doesn't have a tab setting, return a default of 8.
*
* @return the number of characters
*/
public int getTabSize() {
int size = 8;
Document doc = getDocument();
if (doc != null) {
Integer i = (Integer) doc.getProperty(PlainDocument.tabSizeAttribute);
if (i != null) {
size = i.intValue();
}
}
return size;
}
/** {@collect.stats}
* Sets the line-wrapping policy of the text area. If set
* to true the lines will be wrapped if they are too long
* to fit within the allocated width. If set to false,
* the lines will always be unwrapped. A <code>PropertyChange</code>
* event ("lineWrap") is fired when the policy is changed.
* By default this property is false.
*
* @param wrap indicates if lines should be wrapped
* @see #getLineWrap
* @beaninfo
* preferred: true
* bound: true
* description: should lines be wrapped
*/
public void setLineWrap(boolean wrap) {
boolean old = this.wrap;
this.wrap = wrap;
firePropertyChange("lineWrap", old, wrap);
}
/** {@collect.stats}
* Gets the line-wrapping policy of the text area. If set
* to true the lines will be wrapped if they are too long
* to fit within the allocated width. If set to false,
* the lines will always be unwrapped.
*
* @return if lines will be wrapped
*/
public boolean getLineWrap() {
return wrap;
}
/** {@collect.stats}
* Sets the style of wrapping used if the text area is wrapping
* lines. If set to true the lines will be wrapped at word
* boundaries (whitespace) if they are too long
* to fit within the allocated width. If set to false,
* the lines will be wrapped at character boundaries.
* By default this property is false.
*
* @param word indicates if word boundaries should be used
* for line wrapping
* @see #getWrapStyleWord
* @beaninfo
* preferred: false
* bound: true
* description: should wrapping occur at word boundaries
*/
public void setWrapStyleWord(boolean word) {
boolean old = this.word;
this.word = word;
firePropertyChange("wrapStyleWord", old, word);
}
/** {@collect.stats}
* Gets the style of wrapping used if the text area is wrapping
* lines. If set to true the lines will be wrapped at word
* boundaries (ie whitespace) if they are too long
* to fit within the allocated width. If set to false,
* the lines will be wrapped at character boundaries.
*
* @return if the wrap style should be word boundaries
* instead of character boundaries
* @see #setWrapStyleWord
*/
public boolean getWrapStyleWord() {
return word;
}
/** {@collect.stats}
* Translates an offset into the components text to a
* line number.
*
* @param offset the offset >= 0
* @return the line number >= 0
* @exception BadLocationException thrown if the offset is
* less than zero or greater than the document length.
*/
public int getLineOfOffset(int offset) throws BadLocationException {
Document doc = getDocument();
if (offset < 0) {
throw new BadLocationException("Can't translate offset to line", -1);
} else if (offset > doc.getLength()) {
throw new BadLocationException("Can't translate offset to line", doc.getLength()+1);
} else {
Element map = getDocument().getDefaultRootElement();
return map.getElementIndex(offset);
}
}
/** {@collect.stats}
* Determines the number of lines contained in the area.
*
* @return the number of lines > 0
*/
public int getLineCount() {
Element map = getDocument().getDefaultRootElement();
return map.getElementCount();
}
/** {@collect.stats}
* Determines the offset of the start of the given line.
*
* @param line the line number to translate >= 0
* @return the offset >= 0
* @exception BadLocationException thrown if the line is
* less than zero or greater or equal to the number of
* lines contained in the document (as reported by
* getLineCount).
*/
public int getLineStartOffset(int line) throws BadLocationException {
int lineCount = getLineCount();
if (line < 0) {
throw new BadLocationException("Negative line", -1);
} else if (line >= lineCount) {
throw new BadLocationException("No such line", getDocument().getLength()+1);
} else {
Element map = getDocument().getDefaultRootElement();
Element lineElem = map.getElement(line);
return lineElem.getStartOffset();
}
}
/** {@collect.stats}
* Determines the offset of the end of the given line.
*
* @param line the line >= 0
* @return the offset >= 0
* @exception BadLocationException Thrown if the line is
* less than zero or greater or equal to the number of
* lines contained in the document (as reported by
* getLineCount).
*/
public int getLineEndOffset(int line) throws BadLocationException {
int lineCount = getLineCount();
if (line < 0) {
throw new BadLocationException("Negative line", -1);
} else if (line >= lineCount) {
throw new BadLocationException("No such line", getDocument().getLength()+1);
} else {
Element map = getDocument().getDefaultRootElement();
Element lineElem = map.getElement(line);
int endOffset = lineElem.getEndOffset();
// hide the implicit break at the end of the document
return ((line == lineCount - 1) ? (endOffset - 1) : endOffset);
}
}
// --- java.awt.TextArea methods ---------------------------------
/** {@collect.stats}
* Inserts the specified text at the specified position. Does nothing
* if the model is null or if the text is null or empty.
* <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 str the text to insert
* @param pos the position at which to insert >= 0
* @exception IllegalArgumentException if pos is an
* invalid position in the model
* @see TextComponent#setText
* @see #replaceRange
*/
public void insert(String str, int pos) {
Document doc = getDocument();
if (doc != null) {
try {
doc.insertString(pos, str, null);
} catch (BadLocationException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}
/** {@collect.stats}
* Appends the given text to the end of the document. Does nothing if
* the model is null or the string is null or empty.
* <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 str the text to insert
* @see #insert
*/
public void append(String str) {
Document doc = getDocument();
if (doc != null) {
try {
doc.insertString(doc.getLength(), str, null);
} catch (BadLocationException e) {
}
}
}
/** {@collect.stats}
* Replaces text from the indicated start to end position with the
* new text specified. Does nothing if the model is null. Simply
* does a delete if the new string is null or empty.
* <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 str the text to use as the replacement
* @param start the start position >= 0
* @param end the end position >= start
* @exception IllegalArgumentException if part of the range is an
* invalid position in the model
* @see #insert
* @see #replaceRange
*/
public void replaceRange(String str, int start, int end) {
if (end < start) {
throw new IllegalArgumentException("end before start");
}
Document doc = getDocument();
if (doc != null) {
try {
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).replace(start, end - start, str,
null);
}
else {
doc.remove(start, end - start);
doc.insertString(start, str, null);
}
} catch (BadLocationException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}
/** {@collect.stats}
* Returns the number of rows in the TextArea.
*
* @return the number of rows >= 0
*/
public int getRows() {
return rows;
}
/** {@collect.stats}
* Sets the number of rows for this TextArea. Calls invalidate() after
* setting the new value.
*
* @param rows the number of rows >= 0
* @exception IllegalArgumentException if rows is less than 0
* @see #getRows
* @beaninfo
* description: the number of rows preferred for display
*/
public void setRows(int rows) {
int oldVal = this.rows;
if (rows < 0) {
throw new IllegalArgumentException("rows less than zero.");
}
if (rows != oldVal) {
this.rows = rows;
invalidate();
}
}
/** {@collect.stats}
* Defines the meaning of the height of a row. This defaults to
* the height of the font.
*
* @return the height >= 1
*/
protected int getRowHeight() {
if (rowHeight == 0) {
FontMetrics metrics = getFontMetrics(getFont());
rowHeight = metrics.getHeight();
}
return rowHeight;
}
/** {@collect.stats}
* Returns the number of columns in the TextArea.
*
* @return number of columns >= 0
*/
public int getColumns() {
return columns;
}
/** {@collect.stats}
* Sets the number of columns for this TextArea. Does an invalidate()
* after setting the new value.
*
* @param columns the number of columns >= 0
* @exception IllegalArgumentException if columns is less than 0
* @see #getColumns
* @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}
* Gets 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;
}
// --- Component methods -----------------------------------------
/** {@collect.stats}
* Returns the preferred size of the TextArea. This is the
* maximum of the size needed to display the text and the
* size requested for the viewport.
*
* @return the size
*/
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
d = (d == null) ? new Dimension(400,400) : d;
Insets insets = getInsets();
if (columns != 0) {
d.width = Math.max(d.width, columns * getColumnWidth() +
insets.left + insets.right);
}
if (rows != 0) {
d.height = Math.max(d.height, rows * getRowHeight() +
insets.top + insets.bottom);
}
return d;
}
/** {@collect.stats}
* Sets the current font. This removes cached row height and column
* width so the new font will be reflected, and calls revalidate().
*
* @param f the font to use as the current font
*/
public void setFont(Font f) {
super.setFont(f);
rowHeight = 0;
columnWidth = 0;
}
/** {@collect.stats}
* Returns a string representation of this JTextArea. 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 JTextArea.
*/
protected String paramString() {
String wrapString = (wrap ?
"true" : "false");
String wordString = (word ?
"true" : "false");
return super.paramString() +
",colums=" + columns +
",columWidth=" + columnWidth +
",rows=" + rows +
",rowHeight=" + rowHeight +
",word=" + wordString +
",wrap=" + wrapString;
}
// --- Scrollable methods ----------------------------------------
/** {@collect.stats}
* Returns true if a viewport should always force the width of this
* Scrollable to match the width of the viewport. This is implemented
* to return true if the line wrapping policy is true, and false
* if lines are not being wrapped.
*
* @return true if a viewport should force the Scrollables width
* to match its own.
*/
public boolean getScrollableTracksViewportWidth() {
return (wrap) ? true : super.getScrollableTracksViewportWidth();
}
/** {@collect.stats}
* Returns the preferred size of the viewport if this component
* is embedded in a JScrollPane. This uses the desired column
* and row settings if they have been set, otherwise the superclass
* behavior is used.
*
* @return The preferredSize of a JViewport whose view is this Scrollable.
* @see JViewport#getPreferredSize
*/
public Dimension getPreferredScrollableViewportSize() {
Dimension size = super.getPreferredScrollableViewportSize();
size = (size == null) ? new Dimension(400,400) : size;
Insets insets = getInsets();
size.width = (columns == 0) ? size.width :
columns * getColumnWidth() + insets.left + insets.right;
size.height = (rows == 0) ? size.height :
rows * getRowHeight() + insets.top + insets.bottom;
return size;
}
/** {@collect.stats}
* Components that display logical rows or columns should compute
* the scroll increment that will completely expose one new row
* or column, depending on the value of orientation. This is implemented
* to use the values returned by the <code>getRowHeight</code> and
* <code>getColumnWidth</code> methods.
* <p>
* Scrolling containers, like JScrollPane, will use this method
* each time the user requests a unit scroll.
*
* @param visibleRect the view area visible within the viewport
* @param orientation Either SwingConstants.VERTICAL or
* SwingConstants.HORIZONTAL.
* @param direction Less than zero to scroll up/left,
* greater than zero for down/right.
* @return The "unit" increment for scrolling in the specified direction
* @exception IllegalArgumentException for an invalid orientation
* @see JScrollBar#setUnitIncrement
* @see #getRowHeight
* @see #getColumnWidth
*/
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
switch (orientation) {
case SwingConstants.VERTICAL:
return getRowHeight();
case SwingConstants.HORIZONTAL:
return getColumnWidth();
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
}
/** {@collect.stats}
* 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);
}
}
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JTextArea.
* For JTextAreas, the AccessibleContext takes the form of an
* AccessibleJTextArea.
* A new AccessibleJTextArea instance is created if necessary.
*
* @return an AccessibleJTextArea that serves as the
* AccessibleContext of this JTextArea
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJTextArea();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JTextArea</code> class. It provides an implementation of the
* Java Accessibility API appropriate to text area 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 AccessibleJTextArea extends AccessibleJTextComponent {
/** {@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;
}
}
// --- variables -------------------------------------------------
private int rows;
private int columns;
private int columnWidth;
private int rowHeight;
private boolean wrap;
private boolean word;
}
|
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;
import java.awt.*;
import java.awt.image.*;
/** {@collect.stats}
* An image filter that "disables" an image by turning
* it into a grayscale image, and brightening the pixels
* in the image. Used by buttons to create an image for
* a disabled button.
*
* @author Jeff Dinkins
* @author Tom Ball
* @author Jim Graham
*/
public class GrayFilter extends RGBImageFilter {
private boolean brighter;
private int percent;
/** {@collect.stats}
* Creates a disabled image
*/
public static Image createDisabledImage (Image i) {
GrayFilter filter = new GrayFilter(true, 50);
ImageProducer prod = new FilteredImageSource(i.getSource(), filter);
Image grayImage = Toolkit.getDefaultToolkit().createImage(prod);
return grayImage;
}
/** {@collect.stats}
* Constructs a GrayFilter object that filters a color image to a
* grayscale image. Used by buttons to create disabled ("grayed out")
* button images.
*
* @param b a boolean -- true if the pixels should be brightened
* @param p an int in the range 0..100 that determines the percentage
* of gray, where 100 is the darkest gray, and 0 is the lightest
*/
public GrayFilter(boolean b, int p) {
brighter = b;
percent = p;
// canFilterIndexColorModel indicates whether or not it is acceptable
// to apply the color filtering of the filterRGB method to the color
// table entries of an IndexColorModel object in lieu of pixel by pixel
// filtering.
canFilterIndexColorModel = true;
}
/** {@collect.stats}
* Overrides <code>RGBImageFilter.filterRGB</code>.
*/
public int filterRGB(int x, int y, int rgb) {
// Use NTSC conversion formula.
int gray = (int)((0.30 * ((rgb >> 16) & 0xff) +
0.59 * ((rgb >> 8) & 0xff) +
0.11 * (rgb & 0xff)) / 3);
if (brighter) {
gray = (255 - ((255 - gray) * (100 - percent) / 100));
} else {
gray = (gray * (100 - percent) / 100);
}
if (gray < 0) gray = 0;
if (gray > 255) gray = 255;
return (rgb & 0xff000000) | (gray << 16) | (gray << 8) | (gray << 0);
}
}
|
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 javax.swing.event.*;
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 two-state button.
* The <code>JRadioButton</code> and <code>JCheckBox</code> classes
* are subclasses of this class.
* For information on using them see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/button.html">How to Use Buttons, Check Boxes, and Radio Buttons</a>,
* a section in <em>The Java Tutorial</em>.
* <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}.
*
* @beaninfo
* attribute: isContainer false
* description: An implementation of a two-state button.
*
* @see JRadioButton
* @see JCheckBox
* @author Jeff Dinkins
*/
public class JToggleButton extends AbstractButton implements Accessible {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ToggleButtonUI";
/** {@collect.stats}
* Creates an initially unselected toggle button
* without setting the text or image.
*/
public JToggleButton () {
this(null, null, false);
}
/** {@collect.stats}
* Creates an initially unselected toggle button
* with the specified image but no text.
*
* @param icon the image that the button should display
*/
public JToggleButton(Icon icon) {
this(null, icon, false);
}
/** {@collect.stats}
* Creates a toggle button with the specified image
* and selection state, but no text.
*
* @param icon the image that the button should display
* @param selected if true, the button is initially selected;
* otherwise, the button is initially unselected
*/
public JToggleButton(Icon icon, boolean selected) {
this(null, icon, selected);
}
/** {@collect.stats}
* Creates an unselected toggle button with the specified text.
*
* @param text the string displayed on the toggle button
*/
public JToggleButton (String text) {
this(text, null, false);
}
/** {@collect.stats}
* Creates a toggle button with the specified text
* and selection state.
*
* @param text the string displayed on the toggle button
* @param selected if true, the button is initially selected;
* otherwise, the button is initially unselected
*/
public JToggleButton (String text, boolean selected) {
this(text, null, selected);
}
/** {@collect.stats}
* Creates a toggle button where properties are taken from the
* Action supplied.
*
* @since 1.3
*/
public JToggleButton(Action a) {
this();
setAction(a);
}
/** {@collect.stats}
* Creates a toggle button that has the specified text and image,
* and that is initially unselected.
*
* @param text the string displayed on the button
* @param icon the image that the button should display
*/
public JToggleButton(String text, Icon icon) {
this(text, icon, false);
}
/** {@collect.stats}
* Creates a toggle button with the specified text, image, and
* selection state.
*
* @param text the text of the toggle button
* @param icon the image that the button should display
* @param selected if true, the button is initially selected;
* otherwise, the button is initially unselected
*/
public JToggleButton (String text, Icon icon, boolean selected) {
// Create the model
setModel(new ToggleButtonModel());
model.setSelected(selected);
// initialize
init(text, icon);
}
/** {@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 String "ToggleButtonUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
* @beaninfo
* description: A string that specifies the name of the L&F class
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Overriden to return true, JToggleButton supports
* the selected state.
*/
boolean shouldUpdateSelectedStateFromAction() {
return true;
}
// *********************************************************************
/** {@collect.stats}
* The ToggleButton model
* <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}.
*/
public static class ToggleButtonModel extends DefaultButtonModel {
/** {@collect.stats}
* Creates a new ToggleButton Model
*/
public ToggleButtonModel () {
}
/** {@collect.stats}
* Checks if the button is selected.
*/
public boolean isSelected() {
// if(getGroup() != null) {
// return getGroup().isSelected(this);
// } else {
return (stateMask & SELECTED) != 0;
// }
}
/** {@collect.stats}
* Sets the selected state of the button.
* @param b true selects the toggle button,
* false deselects the toggle button.
*/
public void setSelected(boolean b) {
ButtonGroup group = getGroup();
if (group != null) {
// use the group model instead
group.setSelected(this, b);
b = group.isSelected(this);
}
if (isSelected() == b) {
return;
}
if (b) {
stateMask |= SELECTED;
} else {
stateMask &= ~SELECTED;
}
// Send ChangeEvent
fireStateChanged();
// Send ItemEvent
fireItemStateChanged(
new ItemEvent(this,
ItemEvent.ITEM_STATE_CHANGED,
this,
this.isSelected() ? ItemEvent.SELECTED : ItemEvent.DESELECTED));
}
/** {@collect.stats}
* Sets the pressed state of the toggle button.
*/
public void setPressed(boolean b) {
if ((isPressed() == b) || !isEnabled()) {
return;
}
if (b == false && isArmed()) {
setSelected(!this.isSelected());
}
if (b) {
stateMask |= PRESSED;
} else {
stateMask &= ~PRESSED;
}
fireStateChanged();
if(!isPressed() && isArmed()) {
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent) {
modifiers = ((InputEvent)currentEvent).getModifiers();
} else if (currentEvent instanceof ActionEvent) {
modifiers = ((ActionEvent)currentEvent).getModifiers();
}
fireActionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
getActionCommand(),
EventQueue.getMostRecentEventTime(),
modifiers));
}
}
}
/** {@collect.stats}
* 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}
* Returns a string representation of this JToggleButton. 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 JToggleButton.
*/
protected String paramString() {
return super.paramString();
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JToggleButton.
* For toggle buttons, the AccessibleContext takes the form of an
* AccessibleJToggleButton.
* A new AccessibleJToggleButton instance is created if necessary.
*
* @return an AccessibleJToggleButton that serves as the
* AccessibleContext of this JToggleButton
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this ToggleButton.
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJToggleButton();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JToggleButton</code> class. It provides an implementation of the
* Java Accessibility API appropriate to toggle button 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 AccessibleJToggleButton extends AccessibleAbstractButton
implements ItemListener {
public AccessibleJToggleButton() {
super();
JToggleButton.this.addItemListener(this);
}
/** {@collect.stats}
* Fire accessible property change events when the state of the
* toggle button changes.
*/
public void itemStateChanged(ItemEvent e) {
JToggleButton tb = (JToggleButton) e.getSource();
if (JToggleButton.this.accessibleContext != null) {
if (tb.isSelected()) {
JToggleButton.this.accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.CHECKED);
} else {
JToggleButton.this.accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.CHECKED, null);
}
}
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.TOGGLE_BUTTON;
}
} // inner class AccessibleJToggleButton
}
|
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.event.*;
import java.awt.*;
/** {@collect.stats}
* Manages all the <code>ToolTips</code> in the system.
* <p>
* ToolTipManager contains numerous properties for configuring how long it
* will take for the tooltips to become visible, and how long till they
* hide. Consider a component that has a different tooltip based on where
* the mouse is, such as JTree. When the mouse moves into the JTree and
* over a region that has a valid tooltip, the tooltip will become
* visibile after <code>initialDelay</code> milliseconds. After
* <code>dismissDelay</code> milliseconds the tooltip will be hidden. If
* the mouse is over a region that has a valid tooltip, and the tooltip
* is currently visible, when the mouse moves to a region that doesn't have
* a valid tooltip the tooltip will be hidden. If the mouse then moves back
* into a region that has a valid tooltip within <code>reshowDelay</code>
* milliseconds, the tooltip will immediately be shown, otherwise the
* tooltip will be shown again after <code>initialDelay</code> milliseconds.
*
* @see JComponent#createToolTip
* @author Dave Moore
* @author Rich Schiavi
*/
public class ToolTipManager extends MouseAdapter implements MouseMotionListener {
Timer enterTimer, exitTimer, insideTimer;
String toolTipText;
Point preferredLocation;
JComponent insideComponent;
MouseEvent mouseEvent;
boolean showImmediately;
private static final Object TOOL_TIP_MANAGER_KEY = new Object();
transient Popup tipWindow;
/** {@collect.stats} The Window tip is being displayed in. This will be non-null if
* the Window tip is in differs from that of insideComponent's Window.
*/
private Window window;
JToolTip tip;
private Rectangle popupRect = null;
private Rectangle popupFrameRect = null;
boolean enabled = true;
private boolean tipShowing = false;
private FocusListener focusChangeListener = null;
private MouseMotionListener moveBeforeEnterListener = null;
private KeyListener accessibilityKeyListener = null;
// PENDING(ges)
protected boolean lightWeightPopupEnabled = true;
protected boolean heavyWeightPopupEnabled = false;
ToolTipManager() {
enterTimer = new Timer(750, new insideTimerAction());
enterTimer.setRepeats(false);
exitTimer = new Timer(500, new outsideTimerAction());
exitTimer.setRepeats(false);
insideTimer = new Timer(4000, new stillInsideTimerAction());
insideTimer.setRepeats(false);
moveBeforeEnterListener = new MoveBeforeEnterListener();
accessibilityKeyListener = new AccessibilityKeyListener();
}
/** {@collect.stats}
* Enables or disables the tooltip.
*
* @param flag true to enable the tip, false otherwise
*/
public void setEnabled(boolean flag) {
enabled = flag;
if (!flag) {
hideTipWindow();
}
}
/** {@collect.stats}
* Returns true if this object is enabled.
*
* @return true if this object is enabled, false otherwise
*/
public boolean isEnabled() {
return enabled;
}
/** {@collect.stats}
* When displaying the <code>JToolTip</code>, the
* <code>ToolTipManager</code> chooses to use a lightweight
* <code>JPanel</code> if it fits. This method allows you to
* disable this feature. You have to do disable it if your
* application mixes light weight and heavy weights components.
*
* @param aFlag true if a lightweight panel is desired, false otherwise
*
*/
public void setLightWeightPopupEnabled(boolean aFlag){
lightWeightPopupEnabled = aFlag;
}
/** {@collect.stats}
* Returns true if lightweight (all-Java) <code>Tooltips</code>
* are in use, or false if heavyweight (native peer)
* <code>Tooltips</code> are being used.
*
* @return true if lightweight <code>ToolTips</code> are in use
*/
public boolean isLightWeightPopupEnabled() {
return lightWeightPopupEnabled;
}
/** {@collect.stats}
* Specifies the initial delay value.
*
* @param milliseconds the number of milliseconds to delay
* (after the cursor has paused) before displaying the
* tooltip
* @see #getInitialDelay
*/
public void setInitialDelay(int milliseconds) {
enterTimer.setInitialDelay(milliseconds);
}
/** {@collect.stats}
* Returns the initial delay value.
*
* @return an integer representing the initial delay value,
* in milliseconds
* @see #setInitialDelay
*/
public int getInitialDelay() {
return enterTimer.getInitialDelay();
}
/** {@collect.stats}
* Specifies the dismissal delay value.
*
* @param milliseconds the number of milliseconds to delay
* before taking away the tooltip
* @see #getDismissDelay
*/
public void setDismissDelay(int milliseconds) {
insideTimer.setInitialDelay(milliseconds);
}
/** {@collect.stats}
* Returns the dismissal delay value.
*
* @return an integer representing the dismissal delay value,
* in milliseconds
* @see #setDismissDelay
*/
public int getDismissDelay() {
return insideTimer.getInitialDelay();
}
/** {@collect.stats}
* Used to specify the amount of time before the user has to wait
* <code>initialDelay</code> milliseconds before a tooltip will be
* shown. That is, if the tooltip is hidden, and the user moves into
* a region of the same Component that has a valid tooltip within
* <code>milliseconds</code> milliseconds the tooltip will immediately
* be shown. Otherwise, if the user moves into a region with a valid
* tooltip after <code>milliseconds</code> milliseconds, the user
* will have to wait an additional <code>initialDelay</code>
* milliseconds before the tooltip is shown again.
*
* @param milliseconds time in milliseconds
* @see #getReshowDelay
*/
public void setReshowDelay(int milliseconds) {
exitTimer.setInitialDelay(milliseconds);
}
/** {@collect.stats}
* Returns the reshow delay property.
*
* @return reshown delay property
* @see #setReshowDelay
*/
public int getReshowDelay() {
return exitTimer.getInitialDelay();
}
void showTipWindow() {
if(insideComponent == null || !insideComponent.isShowing())
return;
String mode = UIManager.getString("ToolTipManager.enableToolTipMode");
if ("activeApplication".equals(mode)) {
KeyboardFocusManager kfm =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
if (kfm.getFocusedWindow() == null) {
return;
}
}
if (enabled) {
Dimension size;
Point screenLocation = insideComponent.getLocationOnScreen();
Point location = new Point();
GraphicsConfiguration gc;
gc = insideComponent.getGraphicsConfiguration();
Rectangle sBounds = gc.getBounds();
Insets screenInsets = Toolkit.getDefaultToolkit()
.getScreenInsets(gc);
// Take into account screen insets, decrease viewport
sBounds.x += screenInsets.left;
sBounds.y += screenInsets.top;
sBounds.width -= (screenInsets.left + screenInsets.right);
sBounds.height -= (screenInsets.top + screenInsets.bottom);
boolean leftToRight
= SwingUtilities.isLeftToRight(insideComponent);
// Just to be paranoid
hideTipWindow();
tip = insideComponent.createToolTip();
tip.setTipText(toolTipText);
size = tip.getPreferredSize();
if(preferredLocation != null) {
location.x = screenLocation.x + preferredLocation.x;
location.y = screenLocation.y + preferredLocation.y;
if (!leftToRight) {
location.x -= size.width;
}
} else {
location.x = screenLocation.x + mouseEvent.getX();
location.y = screenLocation.y + mouseEvent.getY() + 20;
if (!leftToRight) {
if(location.x - size.width>=0) {
location.x -= size.width;
}
}
}
// we do not adjust x/y when using awt.Window tips
if (popupRect == null){
popupRect = new Rectangle();
}
popupRect.setBounds(location.x,location.y,
size.width,size.height);
// Fit as much of the tooltip on screen as possible
if (location.x < sBounds.x) {
location.x = sBounds.x;
}
else if (location.x - sBounds.x + size.width > sBounds.width) {
location.x = sBounds.x + Math.max(0, sBounds.width - size.width)
;
}
if (location.y < sBounds.y) {
location.y = sBounds.y;
}
else if (location.y - sBounds.y + size.height > sBounds.height) {
location.y = sBounds.y + Math.max(0, sBounds.height - size.height);
}
PopupFactory popupFactory = PopupFactory.getSharedInstance();
if (lightWeightPopupEnabled) {
int y = getPopupFitHeight(popupRect, insideComponent);
int x = getPopupFitWidth(popupRect,insideComponent);
if (x>0 || y>0) {
popupFactory.setPopupType(PopupFactory.MEDIUM_WEIGHT_POPUP);
} else {
popupFactory.setPopupType(PopupFactory.LIGHT_WEIGHT_POPUP);
}
}
else {
popupFactory.setPopupType(PopupFactory.MEDIUM_WEIGHT_POPUP);
}
tipWindow = popupFactory.getPopup(insideComponent, tip,
location.x,
location.y);
popupFactory.setPopupType(PopupFactory.LIGHT_WEIGHT_POPUP);
tipWindow.show();
Window componentWindow = SwingUtilities.windowForComponent(
insideComponent);
window = SwingUtilities.windowForComponent(tip);
if (window != null && window != componentWindow) {
window.addMouseListener(this);
}
else {
window = null;
}
insideTimer.start();
tipShowing = true;
}
}
void hideTipWindow() {
if (tipWindow != null) {
if (window != null) {
window.removeMouseListener(this);
window = null;
}
tipWindow.hide();
tipWindow = null;
tipShowing = false;
tip = null;
insideTimer.stop();
}
}
/** {@collect.stats}
* Returns a shared <code>ToolTipManager</code> instance.
*
* @return a shared <code>ToolTipManager</code> object
*/
public static ToolTipManager sharedInstance() {
Object value = SwingUtilities.appContextGet(TOOL_TIP_MANAGER_KEY);
if (value instanceof ToolTipManager) {
return (ToolTipManager) value;
}
ToolTipManager manager = new ToolTipManager();
SwingUtilities.appContextPut(TOOL_TIP_MANAGER_KEY, manager);
return manager;
}
// add keylistener here to trigger tip for access
/** {@collect.stats}
* Registers a component for tooltip management.
* <p>
* This will register key bindings to show and hide the tooltip text
* only if <code>component</code> has focus bindings. This is done
* so that components that are not normally focus traversable, such
* as <code>JLabel</code>, are not made focus traversable as a result
* of invoking this method.
*
* @param component a <code>JComponent</code> object to add
* @see JComponent#isFocusTraversable
*/
public void registerComponent(JComponent component) {
component.removeMouseListener(this);
component.addMouseListener(this);
component.removeMouseMotionListener(moveBeforeEnterListener);
component.addMouseMotionListener(moveBeforeEnterListener);
component.removeKeyListener(accessibilityKeyListener);
component.addKeyListener(accessibilityKeyListener);
}
/** {@collect.stats}
* Removes a component from tooltip control.
*
* @param component a <code>JComponent</code> object to remove
*/
public void unregisterComponent(JComponent component) {
component.removeMouseListener(this);
component.removeMouseMotionListener(moveBeforeEnterListener);
component.removeKeyListener(accessibilityKeyListener);
}
// implements java.awt.event.MouseListener
/** {@collect.stats}
* Called when the mouse enters the region of a component.
* This determines whether the tool tip should be shown.
*
* @param event the event in question
*/
public void mouseEntered(MouseEvent event) {
initiateToolTip(event);
}
private void initiateToolTip(MouseEvent event) {
if (event.getSource() == window) {
return;
}
JComponent component = (JComponent)event.getSource();
component.removeMouseMotionListener(moveBeforeEnterListener);
exitTimer.stop();
Point location = event.getPoint();
// ensure tooltip shows only in proper place
if (location.x < 0 ||
location.x >=component.getWidth() ||
location.y < 0 ||
location.y >= component.getHeight()) {
return;
}
if (insideComponent != null) {
enterTimer.stop();
}
// A component in an unactive internal frame is sent two
// mouseEntered events, make sure we don't end up adding
// ourselves an extra time.
component.removeMouseMotionListener(this);
component.addMouseMotionListener(this);
boolean sameComponent = (insideComponent == component);
insideComponent = component;
if (tipWindow != null){
mouseEvent = event;
if (showImmediately) {
String newToolTipText = component.getToolTipText(event);
Point newPreferredLocation = component.getToolTipLocation(
event);
boolean sameLoc = (preferredLocation != null) ?
preferredLocation.equals(newPreferredLocation) :
(newPreferredLocation == null);
if (!sameComponent || !toolTipText.equals(newToolTipText) ||
!sameLoc) {
toolTipText = newToolTipText;
preferredLocation = newPreferredLocation;
showTipWindow();
}
} else {
enterTimer.start();
}
}
}
// implements java.awt.event.MouseListener
/** {@collect.stats}
* Called when the mouse exits the region of a component.
* Any tool tip showing should be hidden.
*
* @param event the event in question
*/
public void mouseExited(MouseEvent event) {
boolean shouldHide = true;
if (insideComponent == null) {
// Drag exit
}
if (window != null && event.getSource() == window) {
// if we get an exit and have a heavy window
// we need to check if it if overlapping the inside component
Container insideComponentWindow = insideComponent.getTopLevelAncestor();
// insideComponent may be removed after tooltip is made visible
if (insideComponentWindow != null) {
Point location = event.getPoint();
SwingUtilities.convertPointToScreen(location, window);
location.x -= insideComponentWindow.getX();
location.y -= insideComponentWindow.getY();
location = SwingUtilities.convertPoint(null, location, insideComponent);
if (location.x >= 0 && location.x < insideComponent.getWidth() &&
location.y >= 0 && location.y < insideComponent.getHeight()) {
shouldHide = false;
} else {
shouldHide = true;
}
}
} else if(event.getSource() == insideComponent && tipWindow != null) {
Window win = SwingUtilities.getWindowAncestor(insideComponent);
if (win != null) { // insideComponent may have been hidden (e.g. in a menu)
Point location = SwingUtilities.convertPoint(insideComponent,
event.getPoint(),
win);
Rectangle bounds = insideComponent.getTopLevelAncestor().getBounds();
location.x += bounds.x;
location.y += bounds.y;
Point loc = new Point(0, 0);
SwingUtilities.convertPointToScreen(loc, tip);
bounds.x = loc.x;
bounds.y = loc.y;
bounds.width = tip.getWidth();
bounds.height = tip.getHeight();
if (location.x >= bounds.x && location.x < (bounds.x + bounds.width) &&
location.y >= bounds.y && location.y < (bounds.y + bounds.height)) {
shouldHide = false;
} else {
shouldHide = true;
}
}
}
if (shouldHide) {
enterTimer.stop();
if (insideComponent != null) {
insideComponent.removeMouseMotionListener(this);
}
insideComponent = null;
toolTipText = null;
mouseEvent = null;
hideTipWindow();
exitTimer.restart();
}
}
// implements java.awt.event.MouseListener
/** {@collect.stats}
* Called when the mouse is pressed.
* Any tool tip showing should be hidden.
*
* @param event the event in question
*/
public void mousePressed(MouseEvent event) {
hideTipWindow();
enterTimer.stop();
showImmediately = false;
insideComponent = null;
mouseEvent = null;
}
// implements java.awt.event.MouseMotionListener
/** {@collect.stats}
* Called when the mouse is pressed and dragged.
* Does nothing.
*
* @param event the event in question
*/
public void mouseDragged(MouseEvent event) {
}
// implements java.awt.event.MouseMotionListener
/** {@collect.stats}
* Called when the mouse is moved.
* Determines whether the tool tip should be displayed.
*
* @param event the event in question
*/
public void mouseMoved(MouseEvent event) {
if (tipShowing) {
checkForTipChange(event);
}
else if (showImmediately) {
JComponent component = (JComponent)event.getSource();
toolTipText = component.getToolTipText(event);
if (toolTipText != null) {
preferredLocation = component.getToolTipLocation(event);
mouseEvent = event;
insideComponent = component;
exitTimer.stop();
showTipWindow();
}
}
else {
// Lazily lookup the values from within insideTimerAction
insideComponent = (JComponent)event.getSource();
mouseEvent = event;
toolTipText = null;
enterTimer.restart();
}
}
/** {@collect.stats}
* Checks to see if the tooltip needs to be changed in response to
* the MouseMoved event <code>event</code>.
*/
private void checkForTipChange(MouseEvent event) {
JComponent component = (JComponent)event.getSource();
String newText = component.getToolTipText(event);
Point newPreferredLocation = component.getToolTipLocation(event);
if (newText != null || newPreferredLocation != null) {
mouseEvent = event;
if (((newText != null && newText.equals(toolTipText)) || newText == null) &&
((newPreferredLocation != null && newPreferredLocation.equals(preferredLocation))
|| newPreferredLocation == null)) {
if (tipWindow != null) {
insideTimer.restart();
} else {
enterTimer.restart();
}
} else {
toolTipText = newText;
preferredLocation = newPreferredLocation;
if (showImmediately) {
hideTipWindow();
showTipWindow();
exitTimer.stop();
} else {
enterTimer.restart();
}
}
} else {
toolTipText = null;
preferredLocation = null;
mouseEvent = null;
insideComponent = null;
hideTipWindow();
enterTimer.stop();
exitTimer.restart();
}
}
protected class insideTimerAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(insideComponent != null && insideComponent.isShowing()) {
// Lazy lookup
if (toolTipText == null && mouseEvent != null) {
toolTipText = insideComponent.getToolTipText(mouseEvent);
preferredLocation = insideComponent.getToolTipLocation(
mouseEvent);
}
if(toolTipText != null) {
showImmediately = true;
showTipWindow();
}
else {
insideComponent = null;
toolTipText = null;
preferredLocation = null;
mouseEvent = null;
hideTipWindow();
}
}
}
}
protected class outsideTimerAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
showImmediately = false;
}
}
protected class stillInsideTimerAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
hideTipWindow();
enterTimer.stop();
showImmediately = false;
insideComponent = null;
mouseEvent = null;
}
}
/* This listener is registered when the tooltip is first registered
* on a component in order to catch the situation where the tooltip
* was turned on while the mouse was already within the bounds of
* the component. This way, the tooltip will be initiated on a
* mouse-entered or mouse-moved, whichever occurs first. Once the
* tooltip has been initiated, we can remove this listener and rely
* solely on mouse-entered to initiate the tooltip.
*/
private class MoveBeforeEnterListener extends MouseMotionAdapter {
public void mouseMoved(MouseEvent e) {
initiateToolTip(e);
}
}
static Frame frameForComponent(Component component) {
while (!(component instanceof Frame)) {
component = component.getParent();
}
return (Frame)component;
}
private FocusListener createFocusChangeListener(){
return new FocusAdapter(){
public void focusLost(FocusEvent evt){
hideTipWindow();
insideComponent = null;
JComponent c = (JComponent)evt.getSource();
c.removeFocusListener(focusChangeListener);
}
};
}
// Returns: 0 no adjust
// -1 can't fit
// >0 adjust value by amount returned
private int getPopupFitWidth(Rectangle popupRectInScreen, Component invoker){
if (invoker != null){
Container parent;
for (parent = invoker.getParent(); parent != null; parent = parent.getParent()){
// fix internal frame size bug: 4139087 - 4159012
if(parent instanceof JFrame || parent instanceof JDialog ||
parent instanceof JWindow) { // no check for awt.Frame since we use Heavy tips
return getWidthAdjust(parent.getBounds(),popupRectInScreen);
} else if (parent instanceof JApplet || parent instanceof JInternalFrame) {
if (popupFrameRect == null){
popupFrameRect = new Rectangle();
}
Point p = parent.getLocationOnScreen();
popupFrameRect.setBounds(p.x,p.y,
parent.getBounds().width,
parent.getBounds().height);
return getWidthAdjust(popupFrameRect,popupRectInScreen);
}
}
}
return 0;
}
// Returns: 0 no adjust
// >0 adjust by value return
private int getPopupFitHeight(Rectangle popupRectInScreen, Component invoker){
if (invoker != null){
Container parent;
for (parent = invoker.getParent(); parent != null; parent = parent.getParent()){
if(parent instanceof JFrame || parent instanceof JDialog ||
parent instanceof JWindow) {
return getHeightAdjust(parent.getBounds(),popupRectInScreen);
} else if (parent instanceof JApplet || parent instanceof JInternalFrame) {
if (popupFrameRect == null){
popupFrameRect = new Rectangle();
}
Point p = parent.getLocationOnScreen();
popupFrameRect.setBounds(p.x,p.y,
parent.getBounds().width,
parent.getBounds().height);
return getHeightAdjust(popupFrameRect,popupRectInScreen);
}
}
}
return 0;
}
private int getHeightAdjust(Rectangle a, Rectangle b){
if (b.y >= a.y && (b.y + b.height) <= (a.y + a.height))
return 0;
else
return (((b.y + b.height) - (a.y + a.height)) + 5);
}
// Return the number of pixels over the edge we are extending.
// If we are over the edge the ToolTipManager can adjust.
// REMIND: what if the Tooltip is just too big to fit at all - we currently will just clip
private int getWidthAdjust(Rectangle a, Rectangle b){
// System.out.println("width b.x/b.width: " + b.x + "/" + b.width +
// "a.x/a.width: " + a.x + "/" + a.width);
if (b.x >= a.x && (b.x + b.width) <= (a.x + a.width)){
return 0;
}
else {
return (((b.x + b.width) - (a.x +a.width)) + 5);
}
}
//
// Actions
//
private void show(JComponent source) {
if (tipWindow != null) { // showing we unshow
hideTipWindow();
insideComponent = null;
}
else {
hideTipWindow(); // be safe
enterTimer.stop();
exitTimer.stop();
insideTimer.stop();
insideComponent = source;
if (insideComponent != null){
toolTipText = insideComponent.getToolTipText();
preferredLocation = new Point(10,insideComponent.getHeight()+
10); // manual set
showTipWindow();
// put a focuschange listener on to bring the tip down
if (focusChangeListener == null){
focusChangeListener = createFocusChangeListener();
}
insideComponent.addFocusListener(focusChangeListener);
}
}
}
private void hide(JComponent source) {
hideTipWindow();
source.removeFocusListener(focusChangeListener);
preferredLocation = null;
insideComponent = null;
}
/* This listener is registered when the tooltip is first registered
* on a component in order to process accessibility keybindings.
* This will apply globally across L&F
*
* Post Tip: Ctrl+F1
* Unpost Tip: Esc and Ctrl+F1
*/
private class AccessibilityKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if (!e.isConsumed()) {
JComponent source = (JComponent) e.getComponent();
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
if (tipWindow != null) {
hide(source);
e.consume();
}
} else if (e.getKeyCode() == KeyEvent.VK_F1
&& e.getModifiers() == Event.CTRL_MASK) {
// Shown tooltip will be hidden
ToolTipManager.this.show(source);
e.consume();
}
}
}
}
}
|
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.awt.event.*;
import javax.accessibility.*;
/** {@collect.stats}
* The main class for creating a dialog window. You can use this class
* to create a custom dialog, or invoke the many class methods
* in {@link JOptionPane} to create a variety of standard dialogs.
* For information about creating dialogs, see
* <em>The Java Tutorial</em> section
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html">How
* to Make Dialogs</a>.
*
* <p>
*
* The <code>JDialog</code> component contains a <code>JRootPane</code>
* as its only child.
* The <code>contentPane</code> should be the parent of any children of the
* <code>JDialog</code>.
* As a convenience <code>add</code> and its variants, <code>remove</code> and
* <code>setLayout</code> have been overridden to forward to the
* <code>contentPane</code> as necessary. This means you can write:
* <pre>
* dialog.add(child);
* </pre>
* And the child will be added to the contentPane.
* The <code>contentPane</code> is always non-<code>null</code>.
* Attempting to set it to <code>null</code> generates an exception.
* The default <code>contentPane</code> has a <code>BorderLayout</code>
* manager set on it.
* Refer to {@link javax.swing.RootPaneContainer}
* for details on adding, removing and setting the <code>LayoutManager</code>
* of a <code>JDialog</code>.
* <p>
* Please see the <code>JRootPane</code> documentation for a complete
* description of the <code>contentPane</code>, <code>glassPane</code>,
* and <code>layeredPane</code> components.
* <p>
* In a multi-screen environment, you can create a <code>JDialog</code>
* on a different screen device than its owner. See {@link java.awt.Frame} for
* more information.
* <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 JOptionPane
* @see JRootPane
* @see javax.swing.RootPaneContainer
*
* @beaninfo
* attribute: isContainer true
* attribute: containerDelegate getContentPane
* description: A toplevel window for creating dialog boxes.
*
* @author David Kloba
* @author James Gosling
* @author Scott Violet
*/
public class JDialog extends Dialog implements WindowConstants,
Accessible,
RootPaneContainer,
TransferHandler.HasGetTransferHandler
{
/** {@collect.stats}
* Key into the AppContext, used to check if should provide decorations
* by default.
*/
private static final Object defaultLookAndFeelDecoratedKey = new Object(); // JDialog.defaultLookAndFeelDecorated
private int defaultCloseOperation = HIDE_ON_CLOSE;
/** {@collect.stats}
* @see #getRootPane
* @see #setRootPane
*/
protected JRootPane rootPane;
/** {@collect.stats}
* If true then calls to <code>add</code> and <code>setLayout</code>
* will be forwarded to the <code>contentPane</code>. This is initially
* false, but is set to true when the <code>JDialog</code> is constructed.
*
* @see #isRootPaneCheckingEnabled
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean rootPaneCheckingEnabled = false;
/** {@collect.stats}
* The <code>TransferHandler</code> for this dialog.
*/
private TransferHandler transferHandler;
/** {@collect.stats}
* Creates a modeless dialog without a title and without a specified
* <code>Frame</code> owner. A shared, hidden frame will be
* set as the owner of the dialog.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
* <p>
* NOTE: This constructor does not allow you to create an unowned
* <code>JDialog</code>. To create an unowned <code>JDialog</code>
* you must use either the <code>JDialog(Window)</code> or
* <code>JDialog(Dialog)</code> constructor with an argument of
* <code>null</code>.
*
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JDialog() {
this((Frame)null, false);
}
/** {@collect.stats}
* Creates a modeless dialog without a title with the
* specified <code>Frame</code> as its owner. If <code>owner</code>
* is <code>null</code>, a shared, hidden frame will be set as the
* owner of the dialog.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
* <p>
* NOTE: This constructor does not allow you to create an unowned
* <code>JDialog</code>. To create an unowned <code>JDialog</code>
* you must use either the <code>JDialog(Window)</code> or
* <code>JDialog(Dialog)</code> constructor with an argument of
* <code>null</code>.
*
* @param owner the <code>Frame</code> from which the dialog is displayed
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JDialog(Frame owner) {
this(owner, false);
}
/** {@collect.stats}
* Creates a dialog with the specified owner <code>Frame</code>, modality
* and an empty title. If <code>owner</code> is <code>null</code>,
* a shared, hidden frame will be set as the owner of the dialog.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
* <p>
* NOTE: This constructor does not allow you to create an unowned
* <code>JDialog</code>. To create an unowned <code>JDialog</code>
* you must use either the <code>JDialog(Window)</code> or
* <code>JDialog(Dialog)</code> constructor with an argument of
* <code>null</code>.
*
* @param owner the <code>Frame</code> from which the dialog is displayed
* @param modal specifies whether dialog blocks user input to other top-level
* windows when shown. If <code>true</code>, the modality type property is set to
* <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless.
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JDialog(Frame owner, boolean modal) {
this(owner, null, modal);
}
/** {@collect.stats}
* Creates a modeless dialog with the specified title and
* with the specified owner frame. If <code>owner</code>
* is <code>null</code>, a shared, hidden frame will be set as the
* owner of the dialog.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
* <p>
* NOTE: This constructor does not allow you to create an unowned
* <code>JDialog</code>. To create an unowned <code>JDialog</code>
* you must use either the <code>JDialog(Window)</code> or
* <code>JDialog(Dialog)</code> constructor with an argument of
* <code>null</code>.
*
* @param owner the <code>Frame</code> from which the dialog is displayed
* @param title the <code>String</code> to display in the dialog's
* title bar
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JDialog(Frame owner, String title) {
this(owner, title, false);
}
/** {@collect.stats}
* Creates a dialog with the specified title, owner <code>Frame</code>
* and modality. If <code>owner</code> is <code>null</code>,
* a shared, hidden frame will be set as the owner of this dialog.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
* <p>
* NOTE: Any popup components (<code>JComboBox</code>,
* <code>JPopupMenu</code>, <code>JMenuBar</code>)
* created within a modal dialog will be forced to be lightweight.
* <p>
* NOTE: This constructor does not allow you to create an unowned
* <code>JDialog</code>. To create an unowned <code>JDialog</code>
* you must use either the <code>JDialog(Window)</code> or
* <code>JDialog(Dialog)</code> constructor with an argument of
* <code>null</code>.
*
* @param owner the <code>Frame</code> from which the dialog is displayed
* @param title the <code>String</code> to display in the dialog's
* title bar
* @param modal specifies whether dialog blocks user input to other top-level
* windows when shown. If <code>true</code>, the modality type property is set to
* <code>DEFAULT_MODALITY_TYPE</code> otherwise the dialog is modeless
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
*
* @see java.awt.Dialog.ModalityType
* @see java.awt.Dialog.ModalityType#MODELESS
* @see java.awt.Dialog#DEFAULT_MODALITY_TYPE
* @see java.awt.Dialog#setModal
* @see java.awt.Dialog#setModalityType
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JDialog(Frame owner, String title, boolean modal) {
super(owner == null? SwingUtilities.getSharedOwnerFrame() : owner,
title, modal);
if (owner == null) {
WindowListener ownerShutdownListener =
(WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
addWindowListener(ownerShutdownListener);
}
dialogInit();
}
/** {@collect.stats}
* Creates a dialog with the specified title,
* owner <code>Frame</code>, modality and <code>GraphicsConfiguration</code>.
* If <code>owner</code> is <code>null</code>,
* a shared, hidden frame will be set as the owner of this dialog.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
* <p>
* NOTE: Any popup components (<code>JComboBox</code>,
* <code>JPopupMenu</code>, <code>JMenuBar</code>)
* created within a modal dialog will be forced to be lightweight.
* <p>
* NOTE: This constructor does not allow you to create an unowned
* <code>JDialog</code>. To create an unowned <code>JDialog</code>
* you must use either the <code>JDialog(Window)</code> or
* <code>JDialog(Dialog)</code> constructor with an argument of
* <code>null</code>.
*
* @param owner the <code>Frame</code> from which the dialog is displayed
* @param title the <code>String</code> to display in the dialog's
* title bar
* @param modal specifies whether dialog blocks user input to other top-level
* windows when shown. If <code>true</code>, the modality type property is set to
* <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless.
* @param gc the <code>GraphicsConfiguration</code>
* of the target screen device. If <code>gc</code> is
* <code>null</code>, the same
* <code>GraphicsConfiguration</code> as the owning Frame is used.
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.Dialog.ModalityType
* @see java.awt.Dialog.ModalityType#MODELESS
* @see java.awt.Dialog#DEFAULT_MODALITY_TYPE
* @see java.awt.Dialog#setModal
* @see java.awt.Dialog#setModalityType
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
* @since 1.4
*/
public JDialog(Frame owner, String title, boolean modal,
GraphicsConfiguration gc) {
super(owner == null? SwingUtilities.getSharedOwnerFrame() : owner,
title, modal, gc);
if (owner == null) {
WindowListener ownerShutdownListener =
(WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
addWindowListener(ownerShutdownListener);
}
dialogInit();
}
/** {@collect.stats}
* Creates a modeless dialog without a title with the
* specified <code>Dialog</code> as its owner.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the owner <code>Dialog</code> from which the dialog is displayed
* or <code>null</code> if this dialog has no owner
* @exception HeadlessException <code>if GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JDialog(Dialog owner) {
this(owner, false);
}
/** {@collect.stats}
* Creates a dialog with the specified owner <code>Dialog</code> and modality.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the owner <code>Dialog</code> from which the dialog is displayed
* or <code>null</code> if this dialog has no owner
* @param modal specifies whether dialog blocks user input to other top-level
* windows when shown. If <code>true</code>, the modality type property is set to
* <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless.
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.Dialog.ModalityType
* @see java.awt.Dialog.ModalityType#MODELESS
* @see java.awt.Dialog#DEFAULT_MODALITY_TYPE
* @see java.awt.Dialog#setModal
* @see java.awt.Dialog#setModalityType
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JDialog(Dialog owner, boolean modal) {
this(owner, null, modal);
}
/** {@collect.stats}
* Creates a modeless dialog with the specified title and
* with the specified owner dialog.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the owner <code>Dialog</code> from which the dialog is displayed
* or <code>null</code> if this dialog has no owner
* @param title the <code>String</code> to display in the dialog's
* title bar
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JDialog(Dialog owner, String title) {
this(owner, title, false);
}
/** {@collect.stats}
* Creates a dialog with the specified title, modality
* and the specified owner <code>Dialog</code>.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the owner <code>Dialog</code> from which the dialog is displayed
* or <code>null</code> if this dialog has no owner
* @param title the <code>String</code> to display in the dialog's
* title bar
* @param modal specifies whether dialog blocks user input to other top-level
* windows when shown. If <code>true</code>, the modality type property is set to
* <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.Dialog.ModalityType
* @see java.awt.Dialog.ModalityType#MODELESS
* @see java.awt.Dialog#DEFAULT_MODALITY_TYPE
* @see java.awt.Dialog#setModal
* @see java.awt.Dialog#setModalityType
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JDialog(Dialog owner, String title, boolean modal) {
super(owner, title, modal);
dialogInit();
}
/** {@collect.stats}
* Creates a dialog with the specified title, owner <code>Dialog</code>,
* modality and <code>GraphicsConfiguration</code>.
*
* <p>
* NOTE: Any popup components (<code>JComboBox</code>,
* <code>JPopupMenu</code>, <code>JMenuBar</code>)
* created within a modal dialog will be forced to be lightweight.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the owner <code>Dialog</code> from which the dialog is displayed
* or <code>null</code> if this dialog has no owner
* @param title the <code>String</code> to display in the dialog's
* title bar
* @param modal specifies whether dialog blocks user input to other top-level
* windows when shown. If <code>true</code>, the modality type property is set to
* <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless
* @param gc the <code>GraphicsConfiguration</code>
* of the target screen device. If <code>gc</code> is
* <code>null</code>, the same
* <code>GraphicsConfiguration</code> as the owning Dialog is used.
* @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>.
* @see java.awt.Dialog.ModalityType
* @see java.awt.Dialog.ModalityType#MODELESS
* @see java.awt.Dialog#DEFAULT_MODALITY_TYPE
* @see java.awt.Dialog#setModal
* @see java.awt.Dialog#setModalityType
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
* @since 1.4
*/
public JDialog(Dialog owner, String title, boolean modal,
GraphicsConfiguration gc) {
super(owner, title, modal, gc);
dialogInit();
}
/** {@collect.stats}
* Creates a modeless dialog with the specified owner <code>Window</code> and
* an empty title.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the <code>Window</code> from which the dialog is displayed or
* <code>null</code> if this dialog has no owner
* @exception HeadlessException when
* <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
*
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*
* @since 1.6
*/
public JDialog(Window owner) {
this(owner, Dialog.ModalityType.MODELESS);
}
/** {@collect.stats}
* Creates a dialog with the specified owner <code>Window</code>, modality
* and an empty title.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the <code>Window</code> from which the dialog is displayed or
* <code>null</code> if this dialog has no owner
* @param modalityType specifies whether dialog blocks input to other
* windows when shown. <code>null</code> value and unsupported modality
* types are equivalent to <code>MODELESS</code>
* @exception HeadlessException when
* <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
*
* @see java.awt.Dialog.ModalityType
* @see java.awt.Dialog#setModal
* @see java.awt.Dialog#setModalityType
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*
* @since 1.6
*/
public JDialog(Window owner, ModalityType modalityType) {
this(owner, null, modalityType);
}
/** {@collect.stats}
* Creates a modeless dialog with the specified title and owner
* <code>Window</code>.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the <code>Window</code> from which the dialog is displayed or
* <code>null</code> if this dialog has no owner
* @param title the <code>String</code> to display in the dialog's
* title bar or <code>null</code> if the dialog has no title
* @exception java.awt.HeadlessException when
* <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
*
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*
* @since 1.6
*/
public JDialog(Window owner, String title) {
this(owner, title, Dialog.ModalityType.MODELESS);
}
/** {@collect.stats}
* Creates a dialog with the specified title, owner <code>Window</code> and
* modality.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the <code>Window</code> from which the dialog is displayed or
* <code>null</code> if this dialog has no owner
* @param title the <code>String</code> to display in the dialog's
* title bar or <code>null</code> if the dialog has no title
* @param modalityType specifies whether dialog blocks input to other
* windows when shown. <code>null</code> value and unsupported modality
* types are equivalent to <code>MODELESS</code>
* @exception java.awt.HeadlessException when
* <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
*
* @see java.awt.Dialog.ModalityType
* @see java.awt.Dialog#setModal
* @see java.awt.Dialog#setModalityType
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*
* @since 1.6
*/
public JDialog(Window owner, String title, Dialog.ModalityType modalityType) {
super(owner, title, modalityType);
dialogInit();
}
/** {@collect.stats}
* Creates a dialog with the specified title, owner <code>Window</code>,
* modality and <code>GraphicsConfiguration</code>.
* <p>
* NOTE: Any popup components (<code>JComboBox</code>,
* <code>JPopupMenu</code>, <code>JMenuBar</code>)
* created within a modal dialog will be forced to be lightweight.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the <code>Window</code> from which the dialog is displayed or
* <code>null</code> if this dialog has no owner
* @param title the <code>String</code> to display in the dialog's
* title bar or <code>null</code> if the dialog has no title
* @param modalityType specifies whether dialog blocks input to other
* windows when shown. <code>null</code> value and unsupported modality
* types are equivalent to <code>MODELESS</code>
* @param gc the <code>GraphicsConfiguration</code> of the target screen device;
* if <code>null</code>, the <code>GraphicsConfiguration</code> from the owning
* window is used; if <code>owner</code> is also <code>null</code>, the
* system default <code>GraphicsConfiguration</code> is assumed
* @exception java.awt.HeadlessException when
* <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
*
* @see java.awt.Dialog.ModalityType
* @see java.awt.Dialog#setModal
* @see java.awt.Dialog#setModalityType
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*
* @since 1.6
*/
public JDialog(Window owner, String title, Dialog.ModalityType modalityType,
GraphicsConfiguration gc) {
super(owner, title, modalityType, gc);
dialogInit();
}
/** {@collect.stats}
* Called by the constructors to init the <code>JDialog</code> properly.
*/
protected void dialogInit() {
enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK);
setLocale( JComponent.getDefaultLocale() );
setRootPane(createRootPane());
setRootPaneCheckingEnabled(true);
if (JDialog.isDefaultLookAndFeelDecorated()) {
boolean supportsWindowDecorations =
UIManager.getLookAndFeel().getSupportsWindowDecorations();
if (supportsWindowDecorations) {
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
}
}
sun.awt.SunToolkit.checkAndSetPolicy(this, true);
}
/** {@collect.stats}
* Called by the constructor methods to create the default
* <code>rootPane</code>.
*/
protected JRootPane createRootPane() {
JRootPane rp = 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.
rp.setOpaque(true);
return rp;
}
/** {@collect.stats}
* Handles window events depending on the state of the
* <code>defaultCloseOperation</code> property.
*
* @see #setDefaultCloseOperation
*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
switch(defaultCloseOperation) {
case HIDE_ON_CLOSE:
setVisible(false);
break;
case DISPOSE_ON_CLOSE:
dispose();
break;
case DO_NOTHING_ON_CLOSE:
default:
break;
}
}
}
/** {@collect.stats}
* Sets the operation that will happen by default when
* the user initiates a "close" on this dialog.
* You must specify one of the following choices:
* <p>
* <ul>
* <li><code>DO_NOTHING_ON_CLOSE</code>
* (defined in <code>WindowConstants</code>):
* Don't do anything; require the
* program to handle the operation in the <code>windowClosing</code>
* method of a registered <code>WindowListener</code> object.
*
* <li><code>HIDE_ON_CLOSE</code>
* (defined in <code>WindowConstants</code>):
* Automatically hide the dialog after
* invoking any registered <code>WindowListener</code>
* objects.
*
* <li><code>DISPOSE_ON_CLOSE</code>
* (defined in <code>WindowConstants</code>):
* Automatically hide and dispose the
* dialog after invoking any registered <code>WindowListener</code>
* objects.
* </ul>
* <p>
* The value is set to <code>HIDE_ON_CLOSE</code> by default. Changes
* to the value of this property cause the firing of a property
* change event, with property name "defaultCloseOperation".
* <p>
* <b>Note</b>: When the last displayable window within the
* Java virtual machine (VM) is disposed of, the VM may
* terminate. See <a href="../../java/awt/doc-files/AWTThreadIssues.html">
* AWT Threading Issues</a> for more information.
*
* @param operation the operation which should be performed when the
* user closes the dialog
* @throws IllegalArgumentException if defaultCloseOperation value
* isn't one of the above valid values
* @see #addWindowListener
* @see #getDefaultCloseOperation
* @see WindowConstants
*
* @beaninfo
* preferred: true
* bound: true
* enum: DO_NOTHING_ON_CLOSE WindowConstants.DO_NOTHING_ON_CLOSE
* HIDE_ON_CLOSE WindowConstants.HIDE_ON_CLOSE
* DISPOSE_ON_CLOSE WindowConstants.DISPOSE_ON_CLOSE
* description: The dialog's default close operation.
*/
public void setDefaultCloseOperation(int operation) {
if (operation != DO_NOTHING_ON_CLOSE &&
operation != HIDE_ON_CLOSE &&
operation != DISPOSE_ON_CLOSE) {
throw new IllegalArgumentException("defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, or DISPOSE_ON_CLOSE");
}
int oldValue = this.defaultCloseOperation;
this.defaultCloseOperation = operation;
firePropertyChange("defaultCloseOperation", oldValue, operation);
}
/** {@collect.stats}
* Returns the operation which occurs when the user
* initiates a "close" on this dialog.
*
* @return an integer indicating the window-close operation
* @see #setDefaultCloseOperation
*/
public int getDefaultCloseOperation() {
return defaultCloseOperation;
}
/** {@collect.stats}
* Sets the {@code transferHandler} property, which is a mechanism to
* support transfer of data into this component. Use {@code null}
* if the component does not support data transfer operations.
* <p>
* If the system property {@code suppressSwingDropSupport} is {@code false}
* (the default) and the current drop target on this component is either
* {@code null} or not a user-set drop target, this method will change the
* drop target as follows: If {@code newHandler} is {@code null} it will
* clear the drop target. If not {@code null} it will install a new
* {@code DropTarget}.
* <p>
* Note: When used with {@code JDialog}, {@code TransferHandler} only
* provides data import capability, as the data export related methods
* are currently typed to {@code JComponent}.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html">
* How to Use Drag and Drop and Data Transfer</a>, a section in
* <em>The Java Tutorial</em>, for more information.
*
* @param newHandler the new {@code TransferHandler}
*
* @see TransferHandler
* @see #getTransferHandler
* @see java.awt.Component#setDropTarget
* @since 1.6
*
* @beaninfo
* bound: true
* hidden: true
* description: Mechanism for transfer of data into the component
*/
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = transferHandler;
transferHandler = newHandler;
SwingUtilities.installSwingDropTargetAsNecessary(this, transferHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
/** {@collect.stats}
* Gets the <code>transferHandler</code> property.
*
* @return the value of the <code>transferHandler</code> property
*
* @see TransferHandler
* @see #setTransferHandler
* @since 1.6
*/
public TransferHandler getTransferHandler() {
return transferHandler;
}
/** {@collect.stats}
* Calls <code>paint(g)</code>. This method was overridden to
* prevent an unnecessary call to clear the background.
*
* @param g the <code>Graphics</code> context in which to paint
*/
public void update(Graphics g) {
paint(g);
}
/** {@collect.stats}
* Sets the menubar for this dialog.
*
* @param menu the menubar being placed in the dialog
*
* @see #getJMenuBar
*
* @beaninfo
* hidden: true
* description: The menubar for accessing pulldown menus from this dialog.
*/
public void setJMenuBar(JMenuBar menu) {
getRootPane().setMenuBar(menu);
}
/** {@collect.stats}
* Returns the menubar set on this dialog.
*
* @see #setJMenuBar
*/
public JMenuBar getJMenuBar() {
return getRootPane().getMenuBar();
}
/** {@collect.stats}
* Returns whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @return true if <code>add</code> and <code>setLayout</code>
* are fowarded; false otherwise
*
* @see #addImpl
* @see #setLayout
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean isRootPaneCheckingEnabled() {
return rootPaneCheckingEnabled;
}
/** {@collect.stats}
* Sets whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @param enabled true if <code>add</code> and <code>setLayout</code>
* are forwarded, false if they should operate directly on the
* <code>JDialog</code>.
*
* @see #addImpl
* @see #setLayout
* @see #isRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
* @beaninfo
* hidden: true
* description: Whether the add and setLayout methods are forwarded
*/
protected void setRootPaneCheckingEnabled(boolean enabled) {
rootPaneCheckingEnabled = enabled;
}
/** {@collect.stats}
* Adds the specified child <code>Component</code>.
* This method is overridden to conditionally forward calls to the
* <code>contentPane</code>.
* By default, children are added to the <code>contentPane</code> instead
* of the frame, refer to {@link javax.swing.RootPaneContainer} for
* details.
*
* @param comp the component to be enhanced
* @param constraints the constraints to be respected
* @param index the index
* @exception IllegalArgumentException if <code>index</code> is invalid
* @exception IllegalArgumentException if adding the container's parent
* to itself
* @exception IllegalArgumentException if adding a window to a container
*
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected void addImpl(Component comp, Object constraints, int index)
{
if(isRootPaneCheckingEnabled()) {
getContentPane().add(comp, constraints, index);
}
else {
super.addImpl(comp, constraints, index);
}
}
/** {@collect.stats}
* Removes the specified component from the container. If
* <code>comp</code> is not the <code>rootPane</code>, this will forward
* the call to the <code>contentPane</code>. This will do nothing if
* <code>comp</code> is not a child of the <code>JDialog</code> or
* <code>contentPane</code>.
*
* @param comp the component to be removed
* @throws NullPointerException if <code>comp</code> is null
* @see #add
* @see javax.swing.RootPaneContainer
*/
public void remove(Component comp) {
if (comp == rootPane) {
super.remove(comp);
} else {
getContentPane().remove(comp);
}
}
/** {@collect.stats}
* Sets the <code>LayoutManager</code>.
* Overridden to conditionally forward the call to the
* <code>contentPane</code>.
* Refer to {@link javax.swing.RootPaneContainer} for
* more information.
*
* @param manager the <code>LayoutManager</code>
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
public void setLayout(LayoutManager manager) {
if(isRootPaneCheckingEnabled()) {
getContentPane().setLayout(manager);
}
else {
super.setLayout(manager);
}
}
/** {@collect.stats}
* Returns the <code>rootPane</code> object for this dialog.
*
* @see #setRootPane
* @see RootPaneContainer#getRootPane
*/
public JRootPane getRootPane() {
return rootPane;
}
/** {@collect.stats}
* Sets the <code>rootPane</code> property.
* This method is called by the constructor.
*
* @param root the <code>rootPane</code> object for this dialog
*
* @see #getRootPane
*
* @beaninfo
* hidden: true
* description: the RootPane object for this dialog.
*/
protected void setRootPane(JRootPane root) {
if(rootPane != null) {
remove(rootPane);
}
rootPane = root;
if(rootPane != null) {
boolean checkingEnabled = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
add(rootPane, BorderLayout.CENTER);
}
finally {
setRootPaneCheckingEnabled(checkingEnabled);
}
}
}
/** {@collect.stats}
* Returns the <code>contentPane</code> object for this dialog.
*
* @return the <code>contentPane</code> property
*
* @see #setContentPane
* @see RootPaneContainer#getContentPane
*/
public Container getContentPane() {
return getRootPane().getContentPane();
}
/** {@collect.stats}
* Sets the <code>contentPane</code> property.
* This method is called by the constructor.
* <p>
* Swing's painting architecture requires an opaque <code>JComponent</code>
* in the containment hiearchy. This is typically provided by the
* content pane. If you replace the content pane it is recommended you
* replace it with an opaque <code>JComponent</code>.
* @see JRootPane
*
* @param contentPane the <code>contentPane</code> object for this dialog
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the content pane parameter is <code>null</code>
* @see #getContentPane
* @see RootPaneContainer#setContentPane
*
* @beaninfo
* hidden: true
* description: The client area of the dialog where child
* components are normally inserted.
*/
public void setContentPane(Container contentPane) {
getRootPane().setContentPane(contentPane);
}
/** {@collect.stats}
* Returns the <code>layeredPane</code> object for this dialog.
*
* @return the <code>layeredPane</code> property
*
* @see #setLayeredPane
* @see RootPaneContainer#getLayeredPane
*/
public JLayeredPane getLayeredPane() {
return getRootPane().getLayeredPane();
}
/** {@collect.stats}
* Sets the <code>layeredPane</code> property.
* This method is called by the constructor.
*
* @param layeredPane the new <code>layeredPane</code> property
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the layered pane parameter is null
* @see #getLayeredPane
* @see RootPaneContainer#setLayeredPane
*
* @beaninfo
* hidden: true
* description: The pane which holds the various dialog layers.
*/
public void setLayeredPane(JLayeredPane layeredPane) {
getRootPane().setLayeredPane(layeredPane);
}
/** {@collect.stats}
* Returns the <code>glassPane</code> object for this dialog.
*
* @return the <code>glassPane</code> property
*
* @see #setGlassPane
* @see RootPaneContainer#getGlassPane
*/
public Component getGlassPane() {
return getRootPane().getGlassPane();
}
/** {@collect.stats}
* Sets the <code>glassPane</code> property.
* This method is called by the constructor.
*
* @param glassPane the <code>glassPane</code> object for this dialog
* @see #getGlassPane
* @see RootPaneContainer#setGlassPane
*
* @beaninfo
* hidden: true
* description: A transparent pane used for menu rendering.
*/
public void setGlassPane(Component glassPane) {
getRootPane().setGlassPane(glassPane);
}
/** {@collect.stats}
* {@inheritDoc}
*
* @since 1.6
*/
public Graphics getGraphics() {
JComponent.getGraphicsInvoked(this);
return super.getGraphics();
}
/** {@collect.stats}
* Repaints the specified rectangle of this component within
* <code>time</code> milliseconds. Refer to <code>RepaintManager</code>
* for details on how the repaint is handled.
*
* @param time maximum time in milliseconds before update
* @param x the <i>x</i> coordinate
* @param y the <i>y</i> coordinate
* @param width the width
* @param height the height
* @see RepaintManager
* @since 1.6
*/
public void repaint(long time, int x, int y, int width, int height) {
if (RepaintManager.HANDLE_TOP_LEVEL_PAINT) {
RepaintManager.currentManager(this).addDirtyRegion(
this, x, y, width, height);
}
else {
super.repaint(time, x, y, width, height);
}
}
/** {@collect.stats}
* Provides a hint as to whether or not newly created <code>JDialog</code>s
* should have their Window decorations (such as borders, widgets to
* close the window, title...) provided by the current look
* and feel. If <code>defaultLookAndFeelDecorated</code> is true,
* the current <code>LookAndFeel</code> supports providing window
* decorations, and the current window manager supports undecorated
* windows, then newly created <code>JDialog</code>s will have their
* Window decorations provided by the current <code>LookAndFeel</code>.
* Otherwise, newly created <code>JDialog</code>s will have their
* Window decorations provided by the current window manager.
* <p>
* You can get the same effect on a single JDialog by doing the following:
* <pre>
* JDialog dialog = new JDialog();
* dialog.setUndecorated(true);
* dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
* </pre>
*
* @param defaultLookAndFeelDecorated A hint as to whether or not current
* look and feel should provide window decorations
* @see javax.swing.LookAndFeel#getSupportsWindowDecorations
* @since 1.4
*/
public static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated) {
if (defaultLookAndFeelDecorated) {
SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.TRUE);
} else {
SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.FALSE);
}
}
/** {@collect.stats}
* Returns true if newly created <code>JDialog</code>s should have their
* Window decorations provided by the current look and feel. This is only
* a hint, as certain look and feels may not support this feature.
*
* @return true if look and feel should provide Window decorations.
* @since 1.4
*/
public static boolean isDefaultLookAndFeelDecorated() {
Boolean defaultLookAndFeelDecorated =
(Boolean) SwingUtilities.appContextGet(defaultLookAndFeelDecoratedKey);
if (defaultLookAndFeelDecorated == null) {
defaultLookAndFeelDecorated = Boolean.FALSE;
}
return defaultLookAndFeelDecorated.booleanValue();
}
/** {@collect.stats}
* Returns a string representation of this <code>JDialog</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>JDialog</code>.
*/
protected String paramString() {
String defaultCloseOperationString;
if (defaultCloseOperation == HIDE_ON_CLOSE) {
defaultCloseOperationString = "HIDE_ON_CLOSE";
} else if (defaultCloseOperation == DISPOSE_ON_CLOSE) {
defaultCloseOperationString = "DISPOSE_ON_CLOSE";
} else if (defaultCloseOperation == DO_NOTHING_ON_CLOSE) {
defaultCloseOperationString = "DO_NOTHING_ON_CLOSE";
} else defaultCloseOperationString = "";
String rootPaneString = (rootPane != null ?
rootPane.toString() : "");
String rootPaneCheckingEnabledString = (rootPaneCheckingEnabled ?
"true" : "false");
return super.paramString() +
",defaultCloseOperation=" + defaultCloseOperationString +
",rootPane=" + rootPaneString +
",rootPaneCheckingEnabled=" + rootPaneCheckingEnabledString;
}
/////////////////
// Accessibility support
////////////////
protected AccessibleContext accessibleContext = null;
/** {@collect.stats}
* Gets the AccessibleContext associated with this JDialog.
* For JDialogs, the AccessibleContext takes the form of an
* AccessibleJDialog.
* A new AccessibleJDialog instance is created if necessary.
*
* @return an AccessibleJDialog that serves as the
* AccessibleContext of this JDialog
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJDialog();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JDialog</code> class. It provides an implementation of the
* Java Accessibility API appropriate to dialog user-interface
* elements.
*/
protected class AccessibleJDialog extends AccessibleAWTDialog {
// AccessibleContext methods
//
/** {@collect.stats}
* Get the accessible name of this object.
*
* @return the localized name of the object -- can be null if this
* object does not have a name
*/
public String getAccessibleName() {
if (accessibleName != null) {
return accessibleName;
} else {
if (getTitle() == null) {
return super.getAccessibleName();
} else {
return getTitle();
}
}
}
/** {@collect.stats}
* Get the state of this object.
*
* @return an instance of AccessibleStateSet containing the current
* state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (isResizable()) {
states.add(AccessibleState.RESIZABLE);
}
if (getFocusOwner() != null) {
states.add(AccessibleState.ACTIVE);
}
if (isModal()) {
states.add(AccessibleState.MODAL);
}
return states;
}
} // inner class AccessibleJDialog
}
|
Java
|
/*
* Copyright (c) 1997, 2010, 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.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Set;
/** {@collect.stats}
*
* @author Hans Muller
*/
class MultiUIDefaults extends UIDefaults
{
private UIDefaults[] tables;
public MultiUIDefaults(UIDefaults[] defaults) {
super();
tables = defaults;
}
public MultiUIDefaults() {
super();
tables = new UIDefaults[0];
}
@Override
public Object get(Object key)
{
Object value = super.get(key);
if (value != null) {
return value;
}
for(int i = 0; i < tables.length; i++) {
UIDefaults table = tables[i];
value = (table != null) ? table.get(key) : null;
if (value != null) {
return value;
}
}
return null;
}
@Override
public Object get(Object key, Locale l)
{
Object value = super.get(key,l);
if (value != null) {
return value;
}
for(int i = 0; i < tables.length; i++) {
UIDefaults table = tables[i];
value = (table != null) ? table.get(key,l) : null;
if (value != null) {
return value;
}
}
return null;
}
@Override
public int size() {
return entrySet().size();
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public Enumeration keys()
{
return new MultiUIDefaultsEnumerator(
MultiUIDefaultsEnumerator.Type.KEYS, entrySet());
}
@Override
public Enumeration elements()
{
return new MultiUIDefaultsEnumerator(
MultiUIDefaultsEnumerator.Type.ELEMENTS, entrySet());
}
@Override
public Set<Entry<Object, Object>> entrySet() {
Set<Entry<Object, Object>> set = new HashSet<Entry<Object, Object>>();
for (int i = tables.length - 1; i >= 0; i--) {
if (tables[i] != null) {
set.addAll(tables[i].entrySet());
}
}
set.addAll(super.entrySet());
return set;
}
@Override
protected void getUIError(String msg) {
if (tables.length > 0) {
tables[0].getUIError(msg);
} else {
super.getUIError(msg);
}
}
private static class MultiUIDefaultsEnumerator implements Enumeration
{
public static enum Type { KEYS, ELEMENTS };
private Iterator<Entry<Object, Object>> iterator;
private Type type;
MultiUIDefaultsEnumerator(Type type, Set<Entry<Object, Object>> entries) {
this.type = type;
this.iterator = entries.iterator();
}
public boolean hasMoreElements() {
return iterator.hasNext();
}
public Object nextElement() {
switch (type) {
case KEYS: return iterator.next().getKey();
case ELEMENTS: return iterator.next().getValue();
default: return null;
}
}
}
@Override
public Object remove(Object key)
{
Object value = null;
for (int i = tables.length - 1; i >= 0; i--) {
if (tables[i] != null) {
Object v = tables[i].remove(key);
if (v != null) {
value = v;
}
}
}
Object v = super.remove(key);
if (v != null) {
value = v;
}
return value;
}
@Override
public void clear() {
super.clear();
for(int i = 0; i < tables.length; i++) {
UIDefaults table = tables[i];
if (table != null) {
table.clear();
}
}
}
@Override
public synchronized String toString() {
StringBuffer buf = new StringBuffer();
buf.append("{");
Enumeration keys = keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
buf.append(key + "=" + get(key) + ", ");
}
int length = buf.length();
if (length > 1) {
buf.delete(length-2, length);
}
buf.append("}");
return buf.toString();
}
}
|
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;
import java.beans.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.border.*;
import javax.accessibility.*;
/** {@collect.stats}
* The default model for combo boxes.
*
* @author Arnaud Weber
* @author Tom Santos
*/
public class DefaultComboBoxModel extends AbstractListModel implements MutableComboBoxModel, Serializable {
Vector objects;
Object selectedObject;
/** {@collect.stats}
* Constructs an empty DefaultComboBoxModel object.
*/
public DefaultComboBoxModel() {
objects = new Vector();
}
/** {@collect.stats}
* Constructs a DefaultComboBoxModel object initialized with
* an array of objects.
*
* @param items an array of Object objects
*/
public DefaultComboBoxModel(final Object items[]) {
objects = new Vector();
objects.ensureCapacity( items.length );
int i,c;
for ( i=0,c=items.length;i<c;i++ )
objects.addElement(items[i]);
if ( getSize() > 0 ) {
selectedObject = getElementAt( 0 );
}
}
/** {@collect.stats}
* Constructs a DefaultComboBoxModel object initialized with
* a vector.
*
* @param v a Vector object ...
*/
public DefaultComboBoxModel(Vector<?> v) {
objects = v;
if ( getSize() > 0 ) {
selectedObject = getElementAt( 0 );
}
}
// implements javax.swing.ComboBoxModel
/** {@collect.stats}
* Set the value of the selected item. The selected item may be null.
* <p>
* @param anObject The combo box value or null for no selection.
*/
public void setSelectedItem(Object anObject) {
if ((selectedObject != null && !selectedObject.equals( anObject )) ||
selectedObject == null && anObject != null) {
selectedObject = anObject;
fireContentsChanged(this, -1, -1);
}
}
// implements javax.swing.ComboBoxModel
public Object getSelectedItem() {
return selectedObject;
}
// implements javax.swing.ListModel
public int getSize() {
return objects.size();
}
// implements javax.swing.ListModel
public Object getElementAt(int index) {
if ( index >= 0 && index < objects.size() )
return objects.elementAt(index);
else
return null;
}
/** {@collect.stats}
* Returns the index-position of the specified object in the list.
*
* @param anObject
* @return an int representing the index position, where 0 is
* the first position
*/
public int getIndexOf(Object anObject) {
return objects.indexOf(anObject);
}
// implements javax.swing.MutableComboBoxModel
public void addElement(Object anObject) {
objects.addElement(anObject);
fireIntervalAdded(this,objects.size()-1, objects.size()-1);
if ( objects.size() == 1 && selectedObject == null && anObject != null ) {
setSelectedItem( anObject );
}
}
// implements javax.swing.MutableComboBoxModel
public void insertElementAt(Object anObject,int index) {
objects.insertElementAt(anObject,index);
fireIntervalAdded(this, index, index);
}
// implements javax.swing.MutableComboBoxModel
public void removeElementAt(int index) {
if ( getElementAt( index ) == selectedObject ) {
if ( index == 0 ) {
setSelectedItem( getSize() == 1 ? null : getElementAt( index + 1 ) );
}
else {
setSelectedItem( getElementAt( index - 1 ) );
}
}
objects.removeElementAt(index);
fireIntervalRemoved(this, index, index);
}
// implements javax.swing.MutableComboBoxModel
public void removeElement(Object anObject) {
int index = objects.indexOf(anObject);
if ( index != -1 ) {
removeElementAt(index);
}
}
/** {@collect.stats}
* Empties the list.
*/
public void removeAllElements() {
if ( objects.size() > 0 ) {
int firstIndex = 0;
int lastIndex = objects.size() - 1;
objects.removeAllElements();
selectedObject = null;
fireIntervalRemoved(this, firstIndex, lastIndex);
} else {
selectedObject = null;
}
}
}
|
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.PropertyChangeListener;
import java.util.Locale;
import java.util.Vector;
import java.io.Serializable;
import javax.accessibility.*;
/** {@collect.stats}
* A <code>JWindow</code> is a container that can be displayed anywhere on the
* user's desktop. It does not have the title bar, window-management buttons,
* or other trimmings associated with a <code>JFrame</code>, but it is still a
* "first-class citizen" of the user's desktop, and can exist anywhere
* on it.
* <p>
* The <code>JWindow</code> component contains a <code>JRootPane</code>
* as its only child. The <code>contentPane</code> should be the parent
* of any children of the <code>JWindow</code>.
* As a conveniance <code>add</code> and its variants, <code>remove</code> and
* <code>setLayout</code> have been overridden to forward to the
* <code>contentPane</code> as necessary. This means you can write:
* <pre>
* window.add(child);
* </pre>
* And the child will be added to the contentPane.
* The <code>contentPane</code> will always be non-<code>null</code>.
* Attempting to set it to <code>null</code> will cause the <code>JWindow</code>
* to throw an exception. The default <code>contentPane</code> will have a
* <code>BorderLayout</code> manager set on it.
* Refer to {@link javax.swing.RootPaneContainer}
* for details on adding, removing and setting the <code>LayoutManager</code>
* of a <code>JWindow</code>.
* <p>
* Please see the {@link JRootPane} documentation for a complete description of
* the <code>contentPane</code>, <code>glassPane</code>, and
* <code>layeredPane</code> components.
* <p>
* In a multi-screen environment, you can create a <code>JWindow</code>
* on a different screen device. See {@link java.awt.Window} for more
* information.
* <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 JRootPane
*
* @beaninfo
* attribute: isContainer true
* attribute: containerDelegate getContentPane
* description: A toplevel window which has no system border or controls.
*
* @author David Kloba
*/
public class JWindow extends Window implements Accessible,
RootPaneContainer,
TransferHandler.HasGetTransferHandler
{
/** {@collect.stats}
* The <code>JRootPane</code> instance that manages the
* <code>contentPane</code>
* and optional <code>menuBar</code> for this frame, as well as the
* <code>glassPane</code>.
*
* @see #getRootPane
* @see #setRootPane
*/
protected JRootPane rootPane;
/** {@collect.stats}
* If true then calls to <code>add</code> and <code>setLayout</code>
* will be forwarded to the <code>contentPane</code>. This is initially
* false, but is set to true when the <code>JWindow</code> is constructed.
*
* @see #isRootPaneCheckingEnabled
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean rootPaneCheckingEnabled = false;
/** {@collect.stats}
* The <code>TransferHandler</code> for this window.
*/
private TransferHandler transferHandler;
/** {@collect.stats}
* Creates a window with no specified owner. This window will not be
* focusable.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @throws HeadlessException if
* <code>GraphicsEnvironment.isHeadless()</code> returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #isFocusableWindow
* @see JComponent#getDefaultLocale
*/
public JWindow() {
this((Frame)null);
}
/** {@collect.stats}
* Creates a window with the specified <code>GraphicsConfiguration</code>
* of a screen device. This window will not be focusable.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param gc the <code>GraphicsConfiguration</code> that is used
* to construct the new window with; if gc is <code>null</code>,
* the system default <code>GraphicsConfiguration</code>
* is assumed
* @throws HeadlessException If
* <code>GraphicsEnvironment.isHeadless()</code> returns true.
* @throws IllegalArgumentException if <code>gc</code> is not from
* a screen device.
*
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #isFocusableWindow
* @see JComponent#getDefaultLocale
*
* @since 1.3
*/
public JWindow(GraphicsConfiguration gc) {
this(null, gc);
super.setFocusableWindowState(false);
}
/** {@collect.stats}
* Creates a window with the specified owner frame.
* If <code>owner</code> is <code>null</code>, the shared owner
* will be used and this window will not be focusable. Also,
* this window will not be focusable unless its owner is showing
* on the screen.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the frame from which the window is displayed
* @throws HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #isFocusableWindow
* @see JComponent#getDefaultLocale
*/
public JWindow(Frame owner) {
super(owner == null? SwingUtilities.getSharedOwnerFrame() : owner);
if (owner == null) {
WindowListener ownerShutdownListener =
(WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
addWindowListener(ownerShutdownListener);
}
windowInit();
}
/** {@collect.stats}
* Creates a window with the specified owner window. This window
* will not be focusable unless its owner is showing on the screen.
* If <code>owner</code> is <code>null</code>, the shared owner
* will be used and this window will not be focusable.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the window from which the window is displayed
* @throws HeadlessException if
* <code>GraphicsEnvironment.isHeadless()</code> returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #isFocusableWindow
* @see JComponent#getDefaultLocale
*/
public JWindow(Window owner) {
super(owner == null ? (Window)SwingUtilities.getSharedOwnerFrame() :
owner);
if (owner == null) {
WindowListener ownerShutdownListener =
(WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
addWindowListener(ownerShutdownListener);
}
windowInit();
}
/** {@collect.stats}
* Creates a window with the specified owner window and
* <code>GraphicsConfiguration</code> of a screen device. If
* <code>owner</code> is <code>null</code>, the shared owner will be used
* and this window will not be focusable.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param owner the window from which the window is displayed
* @param gc the <code>GraphicsConfiguration</code> that is used
* to construct the new window with; if gc is <code>null</code>,
* the system default <code>GraphicsConfiguration</code>
* is assumed, unless <code>owner</code> is also null, in which
* case the <code>GraphicsConfiguration</code> from the
* shared owner frame will be used.
* @throws HeadlessException if
* <code>GraphicsEnvironment.isHeadless()</code> returns true.
* @throws IllegalArgumentException if <code>gc</code> is not from
* a screen device.
*
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #isFocusableWindow
* @see JComponent#getDefaultLocale
*
* @since 1.3
*/
public JWindow(Window owner, GraphicsConfiguration gc) {
super(owner == null ? (Window)SwingUtilities.getSharedOwnerFrame() :
owner, gc);
if (owner == null) {
WindowListener ownerShutdownListener =
(WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
addWindowListener(ownerShutdownListener);
}
windowInit();
}
/** {@collect.stats}
* Called by the constructors to init the <code>JWindow</code> properly.
*/
protected void windowInit() {
setLocale( JComponent.getDefaultLocale() );
setRootPane(createRootPane());
setRootPaneCheckingEnabled(true);
sun.awt.SunToolkit.checkAndSetPolicy(this, true);
}
/** {@collect.stats}
* Called by the constructor methods to create the default
* <code>rootPane</code>.
*/
protected JRootPane createRootPane() {
JRootPane rp = 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.
rp.setOpaque(true);
return rp;
}
/** {@collect.stats}
* Returns whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @return true if <code>add</code> and <code>setLayout</code>
* are fowarded; false otherwise
*
* @see #addImpl
* @see #setLayout
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean isRootPaneCheckingEnabled() {
return rootPaneCheckingEnabled;
}
/** {@collect.stats}
* Sets the {@code transferHandler} property, which is a mechanism to
* support transfer of data into this component. Use {@code null}
* if the component does not support data transfer operations.
* <p>
* If the system property {@code suppressSwingDropSupport} is {@code false}
* (the default) and the current drop target on this component is either
* {@code null} or not a user-set drop target, this method will change the
* drop target as follows: If {@code newHandler} is {@code null} it will
* clear the drop target. If not {@code null} it will install a new
* {@code DropTarget}.
* <p>
* Note: When used with {@code JWindow}, {@code TransferHandler} only
* provides data import capability, as the data export related methods
* are currently typed to {@code JComponent}.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html">
* How to Use Drag and Drop and Data Transfer</a>, a section in
* <em>The Java Tutorial</em>, for more information.
*
* @param newHandler the new {@code TransferHandler}
*
* @see TransferHandler
* @see #getTransferHandler
* @see java.awt.Component#setDropTarget
* @since 1.6
*
* @beaninfo
* bound: true
* hidden: true
* description: Mechanism for transfer of data into the component
*/
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = transferHandler;
transferHandler = newHandler;
SwingUtilities.installSwingDropTargetAsNecessary(this, transferHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
/** {@collect.stats}
* Gets the <code>transferHandler</code> property.
*
* @return the value of the <code>transferHandler</code> property
*
* @see TransferHandler
* @see #setTransferHandler
* @since 1.6
*/
public TransferHandler getTransferHandler() {
return transferHandler;
}
/** {@collect.stats}
* Calls <code>paint(g)</code>. This method was overridden to
* prevent an unnecessary call to clear the background.
*
* @param g the <code>Graphics</code> context in which to paint
*/
public void update(Graphics g) {
paint(g);
}
/** {@collect.stats}
* Sets whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @param enabled true if <code>add</code> and <code>setLayout</code>
* are forwarded, false if they should operate directly on the
* <code>JWindow</code>.
*
* @see #addImpl
* @see #setLayout
* @see #isRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
* @beaninfo
* hidden: true
* description: Whether the add and setLayout methods are forwarded
*/
protected void setRootPaneCheckingEnabled(boolean enabled) {
rootPaneCheckingEnabled = enabled;
}
/** {@collect.stats}
* Adds the specified child <code>Component</code>.
* This method is overridden to conditionally forward calls to the
* <code>contentPane</code>.
* By default, children are added to the <code>contentPane</code> instead
* of the frame, refer to {@link javax.swing.RootPaneContainer} for
* details.
*
* @param comp the component to be enhanced
* @param constraints the constraints to be respected
* @param index the index
* @exception IllegalArgumentException if <code>index</code> is invalid
* @exception IllegalArgumentException if adding the container's parent
* to itself
* @exception IllegalArgumentException if adding a window to a container
*
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected void addImpl(Component comp, Object constraints, int index)
{
if(isRootPaneCheckingEnabled()) {
getContentPane().add(comp, constraints, index);
}
else {
super.addImpl(comp, constraints, index);
}
}
/** {@collect.stats}
* Removes the specified component from the container. If
* <code>comp</code> is not the <code>rootPane</code>, this will forward
* the call to the <code>contentPane</code>. This will do nothing if
* <code>comp</code> is not a child of the <code>JWindow</code> or
* <code>contentPane</code>.
*
* @param comp the component to be removed
* @throws NullPointerException if <code>comp</code> is null
* @see #add
* @see javax.swing.RootPaneContainer
*/
public void remove(Component comp) {
if (comp == rootPane) {
super.remove(comp);
} else {
getContentPane().remove(comp);
}
}
/** {@collect.stats}
* Sets the <code>LayoutManager</code>.
* Overridden to conditionally forward the call to the
* <code>contentPane</code>.
* Refer to {@link javax.swing.RootPaneContainer} for
* more information.
*
* @param manager the <code>LayoutManager</code>
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
public void setLayout(LayoutManager manager) {
if(isRootPaneCheckingEnabled()) {
getContentPane().setLayout(manager);
}
else {
super.setLayout(manager);
}
}
/** {@collect.stats}
* Returns the <code>rootPane</code> object for this window.
* @return the <code>rootPane</code> property for this window
*
* @see #setRootPane
* @see RootPaneContainer#getRootPane
*/
public JRootPane getRootPane() {
return rootPane;
}
/** {@collect.stats}
* Sets the new <code>rootPane</code> object for this window.
* This method is called by the constructor.
*
* @param root the new <code>rootPane</code> property
* @see #getRootPane
*
* @beaninfo
* hidden: true
* description: the RootPane object for this window.
*/
protected void setRootPane(JRootPane root) {
if(rootPane != null) {
remove(rootPane);
}
rootPane = root;
if(rootPane != null) {
boolean checkingEnabled = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
add(rootPane, BorderLayout.CENTER);
}
finally {
setRootPaneCheckingEnabled(checkingEnabled);
}
}
}
/** {@collect.stats}
* Returns the <code>Container</code> which is the <code>contentPane</code>
* for this window.
*
* @return the <code>contentPane</code> property
* @see #setContentPane
* @see RootPaneContainer#getContentPane
*/
public Container getContentPane() {
return getRootPane().getContentPane();
}
/** {@collect.stats}
* Sets the <code>contentPane</code> property for this window.
* This method is called by the constructor.
*
* @param contentPane the new <code>contentPane</code>
*
* @exception IllegalComponentStateException (a runtime
* exception) if the content pane parameter is <code>null</code>
* @see #getContentPane
* @see RootPaneContainer#setContentPane
*
* @beaninfo
* hidden: true
* description: The client area of the window where child
* components are normally inserted.
*/
public void setContentPane(Container contentPane) {
getRootPane().setContentPane(contentPane);
}
/** {@collect.stats}
* Returns the <code>layeredPane</code> object for this window.
*
* @return the <code>layeredPane</code> property
* @see #setLayeredPane
* @see RootPaneContainer#getLayeredPane
*/
public JLayeredPane getLayeredPane() {
return getRootPane().getLayeredPane();
}
/** {@collect.stats}
* Sets the <code>layeredPane</code> property.
* This method is called by the constructor.
*
* @param layeredPane the new <code>layeredPane</code> object
*
* @exception IllegalComponentStateException (a runtime
* exception) if the content pane parameter is <code>null</code>
* @see #getLayeredPane
* @see RootPaneContainer#setLayeredPane
*
* @beaninfo
* hidden: true
* description: The pane which holds the various window layers.
*/
public void setLayeredPane(JLayeredPane layeredPane) {
getRootPane().setLayeredPane(layeredPane);
}
/** {@collect.stats}
* Returns the <code>glassPane Component</code> for this window.
*
* @return the <code>glassPane</code> property
* @see #setGlassPane
* @see RootPaneContainer#getGlassPane
*/
public Component getGlassPane() {
return getRootPane().getGlassPane();
}
/** {@collect.stats}
* Sets the <code>glassPane</code> property.
* This method is called by the constructor.
* @param glassPane the <code>glassPane</code> object for this window
*
* @see #getGlassPane
* @see RootPaneContainer#setGlassPane
*
* @beaninfo
* hidden: true
* description: A transparent pane used for menu rendering.
*/
public void setGlassPane(Component glassPane) {
getRootPane().setGlassPane(glassPane);
}
/** {@collect.stats}
* {@inheritDoc}
*
* @since 1.6
*/
public Graphics getGraphics() {
JComponent.getGraphicsInvoked(this);
return super.getGraphics();
}
/** {@collect.stats}
* Repaints the specified rectangle of this component within
* <code>time</code> milliseconds. Refer to <code>RepaintManager</code>
* for details on how the repaint is handled.
*
* @param time maximum time in milliseconds before update
* @param x the <i>x</i> coordinate
* @param y the <i>y</i> coordinate
* @param width the width
* @param height the height
* @see RepaintManager
* @since 1.6
*/
public void repaint(long time, int x, int y, int width, int height) {
if (RepaintManager.HANDLE_TOP_LEVEL_PAINT) {
RepaintManager.currentManager(this).addDirtyRegion(
this, x, y, width, height);
}
else {
super.repaint(time, x, y, width, height);
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JWindow</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>JWindow</code>
*/
protected String paramString() {
String rootPaneCheckingEnabledString = (rootPaneCheckingEnabled ?
"true" : "false");
return super.paramString() +
",rootPaneCheckingEnabled=" + rootPaneCheckingEnabledString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats} The accessible context property. */
protected AccessibleContext accessibleContext = null;
/** {@collect.stats}
* Gets the AccessibleContext associated with this JWindow.
* For JWindows, the AccessibleContext takes the form of an
* AccessibleJWindow.
* A new AccessibleJWindow instance is created if necessary.
*
* @return an AccessibleJWindow that serves as the
* AccessibleContext of this JWindow
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJWindow();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JWindow</code> class. It provides an implementation of the
* Java Accessibility API appropriate to window user-interface
* elements.
*/
protected class AccessibleJWindow extends AccessibleAWTWindow {
// everything is in the new parent, AccessibleAWTWindow
}
}
|
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.Component;
import java.awt.Container;
import java.awt.Window;
import java.util.*;
import java.awt.FocusTraversalPolicy;
import java.util.logging.*;
/** {@collect.stats}
* A FocusTraversalPolicy that determines traversal order by sorting the
* Components of a focus traversal cycle based on a given Comparator. Portions
* of the Component hierarchy that are not visible and displayable will not be
* included.
* <p>
* By default, SortingFocusTraversalPolicy implicitly transfers focus down-
* cycle. That is, during normal focus traversal, the Component
* traversed after a focus cycle root will be the focus-cycle-root's default
* Component to focus. This behavior can be disabled using the
* <code>setImplicitDownCycleTraversal</code> method.
* <p>
* By default, methods of this class with return a Component only if it is
* visible, displayable, enabled, and focusable. Subclasses can modify this
* behavior by overriding the <code>accept</code> method.
* <p>
* This policy takes into account <a
* href="../../java/awt/doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus traversal
* policy providers</a>. When searching for first/last/next/previous Component,
* if a focus traversal policy provider is encountered, its focus traversal
* policy is used to perform the search operation.
*
* @author David Mendenhall
*
* @see java.util.Comparator
* @since 1.4
*/
public class SortingFocusTraversalPolicy
extends InternalFrameFocusTraversalPolicy
{
private Comparator<? super Component> comparator;
private boolean implicitDownCycleTraversal = true;
private Logger log = Logger.getLogger("javax.swing.SortingFocusTraversalPolicy");
/** {@collect.stats}
* Used by getComponentAfter and getComponentBefore for efficiency. In
* order to maintain compliance with the specification of
* FocusTraversalPolicy, if traversal wraps, we should invoke
* getFirstComponent or getLastComponent. These methods may be overriden in
* subclasses to behave in a non-generic way. However, in the generic case,
* these methods will simply return the first or last Components of the
* sorted list, respectively. Since getComponentAfter and
* getComponentBefore have already built the sorted list before determining
* that they need to invoke getFirstComponent or getLastComponent, the
* sorted list should be reused if possible.
*/
private Container cachedRoot;
private List cachedCycle;
// Delegate our fitness test to ContainerOrder so that we only have to
// code the algorithm once.
private static final SwingContainerOrderFocusTraversalPolicy
fitnessTestPolicy = new SwingContainerOrderFocusTraversalPolicy();
/** {@collect.stats}
* Constructs a SortingFocusTraversalPolicy without a Comparator.
* Subclasses must set the Comparator using <code>setComparator</code>
* before installing this FocusTraversalPolicy on a focus cycle root or
* KeyboardFocusManager.
*/
protected SortingFocusTraversalPolicy() {
}
/** {@collect.stats}
* Constructs a SortingFocusTraversalPolicy with the specified Comparator.
*/
public SortingFocusTraversalPolicy(Comparator<? super Component> comparator) {
this.comparator = comparator;
}
private void enumerateAndSortCycle(Container focusCycleRoot,
List cycle, Map defaults) {
List defaultRoots = null;
if (!focusCycleRoot.isShowing()) {
return;
}
enumerateCycle(focusCycleRoot, cycle);
boolean addDefaultComponents =
(defaults != null && getImplicitDownCycleTraversal());
if (log.isLoggable(Level.FINE)) log.fine("### Will add defaults: " + addDefaultComponents);
// Create a list of all default Components which should be added
// to the list
if (addDefaultComponents) {
defaultRoots = new ArrayList();
for (Iterator iter = cycle.iterator(); iter.hasNext(); ) {
Component comp = (Component)iter.next();
if ((comp instanceof Container) &&
((Container)comp).isFocusCycleRoot())
{
defaultRoots.add(comp);
}
}
Collections.sort(defaultRoots, comparator);
}
// Sort the Components in the cycle
Collections.sort(cycle, comparator);
// Find all of the roots in the cycle and place their default
// Components after them. Note that the roots may have been removed
// from the list because they were unfit. In that case, insert the
// default Components as though the roots were still in the list.
if (addDefaultComponents) {
for (ListIterator defaultRootsIter =
defaultRoots.listIterator(defaultRoots.size());
defaultRootsIter.hasPrevious(); )
{
Container root = (Container)defaultRootsIter.previous();
Component defComp =
root.getFocusTraversalPolicy().getDefaultComponent(root);
if (defComp != null && defComp.isShowing()) {
int index = Collections.binarySearch(cycle, root,
comparator);
if (index < 0) {
// If root is not in the list, then binarySearch
// returns (-(insertion point) - 1). defComp follows
// the index one less than the insertion point.
index = -index - 2;
}
defaults.put(new Integer(index), defComp);
}
}
}
}
private void enumerateCycle(Container container, List cycle) {
if (!(container.isVisible() && container.isDisplayable())) {
return;
}
cycle.add(container);
Component[] components = container.getComponents();
for (int i = 0; i < components.length; i++) {
Component comp = components[i];
if ((comp instanceof Container)
&& !((Container)comp).isFocusTraversalPolicyProvider()
&& !((Container)comp).isFocusCycleRoot()
&& !((comp instanceof JComponent)
&& ((JComponent)comp).isManagingFocus()))
{
enumerateCycle((Container)comp, cycle);
} else {
cycle.add(comp);
}
}
}
Container getTopmostProvider(Container focusCycleRoot, Component aComponent) {
Container aCont = aComponent.getParent();
Container ftp = null;
while (aCont != focusCycleRoot && aCont != null) {
if (aCont.isFocusTraversalPolicyProvider()) {
ftp = aCont;
}
aCont = aCont.getParent();
}
if (aCont == null) {
return null;
}
return ftp;
}
/** {@collect.stats}
* Returns the Component that should receive the focus after aComponent.
* aContainer must be a focus cycle root of aComponent or a focus traversal policy provider.
* <p>
* By default, SortingFocusTraversalPolicy implicitly transfers focus down-
* cycle. That is, during normal focus traversal, the Component
* traversed after a focus cycle root will be the focus-cycle-root's
* default Component to focus. This behavior can be disabled using the
* <code>setImplicitDownCycleTraversal</code> method.
* <p>
* If aContainer is <a href="../../java/awt/doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus
* traversal policy provider</a>, the focus is always transferred down-cycle.
*
* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider
* @param aComponent a (possibly indirect) child of aContainer, or
* aContainer itself
* @return the Component that should receive the focus after aComponent, or
* null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is not a focus cycle
* root of aComponent or a focus traversal policy provider, or if either aContainer or
* aComponent is null
*/
public Component getComponentAfter(Container aContainer,
Component aComponent) {
if (log.isLoggable(Level.FINE)) log.fine("### Searching in " + aContainer.getName() + " for component after " + aComponent.getName());
if (aContainer == null || aComponent == null) {
throw new IllegalArgumentException("aContainer and aComponent cannot be null");
}
if (!aContainer.isFocusTraversalPolicyProvider() && !aContainer.isFocusCycleRoot()) {
throw new IllegalArgumentException("aContainer should be focus cycle root or focus traversal policy provider");
} else if (aContainer.isFocusCycleRoot() && !aComponent.isFocusCycleRoot(aContainer)) {
throw new IllegalArgumentException("aContainer is not a focus cycle root of aComponent");
}
// See if the component is inside of policy provider
Container ftp = getTopmostProvider(aContainer, aComponent);
if (ftp != null) {
if (log.isLoggable(Level.FINE)) log.fine("### Asking FTP " + ftp.getName() + " for component after " + aComponent.getName());
// FTP knows how to find component after the given. We don't.
FocusTraversalPolicy policy = ftp.getFocusTraversalPolicy();
Component retval = policy.getComponentAfter(ftp, aComponent);
if (retval == policy.getFirstComponent(ftp)) {
retval = null;
}
if (retval != null) {
if (log.isLoggable(Level.FINE)) log.fine("### FTP returned " + retval.getName());
return retval;
}
aComponent = ftp;
}
List cycle = new ArrayList();
Map defaults = new HashMap();
enumerateAndSortCycle(aContainer, cycle, defaults);
int index;
try {
index = Collections.binarySearch(cycle, aComponent, comparator);
} catch (ClassCastException e) {
if (log.isLoggable(Level.FINE)) log.fine("### Didn't find component " + aComponent.getName() + " in a cycle " + aContainer.getName());
return getFirstComponent(aContainer);
}
if (index < 0) {
// Fix for 5070991.
// A workaround for a transitivity problem caused by ROW_TOLERANCE,
// because of that the component may be missed in the binary search.
// Try to search it again directly.
int i = cycle.indexOf(aComponent);
if (i >= 0) {
index = i;
} else {
// If we're not in the cycle, then binarySearch returns
// (-(insertion point) - 1). The next element is our insertion
// point.
index = -index - 2;
}
}
Component defComp = (Component)defaults.get(new Integer(index));
if (defComp != null) {
return defComp;
}
do {
index++;
if (index >= cycle.size()) {
if (aContainer.isFocusCycleRoot()) {
this.cachedRoot = aContainer;
this.cachedCycle = cycle;
Component retval = getFirstComponent(aContainer);
this.cachedRoot = null;
this.cachedCycle = null;
return retval;
} else {
return null;
}
} else {
Component comp = (Component)cycle.get(index);
if (accept(comp)) {
return comp;
} else if (comp instanceof Container && ((Container)comp).isFocusTraversalPolicyProvider()) {
return ((Container)comp).getFocusTraversalPolicy().getDefaultComponent((Container)comp);
}
}
} while (true);
}
/** {@collect.stats}
* Returns the Component that should receive the focus before aComponent.
* aContainer must be a focus cycle root of aComponent or a focus traversal policy provider.
* <p>
* By default, SortingFocusTraversalPolicy implicitly transfers focus down-
* cycle. That is, during normal focus traversal, the Component
* traversed after a focus cycle root will be the focus-cycle-root's
* default Component to focus. This behavior can be disabled using the
* <code>setImplicitDownCycleTraversal</code> method.
* <p>
* If aContainer is <a href="../../java/awt/doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus
* traversal policy provider</a>, the focus is always transferred down-cycle.
*
* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider
* @param aComponent a (possibly indirect) child of aContainer, or
* aContainer itself
* @return the Component that should receive the focus before aComponent,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is not a focus cycle
* root of aComponent or a focus traversal policy provider, or if either aContainer or
* aComponent is null
*/
public Component getComponentBefore(Container aContainer,
Component aComponent) {
if (aContainer == null || aComponent == null) {
throw new IllegalArgumentException("aContainer and aComponent cannot be null");
}
if (!aContainer.isFocusTraversalPolicyProvider() && !aContainer.isFocusCycleRoot()) {
throw new IllegalArgumentException("aContainer should be focus cycle root or focus traversal policy provider");
} else if (aContainer.isFocusCycleRoot() && !aComponent.isFocusCycleRoot(aContainer)) {
throw new IllegalArgumentException("aContainer is not a focus cycle root of aComponent");
}
// See if the component is inside of policy provider
Container ftp = getTopmostProvider(aContainer, aComponent);
if (ftp != null) {
if (log.isLoggable(Level.FINE)) log.fine("### Asking FTP " + ftp.getName() + " for component after " + aComponent.getName());
// FTP knows how to find component after the given. We don't.
FocusTraversalPolicy policy = ftp.getFocusTraversalPolicy();
Component retval = policy.getComponentBefore(ftp, aComponent);
if (retval == policy.getLastComponent(ftp)) {
retval = null;
}
if (retval != null) {
if (log.isLoggable(Level.FINE)) log.fine("### FTP returned " + retval.getName());
return retval;
}
aComponent = ftp;
}
List cycle = new ArrayList();
Map defaults = new HashMap();
enumerateAndSortCycle(aContainer, cycle, defaults);
if (log.isLoggable(Level.FINE)) log.fine("### Cycle is " + cycle + ", component is " + aComponent);
int index;
try {
index = Collections.binarySearch(cycle, aComponent, comparator);
} catch (ClassCastException e) {
return getLastComponent(aContainer);
}
if (index < 0) {
// If we're not in the cycle, then binarySearch returns
// (-(insertion point) - 1). The previous element is our insertion
// point - 1.
index = -index - 2;
} else {
index--;
}
if (log.isLoggable(Level.FINE)) log.fine("### Index is " + index);
if (index >= 0) {
Component defComp = (Component)defaults.get(new Integer(index));
if (defComp != null && cycle.get(index) != aContainer) {
if (log.isLoggable(Level.FINE)) log.fine("### Returning default " + defComp.getName() + " at " + index);
return defComp;
}
}
do {
if (index < 0) {
this.cachedRoot = aContainer;
this.cachedCycle = cycle;
Component retval = getLastComponent(aContainer);
this.cachedRoot = null;
this.cachedCycle = null;
return retval;
} else {
Component comp = (Component)cycle.get(index);
if (accept(comp)) {
return comp;
} else if (comp instanceof Container && ((Container)comp).isFocusTraversalPolicyProvider()) {
return ((Container)comp).getFocusTraversalPolicy().getLastComponent((Container)comp);
}
}
index--;
} while (true);
}
/** {@collect.stats}
* Returns the first Component in the traversal cycle. This method is used
* to determine the next Component to focus when traversal wraps in the
* forward direction.
*
* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider whose
* first Component is to be returned
* @return the first Component in the traversal cycle of aContainer,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is null
*/
public Component getFirstComponent(Container aContainer) {
List cycle;
if (log.isLoggable(Level.FINE)) log.fine("### Getting first component in " + aContainer.getName());
if (aContainer == null) {
throw new IllegalArgumentException("aContainer cannot be null");
}
if (this.cachedRoot == aContainer) {
cycle = this.cachedCycle;
} else {
cycle = new ArrayList();
enumerateAndSortCycle(aContainer, cycle, null);
}
int size = cycle.size();
if (size == 0) {
return null;
}
for (int i= 0; i < cycle.size(); i++) {
Component comp = (Component)cycle.get(i);
if (accept(comp)) {
return comp;
} else if (comp instanceof Container && !(comp == aContainer) && ((Container)comp).isFocusTraversalPolicyProvider()) {
return ((Container)comp).getFocusTraversalPolicy().getDefaultComponent((Container)comp);
}
}
return null;
}
/** {@collect.stats}
* Returns the last Component in the traversal cycle. This method is used
* to determine the next Component to focus when traversal wraps in the
* reverse direction.
*
* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider whose
* last Component is to be returned
* @return the last Component in the traversal cycle of aContainer,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is null
*/
public Component getLastComponent(Container aContainer) {
List cycle;
if (log.isLoggable(Level.FINE)) log.fine("### Getting last component in " + aContainer.getName());
if (aContainer == null) {
throw new IllegalArgumentException("aContainer cannot be null");
}
if (this.cachedRoot == aContainer) {
cycle = this.cachedCycle;
} else {
cycle = new ArrayList();
enumerateAndSortCycle(aContainer, cycle, null);
}
int size = cycle.size();
if (size == 0) {
if (log.isLoggable(Level.FINE)) log.fine("### Cycle is empty");
return null;
}
if (log.isLoggable(Level.FINE)) log.fine("### Cycle is " + cycle);
for (int i= cycle.size()-1; i >= 0; i--) {
Component comp = (Component)cycle.get(i);
if (accept(comp)) {
return comp;
} else if (comp instanceof Container && !(comp == aContainer) && ((Container)comp).isFocusTraversalPolicyProvider()) {
return ((Container)comp).getFocusTraversalPolicy().getLastComponent((Container)comp);
}
}
return null;
}
/** {@collect.stats}
* Returns the default Component to focus. This Component will be the first
* to receive focus when traversing down into a new focus traversal cycle
* rooted at aContainer. The default implementation of this method
* returns the same Component as <code>getFirstComponent</code>.
*
* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider whose
* default Component is to be returned
* @return the default Component in the traversal cycle of aContainer,
* or null if no suitable Component can be found
* @see #getFirstComponent
* @throws IllegalArgumentException if aContainer is null
*/
public Component getDefaultComponent(Container aContainer) {
return getFirstComponent(aContainer);
}
/** {@collect.stats}
* Sets whether this SortingFocusTraversalPolicy transfers focus down-cycle
* implicitly. If <code>true</code>, during normal focus traversal,
* the Component traversed after a focus cycle root will be the focus-
* cycle-root's default Component to focus. If <code>false</code>, the
* next Component in the focus traversal cycle rooted at the specified
* focus cycle root will be traversed instead. The default value for this
* property is <code>true</code>.
*
* @param implicitDownCycleTraversal whether this
* SortingFocusTraversalPolicy transfers focus down-cycle implicitly
* @see #getImplicitDownCycleTraversal
* @see #getFirstComponent
*/
public void setImplicitDownCycleTraversal(boolean
implicitDownCycleTraversal) {
this.implicitDownCycleTraversal = implicitDownCycleTraversal;
}
/** {@collect.stats}
* Returns whether this SortingFocusTraversalPolicy transfers focus down-
* cycle implicitly. If <code>true</code>, during normal focus
* traversal, the Component traversed after a focus cycle root will be the
* focus-cycle-root's default Component to focus. If <code>false</code>,
* the next Component in the focus traversal cycle rooted at the specified
* focus cycle root will be traversed instead.
*
* @return whether this SortingFocusTraversalPolicy transfers focus down-
* cycle implicitly
* @see #setImplicitDownCycleTraversal
* @see #getFirstComponent
*/
public boolean getImplicitDownCycleTraversal() {
return implicitDownCycleTraversal;
}
/** {@collect.stats}
* Sets the Comparator which will be used to sort the Components in a
* focus traversal cycle.
*
* @param comparator the Comparator which will be used for sorting
*/
protected void setComparator(Comparator<? super Component> comparator) {
this.comparator = comparator;
}
/** {@collect.stats}
* Returns the Comparator which will be used to sort the Components in a
* focus traversal cycle.
*
* @return the Comparator which will be used for sorting
*/
protected Comparator<? super Component> getComparator() {
return comparator;
}
/** {@collect.stats}
* Determines whether a Component is an acceptable choice as the new
* focus owner. By default, this method will accept a Component if and
* only if it is visible, displayable, enabled, and focusable.
*
* @param aComponent the Component whose fitness as a focus owner is to
* be tested
* @return <code>true</code> if aComponent is visible, displayable,
* enabled, and focusable; <code>false</code> otherwise
*/
protected boolean accept(Component aComponent) {
return fitnessTestPolicy.accept(aComponent);
}
}
// Create our own subclass and change accept to public so that we can call
// accept.
class SwingContainerOrderFocusTraversalPolicy
extends java.awt.ContainerOrderFocusTraversalPolicy
{
public boolean accept(Component aComponent) {
return super.accept(aComponent);
}
}
|
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;
import java.awt.*;
import java.awt.event.*;
/** {@collect.stats}
* The editor component used for JComboBox components.
*
* @author Arnaud Weber
*/
public interface ComboBoxEditor {
/** {@collect.stats} Return the component that should be added to the tree hierarchy for
* this editor
*/
public Component getEditorComponent();
/** {@collect.stats} Set the item that should be edited. Cancel any editing if necessary **/
public void setItem(Object anObject);
/** {@collect.stats} Return the edited item **/
public Object getItem();
/** {@collect.stats} Ask the editor to start editing and to select everything **/
public void selectAll();
/** {@collect.stats} Add an ActionListener. An action event is generated when the edited item changes **/
public void addActionListener(ActionListener l);
/** {@collect.stats} Remove an ActionListener **/
public void removeActionListener(ActionListener l);
}
|
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;
/** {@collect.stats}
* SortOrder is an enumeration of the possible sort orderings.
*
* @see RowSorter
* @since 1.6
*/
public enum SortOrder {
/** {@collect.stats}
* Enumeration value indicating the items are sorted in increasing order.
* For example, the set <code>1, 4, 0</code> sorted in
* <code>ASCENDING</code> order is <code>0, 1, 4</code>.
*/
ASCENDING,
/** {@collect.stats}
* Enumeration value indicating the items are sorted in decreasing order.
* For example, the set <code>1, 4, 0</code> sorted in
* <code>DESCENDING</code> order is <code>4, 1, 0</code>.
*/
DESCENDING,
/** {@collect.stats}
* Enumeration value indicating the items are unordered.
* For example, the set <code>1, 4, 0</code> in
* <code>UNSORTED</code> order is <code>1, 4, 0</code>.
*/
UNSORTED
}
|
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;
/** {@collect.stats}
* Constants used with the JScrollPane component.
*
* @author Hans Muller
*/
public interface ScrollPaneConstants
{
/** {@collect.stats}
* Identifies a "viewport" or display area, within which
* scrolled contents are visible.
*/
String VIEWPORT = "VIEWPORT";
/** {@collect.stats} Identifies a vertical scrollbar. */
String VERTICAL_SCROLLBAR = "VERTICAL_SCROLLBAR";
/** {@collect.stats} Identifies a horizonal scrollbar. */
String HORIZONTAL_SCROLLBAR = "HORIZONTAL_SCROLLBAR";
/** {@collect.stats}
* Identifies the area along the left side of the viewport between the
* upper left corner and the lower left corner.
*/
String ROW_HEADER = "ROW_HEADER";
/** {@collect.stats}
* Identifies the area at the top the viewport between the
* upper left corner and the upper right corner.
*/
String COLUMN_HEADER = "COLUMN_HEADER";
/** {@collect.stats} Identifies the lower left corner of the viewport. */
String LOWER_LEFT_CORNER = "LOWER_LEFT_CORNER";
/** {@collect.stats} Identifies the lower right corner of the viewport. */
String LOWER_RIGHT_CORNER = "LOWER_RIGHT_CORNER";
/** {@collect.stats} Identifies the upper left corner of the viewport. */
String UPPER_LEFT_CORNER = "UPPER_LEFT_CORNER";
/** {@collect.stats} Identifies the upper right corner of the viewport. */
String UPPER_RIGHT_CORNER = "UPPER_RIGHT_CORNER";
/** {@collect.stats} Identifies the lower leading edge corner of the viewport. The leading edge
* is determined relative to the Scroll Pane's ComponentOrientation property.
*/
String LOWER_LEADING_CORNER = "LOWER_LEADING_CORNER";
/** {@collect.stats} Identifies the lower trailing edge corner of the viewport. The trailing edge
* is determined relative to the Scroll Pane's ComponentOrientation property.
*/
String LOWER_TRAILING_CORNER = "LOWER_TRAILING_CORNER";
/** {@collect.stats} Identifies the upper leading edge corner of the viewport. The leading edge
* is determined relative to the Scroll Pane's ComponentOrientation property.
*/
String UPPER_LEADING_CORNER = "UPPER_LEADING_CORNER";
/** {@collect.stats} Identifies the upper trailing edge corner of the viewport. The trailing edge
* is determined relative to the Scroll Pane's ComponentOrientation property.
*/
String UPPER_TRAILING_CORNER = "UPPER_TRAILING_CORNER";
/** {@collect.stats} Identifies the vertical scroll bar policy property. */
String VERTICAL_SCROLLBAR_POLICY = "VERTICAL_SCROLLBAR_POLICY";
/** {@collect.stats} Identifies the horizontal scroll bar policy property. */
String HORIZONTAL_SCROLLBAR_POLICY = "HORIZONTAL_SCROLLBAR_POLICY";
/** {@collect.stats}
* Used to set the vertical scroll bar policy so that
* vertical scrollbars are displayed only when needed.
*/
int VERTICAL_SCROLLBAR_AS_NEEDED = 20;
/** {@collect.stats}
* Used to set the vertical scroll bar policy so that
* vertical scrollbars are never displayed.
*/
int VERTICAL_SCROLLBAR_NEVER = 21;
/** {@collect.stats}
* Used to set the vertical scroll bar policy so that
* vertical scrollbars are always displayed.
*/
int VERTICAL_SCROLLBAR_ALWAYS = 22;
/** {@collect.stats}
* Used to set the horizontal scroll bar policy so that
* horizontal scrollbars are displayed only when needed.
*/
int HORIZONTAL_SCROLLBAR_AS_NEEDED = 30;
/** {@collect.stats}
* Used to set the horizontal scroll bar policy so that
* horizontal scrollbars are never displayed.
*/
int HORIZONTAL_SCROLLBAR_NEVER = 31;
/** {@collect.stats}
* Used to set the horizontal scroll bar policy so that
* horizontal scrollbars are always displayed.
*/
int HORIZONTAL_SCROLLBAR_ALWAYS = 32;
}
|
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.util.*;
import java.awt.event.*;
import javax.swing.event.*;
import sun.awt.AppContext;
/** {@collect.stats}
* A MenuSelectionManager owns the selection in menu hierarchy.
*
* @author Arnaud Weber
*/
public class MenuSelectionManager {
private Vector selection = new Vector();
/* 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.
private static final Object MENU_SELECTION_MANAGER_KEY = new Object(); // javax.swing.MenuSelectionManager
/** {@collect.stats}
* Returns the default menu selection manager.
*
* @return a MenuSelectionManager object
*/
public static MenuSelectionManager defaultManager() {
synchronized (MENU_SELECTION_MANAGER_KEY) {
AppContext context = AppContext.getAppContext();
MenuSelectionManager msm = (MenuSelectionManager)context.get(
MENU_SELECTION_MANAGER_KEY);
if (msm == null) {
msm = new MenuSelectionManager();
context.put(MENU_SELECTION_MANAGER_KEY, msm);
}
return msm;
}
}
/** {@collect.stats}
* Only one ChangeEvent is needed per button model instance since the
* event's only state is the source property. The source of events
* generated is always "this".
*/
protected transient ChangeEvent changeEvent = null;
protected EventListenerList listenerList = new EventListenerList();
/** {@collect.stats}
* Changes the selection in the menu hierarchy. The elements
* in the array are sorted in order from the root menu
* element to the currently selected menu element.
* <p>
* Note that this method is public but is used by the look and
* feel engine and should not be called by client applications.
*
* @param path an array of <code>MenuElement</code> objects specifying
* the selected path
*/
public void setSelectedPath(MenuElement[] path) {
int i,c;
int currentSelectionCount = selection.size();
int firstDifference = 0;
if(path == null) {
path = new MenuElement[0];
}
if (DEBUG) {
System.out.print("Previous: "); printMenuElementArray(getSelectedPath());
System.out.print("New: "); printMenuElementArray(path);
}
for(i=0,c=path.length;i<c;i++) {
if(i < currentSelectionCount && (MenuElement)selection.elementAt(i) == path[i])
firstDifference++;
else
break;
}
for(i=currentSelectionCount - 1 ; i >= firstDifference ; i--) {
MenuElement me = (MenuElement)selection.elementAt(i);
selection.removeElementAt(i);
me.menuSelectionChanged(false);
}
for(i = firstDifference, c = path.length ; i < c ; i++) {
if (path[i] != null) {
selection.addElement(path[i]);
path[i].menuSelectionChanged(true);
}
}
fireStateChanged();
}
/** {@collect.stats}
* Returns the path to the currently selected menu item
*
* @return an array of MenuElement objects representing the selected path
*/
public MenuElement[] getSelectedPath() {
MenuElement res[] = new MenuElement[selection.size()];
int i,c;
for(i=0,c=selection.size();i<c;i++)
res[i] = (MenuElement) selection.elementAt(i);
return res;
}
/** {@collect.stats}
* Tell the menu selection to close and unselect all the menu components. Call this method
* when a choice has been made
*/
public void clearSelectedPath() {
if (selection.size() > 0) {
setSelectedPath(null);
}
}
/** {@collect.stats}
* Adds a ChangeListener to the button.
*
* @param l the listener to add
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a ChangeListener from the button.
*
* @param l the listener to remove
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this MenuSelectionManager with addChangeListener().
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is created lazily.
*
* @see EventListenerList
*/
protected void fireStateChanged() {
// 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]==ChangeListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/** {@collect.stats}
* When a MenuElement receives an event from a MouseListener, it should never process the event
* directly. Instead all MenuElements should call this method with the event.
*
* @param event a MouseEvent object
*/
public void processMouseEvent(MouseEvent event) {
int screenX,screenY;
Point p;
int i,c,j,d;
Component mc;
Rectangle r2;
int cWidth,cHeight;
MenuElement menuElement;
MenuElement subElements[];
MenuElement path[];
Vector tmp;
int selectionSize;
p = event.getPoint();
Component source = (Component)event.getSource();
if (!source.isShowing()) {
// This can happen if a mouseReleased removes the
// containing component -- bug 4146684
return;
}
int type = event.getID();
int modifiers = event.getModifiers();
// 4188027: drag enter/exit added in JDK 1.1.7A, JDK1.2
if ((type==MouseEvent.MOUSE_ENTERED||
type==MouseEvent.MOUSE_EXITED)
&& ((modifiers & (InputEvent.BUTTON1_MASK |
InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK)) !=0 )) {
return;
}
SwingUtilities.convertPointToScreen(p,source);
screenX = p.x;
screenY = p.y;
tmp = (Vector)selection.clone();
selectionSize = tmp.size();
boolean success = false;
for (i=selectionSize - 1;i >= 0 && success == false; i--) {
menuElement = (MenuElement) tmp.elementAt(i);
subElements = menuElement.getSubElements();
path = null;
for (j = 0, d = subElements.length;j < d && success == false; j++) {
if (subElements[j] == null)
continue;
mc = subElements[j].getComponent();
if(!mc.isShowing())
continue;
if(mc instanceof JComponent) {
cWidth = ((JComponent)mc).getWidth();
cHeight = ((JComponent)mc).getHeight();
} else {
r2 = mc.getBounds();
cWidth = r2.width;
cHeight = r2.height;
}
p.x = screenX;
p.y = screenY;
SwingUtilities.convertPointFromScreen(p,mc);
/** {@collect.stats} Send the event to visible menu element if menu element currently in
* the selected path or contains the event location
*/
if(
(p.x >= 0 && p.x < cWidth && p.y >= 0 && p.y < cHeight)) {
int k;
if(path == null) {
path = new MenuElement[i+2];
for(k=0;k<=i;k++)
path[k] = (MenuElement)tmp.elementAt(k);
}
path[i+1] = subElements[j];
MenuElement currentSelection[] = getSelectedPath();
// Enter/exit detection -- needs tuning...
if (currentSelection[currentSelection.length-1] !=
path[i+1] &&
(currentSelection.length < 2 ||
currentSelection[currentSelection.length-2] !=
path[i+1])) {
Component oldMC = currentSelection[currentSelection.length-1].getComponent();
MouseEvent exitEvent = new MouseEvent(oldMC, MouseEvent.MOUSE_EXITED,
event.getWhen(),
event.getModifiers(), p.x, p.y,
event.getXOnScreen(),
event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(),
MouseEvent.NOBUTTON);
currentSelection[currentSelection.length-1].
processMouseEvent(exitEvent, path, this);
MouseEvent enterEvent = new MouseEvent(mc,
MouseEvent.MOUSE_ENTERED,
event.getWhen(),
event.getModifiers(), p.x, p.y,
event.getXOnScreen(),
event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(),
MouseEvent.NOBUTTON);
subElements[j].processMouseEvent(enterEvent, path, this);
}
MouseEvent mouseEvent = new MouseEvent(mc, event.getID(),event. getWhen(),
event.getModifiers(), p.x, p.y,
event.getXOnScreen(),
event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(),
MouseEvent.NOBUTTON);
subElements[j].processMouseEvent(mouseEvent, path, this);
success = true;
event.consume();
}
}
}
}
private void printMenuElementArray(MenuElement path[]) {
printMenuElementArray(path, false);
}
private void printMenuElementArray(MenuElement path[], boolean dumpStack) {
System.out.println("Path is(");
int i, j;
for(i=0,j=path.length; i<j ;i++){
for (int k=0; k<=i; k++)
System.out.print(" ");
MenuElement me = (MenuElement) path[i];
if(me instanceof JMenuItem) {
System.out.println(((JMenuItem)me).getText() + ", ");
} else if (me instanceof JMenuBar) {
System.out.println("JMenuBar, ");
} else if(me instanceof JPopupMenu) {
System.out.println("JPopupMenu, ");
} else if (me == null) {
System.out.println("NULL , ");
} else {
System.out.println("" + me + ", ");
}
}
System.out.println(")");
if (dumpStack == true)
Thread.dumpStack();
}
/** {@collect.stats}
* Returns the component in the currently selected path
* which contains sourcePoint.
*
* @param source The component in whose coordinate space sourcePoint
* is given
* @param sourcePoint The point which is being tested
* @return The component in the currently selected path which
* contains sourcePoint (relative to the source component's
* coordinate space. If sourcePoint is not inside a component
* on the currently selected path, null is returned.
*/
public Component componentForPoint(Component source, Point sourcePoint) {
int screenX,screenY;
Point p = sourcePoint;
int i,c,j,d;
Component mc;
Rectangle r2;
int cWidth,cHeight;
MenuElement menuElement;
MenuElement subElements[];
Vector tmp;
int selectionSize;
SwingUtilities.convertPointToScreen(p,source);
screenX = p.x;
screenY = p.y;
tmp = (Vector)selection.clone();
selectionSize = tmp.size();
for(i=selectionSize - 1 ; i >= 0 ; i--) {
menuElement = (MenuElement) tmp.elementAt(i);
subElements = menuElement.getSubElements();
for(j = 0, d = subElements.length ; j < d ; j++) {
if (subElements[j] == null)
continue;
mc = subElements[j].getComponent();
if(!mc.isShowing())
continue;
if(mc instanceof JComponent) {
cWidth = ((JComponent)mc).getWidth();
cHeight = ((JComponent)mc).getHeight();
} else {
r2 = mc.getBounds();
cWidth = r2.width;
cHeight = r2.height;
}
p.x = screenX;
p.y = screenY;
SwingUtilities.convertPointFromScreen(p,mc);
/** {@collect.stats} Return the deepest component on the selection
* path in whose bounds the event's point occurs
*/
if (p.x >= 0 && p.x < cWidth && p.y >= 0 && p.y < cHeight) {
return mc;
}
}
}
return null;
}
/** {@collect.stats}
* When a MenuElement receives an event from a KeyListener, it should never process the event
* directly. Instead all MenuElements should call this method with the event.
*
* @param e a KeyEvent object
*/
public void processKeyEvent(KeyEvent e) {
MenuElement[] sel2 = new MenuElement[0];
sel2 = (MenuElement[])selection.toArray(sel2);
int selSize = sel2.length;
MenuElement[] path;
if (selSize < 1) {
return;
}
for (int i=selSize-1; i>=0; i--) {
MenuElement elem = sel2[i];
MenuElement[] subs = elem.getSubElements();
path = null;
for (int j=0; j<subs.length; j++) {
if (subs[j] == null || !subs[j].getComponent().isShowing()
|| !subs[j].getComponent().isEnabled()) {
continue;
}
if(path == null) {
path = new MenuElement[i+2];
System.arraycopy(sel2, 0, path, 0, i+1);
}
path[i+1] = subs[j];
subs[j].processKeyEvent(e, path, this);
if (e.isConsumed()) {
return;
}
}
}
// finally dispatch event to the first component in path
path = new MenuElement[1];
path[0] = sel2[0];
path[0].processKeyEvent(e, path, this);
if (e.isConsumed()) {
return;
}
}
/** {@collect.stats}
* Return true if c is part of the currently used menu
*/
public boolean isComponentPartOfCurrentMenu(Component c) {
if(selection.size() > 0) {
MenuElement me = (MenuElement)selection.elementAt(0);
return isComponentPartOfCurrentMenu(me,c);
} else
return false;
}
private boolean isComponentPartOfCurrentMenu(MenuElement root,Component c) {
MenuElement children[];
int i,d;
if (root == null)
return false;
if(root.getComponent() == c)
return true;
else {
children = root.getSubElements();
for(i=0,d=children.length;i<d;i++) {
if(isComponentPartOfCurrentMenu(children[i],c))
return true;
}
}
return false;
}
}
|
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.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.SortOrder;
/** {@collect.stats}
* An implementation of <code>RowSorter</code> that provides sorting and
* filtering around a grid-based data model.
* Beyond creating and installing a <code>RowSorter</code>, you very rarely
* need to interact with one directly. Refer to
* {@link javax.swing.table.TableRowSorter TableRowSorter} for a concrete
* implementation of <code>RowSorter</code> for <code>JTable</code>.
* <p>
* Sorting is done based on the current <code>SortKey</code>s, in order.
* If two objects are equal (the <code>Comparator</code> for the
* column returns 0) the next <code>SortKey</code> is used. If no
* <code>SortKey</code>s remain or the order is <code>UNSORTED</code>, then
* the order of the rows in the model is used.
* <p>
* Sorting of each column is done by way of a <code>Comparator</code>
* that you can specify using the <code>setComparator</code> method.
* If a <code>Comparator</code> has not been specified, the
* <code>Comparator</code> returned by
* <code>Collator.getInstance()</code> is used on the results of
* calling <code>toString</code> on the underlying objects. The
* <code>Comparator</code> is never passed <code>null</code>. A
* <code>null</code> value is treated as occuring before a
* non-<code>null</code> value, and two <code>null</code> values are
* considered equal.
* <p>
* If you specify a <code>Comparator</code> that casts its argument to
* a type other than that provided by the model, a
* <code>ClassCastException</code> will be thrown when the data is sorted.
* <p>
* In addition to sorting, <code>DefaultRowSorter</code> provides the
* ability to filter rows. Filtering is done by way of a
* <code>RowFilter</code> that is specified using the
* <code>setRowFilter</code> method. If no filter has been specified all
* rows are included.
* <p>
* By default, rows are in unsorted order (the same as the model) and
* every column is sortable. The default <code>Comparator</code>s are
* documented in the subclasses (for example, {@link
* javax.swing.table.TableRowSorter TableRowSorter}).
* <p>
* If the underlying model structure changes (the
* <code>modelStructureChanged</code> method is invoked) the following
* are reset to their default values: <code>Comparator</code>s by
* column, current sort order, and whether each column is sortable. To
* find the default <code>Comparator</code>s, see the concrete
* implementation (for example, {@link
* javax.swing.table.TableRowSorter TableRowSorter}). The default
* sort order is unsorted (the same as the model), and columns are
* sortable by default.
* <p>
* If the underlying model structure changes (the
* <code>modelStructureChanged</code> method is invoked) the following
* are reset to their default values: <code>Comparator</code>s by column,
* current sort order and whether a column is sortable.
* <p>
* <code>DefaultRowSorter</code> is an abstract class. Concrete
* subclasses must provide access to the underlying data by invoking
* {@code setModelWrapper}. The {@code setModelWrapper} method
* <b>must</b> be invoked soon after the constructor is
* called, ideally from within the subclass's constructor.
* Undefined behavior will result if you use a {@code
* DefaultRowSorter} without specifying a {@code ModelWrapper}.
* <p>
* <code>DefaultRowSorter</code> has two formal type parameters. The
* first type parameter corresponds to the class of the model, for example
* <code>DefaultTableModel</code>. The second type parameter
* corresponds to the class of the identifier passed to the
* <code>RowFilter</code>. Refer to <code>TableRowSorter</code> and
* <code>RowFilter</code> for more details on the type parameters.
*
* @param <M> the type of the model
* @param <I> the type of the identifier passed to the <code>RowFilter</code>
* @see javax.swing.table.TableRowSorter
* @see javax.swing.table.DefaultTableModel
* @see java.text.Collator
* @since 1.6
*/
public abstract class DefaultRowSorter<M, I> extends RowSorter<M> {
/** {@collect.stats}
* Whether or not we resort on TableModelEvent.UPDATEs.
*/
private boolean sortsOnUpdates;
/** {@collect.stats}
* View (JTable) -> model.
*/
private Row[] viewToModel;
/** {@collect.stats}
* model -> view (JTable)
*/
private int[] modelToView;
/** {@collect.stats}
* Comparators specified by column.
*/
private Comparator[] comparators;
/** {@collect.stats}
* Whether or not the specified column is sortable, by column.
*/
private boolean[] isSortable;
/** {@collect.stats}
* Cached SortKeys for the current sort.
*/
private SortKey[] cachedSortKeys;
/** {@collect.stats}
* Cached comparators for the current sort
*/
private Comparator[] sortComparators;
/** {@collect.stats}
* Developer supplied Filter.
*/
private RowFilter<? super M,? super I> filter;
/** {@collect.stats}
* Value passed to the filter. The same instance is passed to the
* filter for different rows.
*/
private FilterEntry filterEntry;
/** {@collect.stats}
* The sort keys.
*/
private List<SortKey> sortKeys;
/** {@collect.stats}
* Whether or not to use getStringValueAt. This is indexed by column.
*/
private boolean[] useToString;
/** {@collect.stats}
* Indicates the contents are sorted. This is used if
* getSortsOnUpdates is false and an update event is received.
*/
private boolean sorted;
/** {@collect.stats}
* Maximum number of sort keys.
*/
private int maxSortKeys;
/** {@collect.stats}
* Provides access to the data we're sorting/filtering.
*/
private ModelWrapper<M,I> modelWrapper;
/** {@collect.stats}
* Size of the model. This is used to enforce error checking within
* the table changed notification methods (such as rowsInserted).
*/
private int modelRowCount;
/** {@collect.stats}
* Creates an empty <code>DefaultRowSorter</code>.
*/
public DefaultRowSorter() {
sortKeys = Collections.emptyList();
maxSortKeys = 3;
}
/** {@collect.stats}
* Sets the model wrapper providing the data that is being sorted and
* filtered.
*
* @param modelWrapper the model wrapper responsible for providing the
* data that gets sorted and filtered
* @throws IllegalArgumentException if {@code modelWrapper} is
* {@code null}
*/
protected final void setModelWrapper(ModelWrapper<M,I> modelWrapper) {
if (modelWrapper == null) {
throw new IllegalArgumentException(
"modelWrapper most be non-null");
}
ModelWrapper<M,I> last = this.modelWrapper;
this.modelWrapper = modelWrapper;
if (last != null) {
modelStructureChanged();
} else {
// If last is null, we're in the constructor. If we're in
// the constructor we don't want to call to overridable methods.
modelRowCount = getModelWrapper().getRowCount();
}
}
/** {@collect.stats}
* Returns the model wrapper providing the data that is being sorted and
* filtered.
*
* @return the model wrapper responsible for providing the data that
* gets sorted and filtered
*/
protected final ModelWrapper<M,I> getModelWrapper() {
return modelWrapper;
}
/** {@collect.stats}
* Returns the underlying model.
*
* @return the underlying model
*/
public final M getModel() {
return getModelWrapper().getModel();
}
/** {@collect.stats}
* Sets whether or not the specified column is sortable. The specified
* value is only checked when <code>toggleSortOrder</code> is invoked.
* It is still possible to sort on a column that has been marked as
* unsortable by directly setting the sort keys. The default is
* true.
*
* @param column the column to enable or disable sorting on, in terms
* of the underlying model
* @param sortable whether or not the specified column is sortable
* @throws IndexOutOfBoundsException if <code>column</code> is outside
* the range of the model
* @see #toggleSortOrder
* @see #setSortKeys
*/
public void setSortable(int column, boolean sortable) {
checkColumn(column);
if (isSortable == null) {
isSortable = new boolean[getModelWrapper().getColumnCount()];
for (int i = isSortable.length - 1; i >= 0; i--) {
isSortable[i] = true;
}
}
isSortable[column] = sortable;
}
/** {@collect.stats}
* Returns true if the specified column is sortable; otherwise, false.
*
* @param column the column to check sorting for, in terms of the
* underlying model
* @return true if the column is sortable
* @throws IndexOutOfBoundsException if column is outside
* the range of the underlying model
*/
public boolean isSortable(int column) {
checkColumn(column);
return (isSortable == null) ? true : isSortable[column];
}
/** {@collect.stats}
* Sets the sort keys. This creates a copy of the supplied
* {@code List}; subsequent changes to the supplied
* {@code List} do not effect this {@code DefaultRowSorter}.
* If the sort keys have changed this triggers a sort.
*
* @param sortKeys the new <code>SortKeys</code>; <code>null</code>
* is a shorthand for specifying an empty list,
* indicating that the view should be unsorted
* @throws IllegalArgumentException if any of the values in
* <code>sortKeys</code> are null or have a column index outside
* the range of the model
*/
public void setSortKeys(List<? extends SortKey> sortKeys) {
List<SortKey> old = this.sortKeys;
if (sortKeys != null && sortKeys.size() > 0) {
int max = getModelWrapper().getColumnCount();
for (SortKey key : sortKeys) {
if (key == null || key.getColumn() < 0 ||
key.getColumn() >= max) {
throw new IllegalArgumentException("Invalid SortKey");
}
}
this.sortKeys = Collections.unmodifiableList(
new ArrayList<SortKey>(sortKeys));
}
else {
this.sortKeys = Collections.emptyList();
}
if (!this.sortKeys.equals(old)) {
fireSortOrderChanged();
if (viewToModel == null) {
// Currently unsorted, use sort so that internal fields
// are correctly set.
sort();
} else {
sortExistingData();
}
}
}
/** {@collect.stats}
* Returns the current sort keys. This returns an unmodifiable
* {@code non-null List}. If you need to change the sort keys,
* make a copy of the returned {@code List}, mutate the copy
* and invoke {@code setSortKeys} with the new list.
*
* @return the current sort order
*/
public List<? extends SortKey> getSortKeys() {
return sortKeys;
}
/** {@collect.stats}
* Sets the maximum number of sort keys. The number of sort keys
* determines how equal values are resolved when sorting. For
* example, assume a table row sorter is created and
* <code>setMaxSortKeys(2)</code> is invoked on it. The user
* clicks the header for column 1, causing the table rows to be
* sorted based on the items in column 1. Next, the user clicks
* the header for column 2, causing the table to be sorted based
* on the items in column 2; if any items in column 2 are equal,
* then those particular rows are ordered based on the items in
* column 1. In this case, we say that the rows are primarily
* sorted on column 2, and secondarily on column 1. If the user
* then clicks the header for column 3, then the items are
* primarily sorted on column 3 and secondarily sorted on column
* 2. Because the maximum number of sort keys has been set to 2
* with <code>setMaxSortKeys</code>, column 1 no longer has an
* effect on the order.
* <p>
* The maximum number of sort keys is enforced by
* <code>toggleSortOrder</code>. You can specify more sort
* keys by invoking <code>setSortKeys</code> directly and they will
* all be honored. However if <code>toggleSortOrder</code> is subsequently
* invoked the maximum number of sort keys will be enforced.
* The default value is 3.
*
* @param max the maximum number of sort keys
* @throws IllegalArgumentException if <code>max</code> < 1
*/
public void setMaxSortKeys(int max) {
if (max < 1) {
throw new IllegalArgumentException("Invalid max");
}
maxSortKeys = max;
}
/** {@collect.stats}
* Returns the maximum number of sort keys.
*
* @return the maximum number of sort keys
*/
public int getMaxSortKeys() {
return maxSortKeys;
}
/** {@collect.stats}
* If true, specifies that a sort should happen when the underlying
* model is updated (<code>rowsUpdated</code> is invoked). For
* example, if this is true and the user edits an entry the
* location of that item in the view may change. The default is
* false.
*
* @param sortsOnUpdates whether or not to sort on update events
*/
public void setSortsOnUpdates(boolean sortsOnUpdates) {
this.sortsOnUpdates = sortsOnUpdates;
}
/** {@collect.stats}
* Returns true if a sort should happen when the underlying
* model is updated; otherwise, returns false.
*
* @return whether or not to sort when the model is updated
*/
public boolean getSortsOnUpdates() {
return sortsOnUpdates;
}
/** {@collect.stats}
* Sets the filter that determines which rows, if any, should be
* hidden from the view. The filter is applied before sorting. A value
* of <code>null</code> indicates all values from the model should be
* included.
* <p>
* <code>RowFilter</code>'s <code>include</code> method is passed an
* <code>Entry</code> that wraps the underlying model. The number
* of columns in the <code>Entry</code> corresponds to the
* number of columns in the <code>ModelWrapper</code>. The identifier
* comes from the <code>ModelWrapper</code> as well.
* <p>
* This method triggers a sort.
*
* @param filter the filter used to determine what entries should be
* included
*/
public void setRowFilter(RowFilter<? super M,? super I> filter) {
this.filter = filter;
sort();
}
/** {@collect.stats}
* Returns the filter that determines which rows, if any, should
* be hidden from view.
*
* @return the filter
*/
public RowFilter<? super M,? super I> getRowFilter() {
return filter;
}
/** {@collect.stats}
* Reverses the sort order from ascending to descending (or
* descending to ascending) if the specified column is already the
* primary sorted column; otherwise, makes the specified column
* the primary sorted column, with an ascending sort order. If
* the specified column is not sortable, this method has no
* effect.
*
* @param column index of the column to make the primary sorted column,
* in terms of the underlying model
* @throws IndexOutOfBoundsException {@inheritDoc}
* @see #setSortable(int,boolean)
* @see #setMaxSortKeys(int)
*/
public void toggleSortOrder(int column) {
checkColumn(column);
if (isSortable(column)) {
List<SortKey> keys = new ArrayList<SortKey>(getSortKeys());
SortKey sortKey;
int sortIndex;
for (sortIndex = keys.size() - 1; sortIndex >= 0; sortIndex--) {
if (keys.get(sortIndex).getColumn() == column) {
break;
}
}
if (sortIndex == -1) {
// Key doesn't exist
sortKey = new SortKey(column, SortOrder.ASCENDING);
keys.add(0, sortKey);
}
else if (sortIndex == 0) {
// It's the primary sorting key, toggle it
keys.set(0, toggle(keys.get(0)));
}
else {
// It's not the first, but was sorted on, remove old
// entry, insert as first with ascending.
keys.remove(sortIndex);
keys.add(0, new SortKey(column, SortOrder.ASCENDING));
}
if (keys.size() > getMaxSortKeys()) {
keys = keys.subList(0, getMaxSortKeys());
}
setSortKeys(keys);
}
}
private SortKey toggle(SortKey key) {
if (key.getSortOrder() == SortOrder.ASCENDING) {
return new SortKey(key.getColumn(), SortOrder.DESCENDING);
}
return new SortKey(key.getColumn(), SortOrder.ASCENDING);
}
/** {@collect.stats}
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public int convertRowIndexToView(int index) {
if (modelToView == null) {
if (index < 0 || index >= getModelWrapper().getRowCount()) {
throw new IndexOutOfBoundsException("Invalid index");
}
return index;
}
return modelToView[index];
}
/** {@collect.stats}
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public int convertRowIndexToModel(int index) {
if (viewToModel == null) {
if (index < 0 || index >= getModelWrapper().getRowCount()) {
throw new IndexOutOfBoundsException("Invalid index");
}
return index;
}
return viewToModel[index].modelIndex;
}
private boolean isUnsorted() {
List<? extends SortKey> keys = getSortKeys();
int keySize = keys.size();
return (keySize == 0 || keys.get(0).getSortOrder() ==
SortOrder.UNSORTED);
}
/** {@collect.stats}
* Sorts the existing filtered data. This should only be used if
* the filter hasn't changed.
*/
private void sortExistingData() {
int[] lastViewToModel = getViewToModelAsInts(viewToModel);
updateUseToString();
cacheSortKeys(getSortKeys());
if (isUnsorted()) {
if (getRowFilter() == null) {
viewToModel = null;
modelToView = null;
} else {
int included = 0;
for (int i = 0; i < modelToView.length; i++) {
if (modelToView[i] != -1) {
viewToModel[included].modelIndex = i;
modelToView[i] = included++;
}
}
}
} else {
// sort the data
Arrays.sort(viewToModel);
// Update the modelToView array
setModelToViewFromViewToModel(false);
}
fireRowSorterChanged(lastViewToModel);
}
/** {@collect.stats}
* Sorts and filters the rows in the view based on the sort keys
* of the columns currently being sorted and the filter, if any,
* associated with this sorter. An empty <code>sortKeys</code> list
* indicates that the view should unsorted, the same as the model.
*
* @see #setRowFilter
* @see #setSortKeys
*/
public void sort() {
sorted = true;
int[] lastViewToModel = getViewToModelAsInts(viewToModel);
updateUseToString();
if (isUnsorted()) {
// Unsorted
cachedSortKeys = new SortKey[0];
if (getRowFilter() == null) {
// No filter & unsorted
if (viewToModel != null) {
// sorted -> unsorted
viewToModel = null;
modelToView = null;
}
else {
// unsorted -> unsorted
// No need to do anything.
return;
}
}
else {
// There is filter, reset mappings
initializeFilteredMapping();
}
}
else {
cacheSortKeys(getSortKeys());
if (getRowFilter() != null) {
initializeFilteredMapping();
}
else {
createModelToView(getModelWrapper().getRowCount());
createViewToModel(getModelWrapper().getRowCount());
}
// sort them
Arrays.sort(viewToModel);
// Update the modelToView array
setModelToViewFromViewToModel(false);
}
fireRowSorterChanged(lastViewToModel);
}
/** {@collect.stats}
* Updates the useToString mapping before a sort.
*/
private void updateUseToString() {
int i = getModelWrapper().getColumnCount();
if (useToString == null || useToString.length != i) {
useToString = new boolean[i];
}
for (--i; i >= 0; i--) {
useToString[i] = useToString(i);
}
}
/** {@collect.stats}
* Resets the viewToModel and modelToView mappings based on
* the current Filter.
*/
private void initializeFilteredMapping() {
int rowCount = getModelWrapper().getRowCount();
int i, j;
int excludedCount = 0;
// Update model -> view
createModelToView(rowCount);
for (i = 0; i < rowCount; i++) {
if (include(i)) {
modelToView[i] = i - excludedCount;
}
else {
modelToView[i] = -1;
excludedCount++;
}
}
// Update view -> model
createViewToModel(rowCount - excludedCount);
for (i = 0, j = 0; i < rowCount; i++) {
if (modelToView[i] != -1) {
viewToModel[j++].modelIndex = i;
}
}
}
/** {@collect.stats}
* Makes sure the modelToView array is of size rowCount.
*/
private void createModelToView(int rowCount) {
if (modelToView == null || modelToView.length != rowCount) {
modelToView = new int[rowCount];
}
}
/** {@collect.stats}
* Resets the viewToModel array to be of size rowCount.
*/
private void createViewToModel(int rowCount) {
int recreateFrom = 0;
if (viewToModel != null) {
recreateFrom = Math.min(rowCount, viewToModel.length);
if (viewToModel.length != rowCount) {
Row[] oldViewToModel = viewToModel;
viewToModel = new Row[rowCount];
System.arraycopy(oldViewToModel, 0, viewToModel,
0, recreateFrom);
}
}
else {
viewToModel = new Row[rowCount];
}
int i;
for (i = 0; i < recreateFrom; i++) {
viewToModel[i].modelIndex = i;
}
for (i = recreateFrom; i < rowCount; i++) {
viewToModel[i] = new Row(this, i);
}
}
/** {@collect.stats}
* Caches the sort keys before a sort.
*/
private void cacheSortKeys(List<? extends SortKey> keys) {
int keySize = keys.size();
sortComparators = new Comparator[keySize];
for (int i = 0; i < keySize; i++) {
sortComparators[i] = getComparator0(keys.get(i).getColumn());
}
cachedSortKeys = keys.toArray(new SortKey[keySize]);
}
/** {@collect.stats}
* Returns whether or not to convert the value to a string before
* doing comparisons when sorting. If true
* <code>ModelWrapper.getStringValueAt</code> will be used, otherwise
* <code>ModelWrapper.getValueAt</code> will be used. It is up to
* subclasses, such as <code>TableRowSorter</code>, to honor this value
* in their <code>ModelWrapper</code> implementation.
*
* @param column the index of the column to test, in terms of the
* underlying model
* @throws IndexOutOfBoundsException if <code>column</code> is not valid
*/
protected boolean useToString(int column) {
return (getComparator(column) == null);
}
/** {@collect.stats}
* Refreshes the modelToView mapping from that of viewToModel.
* If <code>unsetFirst</code> is true, all indices in modelToView are
* first set to -1.
*/
private void setModelToViewFromViewToModel(boolean unsetFirst) {
int i;
if (unsetFirst) {
for (i = modelToView.length - 1; i >= 0; i--) {
modelToView[i] = -1;
}
}
for (i = viewToModel.length - 1; i >= 0; i--) {
modelToView[viewToModel[i].modelIndex] = i;
}
}
private int[] getViewToModelAsInts(Row[] viewToModel) {
if (viewToModel != null) {
int[] viewToModelI = new int[viewToModel.length];
for (int i = viewToModel.length - 1; i >= 0; i--) {
viewToModelI[i] = viewToModel[i].modelIndex;
}
return viewToModelI;
}
return new int[0];
}
/** {@collect.stats}
* Sets the <code>Comparator</code> to use when sorting the specified
* column. This does not trigger a sort. If you want to sort after
* setting the comparator you need to explicitly invoke <code>sort</code>.
*
* @param column the index of the column the <code>Comparator</code> is
* to be used for, in terms of the underlying model
* @param comparator the <code>Comparator</code> to use
* @throws IndexOutOfBoundsException if <code>column</code> is outside
* the range of the underlying model
*/
public void setComparator(int column, Comparator<?> comparator) {
checkColumn(column);
if (comparators == null) {
comparators = new Comparator[getModelWrapper().getColumnCount()];
}
comparators[column] = comparator;
}
/** {@collect.stats}
* Returns the <code>Comparator</code> for the specified
* column. This will return <code>null</code> if a <code>Comparator</code>
* has not been specified for the column.
*
* @param column the column to fetch the <code>Comparator</code> for, in
* terms of the underlying model
* @return the <code>Comparator</code> for the specified column
* @throws IndexOutOfBoundsException if column is outside
* the range of the underlying model
*/
public Comparator<?> getComparator(int column) {
checkColumn(column);
if (comparators != null) {
return comparators[column];
}
return null;
}
// Returns the Comparator to use during sorting. Where as
// getComparator() may return null, this will never return null.
private Comparator getComparator0(int column) {
Comparator comparator = getComparator(column);
if (comparator != null) {
return comparator;
}
// This should be ok as useToString(column) should have returned
// true in this case.
return Collator.getInstance();
}
private RowFilter.Entry<M,I> getFilterEntry(int modelIndex) {
if (filterEntry == null) {
filterEntry = new FilterEntry();
}
filterEntry.modelIndex = modelIndex;
return filterEntry;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public int getViewRowCount() {
if (viewToModel != null) {
// When filtering this may differ from getModelWrapper().getRowCount()
return viewToModel.length;
}
return getModelWrapper().getRowCount();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public int getModelRowCount() {
return getModelWrapper().getRowCount();
}
private void allChanged() {
modelToView = null;
viewToModel = null;
comparators = null;
isSortable = null;
if (isUnsorted()) {
// Keys are already empty, to force a resort we have to
// call sort
sort();
} else {
setSortKeys(null);
}
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void modelStructureChanged() {
allChanged();
modelRowCount = getModelWrapper().getRowCount();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void allRowsChanged() {
modelRowCount = getModelWrapper().getRowCount();
sort();
}
/** {@collect.stats}
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void rowsInserted(int firstRow, int endRow) {
checkAgainstModel(firstRow, endRow);
int newModelRowCount = getModelWrapper().getRowCount();
if (endRow >= newModelRowCount) {
throw new IndexOutOfBoundsException("Invalid range");
}
modelRowCount = newModelRowCount;
if (shouldOptimizeChange(firstRow, endRow)) {
rowsInserted0(firstRow, endRow);
}
}
/** {@collect.stats}
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void rowsDeleted(int firstRow, int endRow) {
checkAgainstModel(firstRow, endRow);
if (firstRow >= modelRowCount || endRow >= modelRowCount) {
throw new IndexOutOfBoundsException("Invalid range");
}
modelRowCount = getModelWrapper().getRowCount();
if (shouldOptimizeChange(firstRow, endRow)) {
rowsDeleted0(firstRow, endRow);
}
}
/** {@collect.stats}
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void rowsUpdated(int firstRow, int endRow) {
checkAgainstModel(firstRow, endRow);
if (firstRow >= modelRowCount || endRow >= modelRowCount) {
throw new IndexOutOfBoundsException("Invalid range");
}
if (getSortsOnUpdates()) {
if (shouldOptimizeChange(firstRow, endRow)) {
rowsUpdated0(firstRow, endRow);
}
}
else {
sorted = false;
}
}
/** {@collect.stats}
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void rowsUpdated(int firstRow, int endRow, int column) {
checkColumn(column);
rowsUpdated(firstRow, endRow);
}
private void checkAgainstModel(int firstRow, int endRow) {
if (firstRow > endRow || firstRow < 0 || endRow < 0 ||
firstRow > modelRowCount) {
throw new IndexOutOfBoundsException("Invalid range");
}
}
/** {@collect.stats}
* Returns true if the specified row should be included.
*/
private boolean include(int row) {
RowFilter<? super M, ? super I> filter = getRowFilter();
if (filter != null) {
return filter.include(getFilterEntry(row));
}
// null filter, always include the row.
return true;
}
@SuppressWarnings("unchecked")
private int compare(int model1, int model2) {
int column;
SortOrder sortOrder;
Object v1, v2;
int result;
for (int counter = 0; counter < cachedSortKeys.length; counter++) {
column = cachedSortKeys[counter].getColumn();
sortOrder = cachedSortKeys[counter].getSortOrder();
if (sortOrder == SortOrder.UNSORTED) {
result = model1 - model2;
} else {
// v1 != null && v2 != null
if (useToString[column]) {
v1 = getModelWrapper().getStringValueAt(model1, column);
v2 = getModelWrapper().getStringValueAt(model2, column);
} else {
v1 = getModelWrapper().getValueAt(model1, column);
v2 = getModelWrapper().getValueAt(model2, column);
}
// Treat nulls as < then non-null
if (v1 == null) {
if (v2 == null) {
result = 0;
} else {
result = -1;
}
} else if (v2 == null) {
result = 1;
} else {
result = sortComparators[counter].compare(v1, v2);
}
if (sortOrder == SortOrder.DESCENDING) {
result *= -1;
}
}
if (result != 0) {
return result;
}
}
// If we get here, they're equal. Fallback to model order.
return model1 - model2;
}
/** {@collect.stats}
* Whether not we are filtering/sorting.
*/
private boolean isTransformed() {
return (viewToModel != null);
}
/** {@collect.stats}
* Insets new set of entries.
*
* @param toAdd the Rows to add, sorted
* @param current the array to insert the items into
*/
private void insertInOrder(List<Row> toAdd, Row[] current) {
int last = 0;
int index;
int max = toAdd.size();
for (int i = 0; i < max; i++) {
index = Arrays.binarySearch(current, toAdd.get(i));
if (index < 0) {
index = -1 - index;
}
System.arraycopy(current, last,
viewToModel, last + i, index - last);
viewToModel[index + i] = toAdd.get(i);
last = index;
}
System.arraycopy(current, last, viewToModel, last + max,
current.length - last);
}
/** {@collect.stats}
* Returns true if we should try and optimize the processing of the
* <code>TableModelEvent</code>. If this returns false, assume the
* event was dealt with and no further processing needs to happen.
*/
private boolean shouldOptimizeChange(int firstRow, int lastRow) {
if (!isTransformed()) {
// Not transformed, nothing to do.
return false;
}
if (!sorted || (lastRow - firstRow) > viewToModel.length / 10) {
// We either weren't sorted, or to much changed, sort it all
sort();
return false;
}
return true;
}
private void rowsInserted0(int firstRow, int lastRow) {
int[] oldViewToModel = getViewToModelAsInts(viewToModel);
int i;
int delta = (lastRow - firstRow) + 1;
List<Row> added = new ArrayList<Row>(delta);
// Build the list of Rows to add into added
for (i = firstRow; i <= lastRow; i++) {
if (include(i)) {
added.add(new Row(this, i));
}
}
// Adjust the model index of rows after the effected region
int viewIndex;
for (i = modelToView.length - 1; i >= firstRow; i--) {
viewIndex = modelToView[i];
if (viewIndex != -1) {
viewToModel[viewIndex].modelIndex += delta;
}
}
// Insert newly added rows into viewToModel
if (added.size() > 0) {
Collections.sort(added);
Row[] lastViewToModel = viewToModel;
viewToModel = new Row[viewToModel.length + added.size()];
insertInOrder(added, lastViewToModel);
}
// Update modelToView
createModelToView(getModelWrapper().getRowCount());
setModelToViewFromViewToModel(true);
// Notify of change
fireRowSorterChanged(oldViewToModel);
}
private void rowsDeleted0(int firstRow, int lastRow) {
int[] oldViewToModel = getViewToModelAsInts(viewToModel);
int removedFromView = 0;
int i;
int viewIndex;
// Figure out how many visible rows are going to be effected.
for (i = firstRow; i <= lastRow; i++) {
viewIndex = modelToView[i];
if (viewIndex != -1) {
removedFromView++;
viewToModel[viewIndex] = null;
}
}
// Update the model index of rows after the effected region
int delta = lastRow - firstRow + 1;
for (i = modelToView.length - 1; i > lastRow; i--) {
viewIndex = modelToView[i];
if (viewIndex != -1) {
viewToModel[viewIndex].modelIndex -= delta;
}
}
// Then patch up the viewToModel array
if (removedFromView > 0) {
Row[] newViewToModel = new Row[viewToModel.length -
removedFromView];
int newIndex = 0;
int last = 0;
for (i = 0; i < viewToModel.length; i++) {
if (viewToModel[i] == null) {
System.arraycopy(viewToModel, last,
newViewToModel, newIndex, i - last);
newIndex += (i - last);
last = i + 1;
}
}
System.arraycopy(viewToModel, last,
newViewToModel, newIndex, viewToModel.length - last);
viewToModel = newViewToModel;
}
// Update the modelToView mapping
createModelToView(getModelWrapper().getRowCount());
setModelToViewFromViewToModel(true);
// And notify of change
fireRowSorterChanged(oldViewToModel);
}
private void rowsUpdated0(int firstRow, int lastRow) {
int[] oldViewToModel = getViewToModelAsInts(viewToModel);
int i, j;
int delta = lastRow - firstRow + 1;
int modelIndex;
int last;
int index;
if (getRowFilter() == null) {
// Sorting only:
// Remove the effected rows
Row[] updated = new Row[delta];
for (j = 0, i = firstRow; i <= lastRow; i++, j++) {
updated[j] = viewToModel[modelToView[i]];
}
// Sort the update rows
Arrays.sort(updated);
// Build the intermediary array: the array of
// viewToModel without the effected rows.
Row[] intermediary = new Row[viewToModel.length - delta];
for (i = 0, j = 0; i < viewToModel.length; i++) {
modelIndex = viewToModel[i].modelIndex;
if (modelIndex < firstRow || modelIndex > lastRow) {
intermediary[j++] = viewToModel[i];
}
}
// Build the new viewToModel
insertInOrder(Arrays.asList(updated), intermediary);
// Update modelToView
setModelToViewFromViewToModel(false);
}
else {
// Sorting & filtering.
// Remove the effected rows, adding them to updated and setting
// modelToView to -2 for any rows that were not filtered out
List<Row> updated = new ArrayList<Row>(delta);
int newlyVisible = 0;
int newlyHidden = 0;
int effected = 0;
for (i = firstRow; i <= lastRow; i++) {
if (modelToView[i] == -1) {
// This row was filtered out
if (include(i)) {
// No longer filtered
updated.add(new Row(this, i));
newlyVisible++;
}
}
else {
// This row was visible, make sure it should still be
// visible.
if (!include(i)) {
newlyHidden++;
}
else {
updated.add(viewToModel[modelToView[i]]);
}
modelToView[i] = -2;
effected++;
}
}
// Sort the updated rows
Collections.sort(updated);
// Build the intermediary array: the array of
// viewToModel without the updated rows.
Row[] intermediary = new Row[viewToModel.length - effected];
for (i = 0, j = 0; i < viewToModel.length; i++) {
modelIndex = viewToModel[i].modelIndex;
if (modelToView[modelIndex] != -2) {
intermediary[j++] = viewToModel[i];
}
}
// Recreate viewToModel, if necessary
if (newlyVisible != newlyHidden) {
viewToModel = new Row[viewToModel.length + newlyVisible -
newlyHidden];
}
// Rebuild the new viewToModel array
insertInOrder(updated, intermediary);
// Update modelToView
setModelToViewFromViewToModel(true);
}
// And finally fire a sort event.
fireRowSorterChanged(oldViewToModel);
}
private void checkColumn(int column) {
if (column < 0 || column >= getModelWrapper().getColumnCount()) {
throw new IndexOutOfBoundsException(
"column beyond range of TableModel");
}
}
/** {@collect.stats}
* <code>DefaultRowSorter.ModelWrapper</code> is responsible for providing
* the data that gets sorted by <code>DefaultRowSorter</code>. You
* normally do not interact directly with <code>ModelWrapper</code>.
* Subclasses of <code>DefaultRowSorter</code> provide an
* implementation of <code>ModelWrapper</code> wrapping another model.
* For example,
* <code>TableRowSorter</code> provides a <code>ModelWrapper</code> that
* wraps a <code>TableModel</code>.
* <p>
* <code>ModelWrapper</code> makes a distinction between values as
* <code>Object</code>s and <code>String</code>s. This allows
* implementations to provide a custom string
* converter to be used instead of invoking <code>toString</code> on the
* object.
*
* @param <M> the type of the underlying model
* @param <I> the identifier supplied to the filter
* @since 1.6
* @see RowFilter
* @see RowFilter.Entry
*/
protected abstract static class ModelWrapper<M,I> {
/** {@collect.stats}
* Creates a new <code>ModelWrapper</code>.
*/
protected ModelWrapper() {
}
/** {@collect.stats}
* Returns the underlying model that this <code>Model</code> is
* wrapping.
*
* @return the underlying model
*/
public abstract M getModel();
/** {@collect.stats}
* Returns the number of columns in the model.
*
* @return the number of columns in the model
*/
public abstract int getColumnCount();
/** {@collect.stats}
* Returns the number of rows in the model.
*
* @return the number of rows in the model
*/
public abstract int getRowCount();
/** {@collect.stats}
* Returns the value at the specified index.
*
* @param row the row index
* @param column the column index
* @return the value at the specified index
* @throws IndexOutOfBoundsException if the indices are outside
* the range of the model
*/
public abstract Object getValueAt(int row, int column);
/** {@collect.stats}
* Returns the value as a <code>String</code> at the specified
* index. This implementation uses <code>toString</code> on
* the result from <code>getValueAt</code> (making sure
* to return an empty string for null values). Subclasses that
* override this method should never return null.
*
* @param row the row index
* @param column the column index
* @return the value at the specified index as a <code>String</code>
* @throws IndexOutOfBoundsException if the indices are outside
* the range of the model
*/
public String getStringValueAt(int row, int column) {
Object o = getValueAt(row, column);
if (o == null) {
return "";
}
String string = o.toString();
if (string == null) {
return "";
}
return string;
}
/** {@collect.stats}
* Returns the identifier for the specified row. The return value
* of this is used as the identifier for the
* <code>RowFilter.Entry</code> that is passed to the
* <code>RowFilter</code>.
*
* @param row the row to return the identifier for, in terms of
* the underlying model
* @return the identifier
* @see RowFilter.Entry#getIdentifier
*/
public abstract I getIdentifier(int row);
}
/** {@collect.stats}
* RowFilter.Entry implementation that delegates to the ModelWrapper.
* getFilterEntry(int) creates the single instance of this that is
* passed to the Filter. Only call getFilterEntry(int) to get
* the instance.
*/
private class FilterEntry extends RowFilter.Entry<M,I> {
/** {@collect.stats}
* The index into the model, set in getFilterEntry
*/
int modelIndex;
public M getModel() {
return getModelWrapper().getModel();
}
public int getValueCount() {
return getModelWrapper().getColumnCount();
}
public Object getValue(int index) {
return getModelWrapper().getValueAt(modelIndex, index);
}
public String getStringValue(int index) {
return getModelWrapper().getStringValueAt(modelIndex, index);
}
public I getIdentifier() {
return getModelWrapper().getIdentifier(modelIndex);
}
}
/** {@collect.stats}
* Row is used to handle the actual sorting by way of Comparable. It
* will use the sortKeys to do the actual comparison.
*/
// NOTE: this class is static so that it can be placed in an array
private static class Row implements Comparable<Row> {
private DefaultRowSorter sorter;
int modelIndex;
public Row(DefaultRowSorter sorter, int index) {
this.sorter = sorter;
modelIndex = index;
}
public int compareTo(Row o) {
return sorter.compare(modelIndex, o.modelIndex);
}
}
}
|
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.awt.event.*;
import java.awt.image.*;
import javax.swing.plaf.*;
import javax.swing.event.*;
import javax.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* An implementation of a "push" button.
* <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>
* 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 information and examples of using buttons.
* <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: An implementation of a \"push\" button.
*
* @author Jeff Dinkins
*/
public class JButton extends AbstractButton implements Accessible {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ButtonUI";
/** {@collect.stats}
* Creates a button with no set text or icon.
*/
public JButton() {
this(null, null);
}
/** {@collect.stats}
* Creates a button with an icon.
*
* @param icon the Icon image to display on the button
*/
public JButton(Icon icon) {
this(null, icon);
}
/** {@collect.stats}
* Creates a button with text.
*
* @param text the text of the button
*/
public JButton(String text) {
this(text, null);
}
/** {@collect.stats}
* Creates a button where properties are taken from the
* <code>Action</code> supplied.
*
* @param a the <code>Action</code> used to specify the new button
*
* @since 1.3
*/
public JButton(Action a) {
this();
setAction(a);
}
/** {@collect.stats}
* Creates a button with initial text and an icon.
*
* @param text the text of the button
* @param icon the Icon image to display on the button
*/
public JButton(String text, Icon icon) {
// Create the model
setModel(new DefaultButtonModel());
// initialize
init(text, icon);
}
/** {@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 "ButtonUI"
* @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 value of the <code>defaultButton</code> property,
* which if <code>true</code> means that this button is the current
* default button for its <code>JRootPane</code>.
* Most look and feels render the default button
* differently, and may potentially provide bindings
* to access the default button.
*
* @return the value of the <code>defaultButton</code> property
* @see JRootPane#setDefaultButton
* @see #isDefaultCapable
* @beaninfo
* description: Whether or not this button is the default button
*/
public boolean isDefaultButton() {
JRootPane root = SwingUtilities.getRootPane(this);
if (root != null) {
return root.getDefaultButton() == this;
}
return false;
}
/** {@collect.stats}
* Gets the value of the <code>defaultCapable</code> property.
*
* @return the value of the <code>defaultCapable</code> property
* @see #setDefaultCapable
* @see #isDefaultButton
* @see JRootPane#setDefaultButton
*/
public boolean isDefaultCapable() {
return defaultCapable;
}
/** {@collect.stats}
* Sets the <code>defaultCapable</code> property,
* which determines whether this button can be
* made the default button for its root pane.
* The default value of the <code>defaultCapable</code>
* property is <code>true</code> unless otherwise
* specified by the look and feel.
*
* @param defaultCapable <code>true</code> if this button will be
* capable of being the default button on the
* <code>RootPane</code>; otherwise <code>false</code>
* @see #isDefaultCapable
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether or not this button can be the default button
*/
public void setDefaultCapable(boolean defaultCapable) {
boolean oldDefaultCapable = this.defaultCapable;
this.defaultCapable = defaultCapable;
firePropertyChange("defaultCapable", oldDefaultCapable, defaultCapable);
}
/** {@collect.stats}
* Overrides <code>JComponent.removeNotify</code> to check if
* this button is currently set as the default button on the
* <code>RootPane</code>, and if so, sets the <code>RootPane</code>'s
* default button to <code>null</code> to ensure the
* <code>RootPane</code> doesn't hold onto an invalid button reference.
*/
public void removeNotify() {
JRootPane root = SwingUtilities.getRootPane(this);
if (root != null && root.getDefaultButton() == this) {
root.setDefaultButton(null);
}
super.removeNotify();
}
/** {@collect.stats}
* 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}
* Returns a string representation of this <code>JButton</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>JButton</code>
*/
protected String paramString() {
String defaultCapableString = (defaultCapable ? "true" : "false");
return super.paramString() +
",defaultCapable=" + defaultCapableString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with this
* <code>JButton</code>. For <code>JButton</code>s,
* the <code>AccessibleContext</code> takes the form of an
* <code>AccessibleJButton</code>.
* A new <code>AccessibleJButton</code> instance is created if necessary.
*
* @return an <code>AccessibleJButton</code> that serves as the
* <code>AccessibleContext</code> of this <code>JButton</code>
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this Button.
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJButton();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JButton</code> class. It provides an implementation of the
* Java Accessibility API appropriate to button 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 AccessibleJButton extends AccessibleAbstractButton {
/** {@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.PUSH_BUTTON;
}
} // inner class AccessibleJButton
}
|
Java
|
/*
* Copyright (c) 1999, 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;
import java.util.*;
/** {@collect.stats}
* The purpose of this class is to help clients support smooth focus
* navigation through GUIs with text fields. Such GUIs often need
* to ensure that the text entered by the user is valid (for example,
* that it's in
* the proper format) before allowing the user to navigate out of
* the text field. To do this, clients create a subclass of
* <code>InputVerifier</code> and, using <code>JComponent</code>'s
* <code>setInputVerifier</code> method,
* attach an instance of their subclass to the <code>JComponent</code> whose input they
* want to validate. Before focus is transfered to another Swing component
* that requests it, the input verifier's <code>shouldYieldFocus</code> method is
* called. Focus is transfered only if that method returns <code>true</code>.
* <p>
* The following example has two text fields, with the first one expecting
* the string "pass" to be entered by the user. If that string is entered in
* the first text field, then the user can advance to the second text field
* either by clicking in it or by pressing TAB. However, if another string
* is entered in the first text field, then the user will be unable to
* transfer focus to the second text field.
* <p>
* <pre>
* import java.awt.*;
* import java.util.*;
* import java.awt.event.*;
* import javax.swing.*;
*
* // This program demonstrates the use of the Swing InputVerifier class.
* // It creates two text fields; the first of the text fields expects the
* // string "pass" as input, and will allow focus to advance out of it
* // only after that string is typed in by the user.
*
* public class VerifierTest extends JFrame {
* public VerifierTest() {
* JTextField tf1 = new JTextField ("Type \"pass\" here");
* getContentPane().add (tf1, BorderLayout.NORTH);
* tf1.setInputVerifier(new PassVerifier());
*
* JTextField tf2 = new JTextField ("TextField2");
* getContentPane().add (tf2, BorderLayout.SOUTH);
*
* WindowListener l = new WindowAdapter() {
* public void windowClosing(WindowEvent e) {
* System.exit(0);
* }
* };
* addWindowListener(l);
* }
*
* class PassVerifier extends InputVerifier {
* public boolean verify(JComponent input) {
* JTextField tf = (JTextField) input;
* return "pass".equals(tf.getText());
* }
* }
*
* public static void main(String[] args) {
* Frame f = new VerifierTest();
* f.pack();
* f.setVisible(true);
* }
* }
* </pre>
*
* @since 1.3
*/
public abstract class InputVerifier {
/** {@collect.stats}
* Checks whether the JComponent's input is valid. This method should
* have no side effects. It returns a boolean indicating the status
* of the argument's input.
*
* @param input the JComponent to verify
* @return <code>true</code> when valid, <code>false</code> when invalid
* @see JComponent#setInputVerifier
* @see JComponent#getInputVerifier
*
*/
public abstract boolean verify(JComponent input);
/** {@collect.stats}
* Calls <code>verify(input)</code> to ensure that the input is valid.
* This method can have side effects. In particular, this method
* is called when the user attempts to advance focus out of the
* argument component into another Swing component in this window.
* If this method returns <code>true</code>, then the focus is transfered
* normally; if it returns <code>false</code>, then the focus remains in
* the argument component.
*
* @param input the JComponent to verify
* @return <code>true</code> when valid, <code>false</code> when invalid
* @see JComponent#setInputVerifier
* @see JComponent#getInputVerifier
*
*/
public boolean shouldYieldFocus(JComponent input) {
return verify(input);
}
}
|
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.*;
import java.io.*;
import java.beans.PropertyChangeListener;
import java.util.Locale;
import java.util.Vector;
import javax.accessibility.*;
/** {@collect.stats}
* This class is inserted in between cell renderers and the components that
* use them. It just exists to thwart the repaint() and invalidate() methods
* which would otherwise propagate up the tree when the renderer was configured.
* It's used by the implementations of JTable, JTree, and JList. For example,
* here's how CellRendererPane is used in the code the paints each row
* in a JList:
* <pre>
* cellRendererPane = new CellRendererPane();
* ...
* Component rendererComponent = renderer.getListCellRendererComponent();
* renderer.configureListCellRenderer(dataModel.getElementAt(row), row);
* cellRendererPane.paintComponent(g, rendererComponent, this, x, y, w, h);
* </pre>
* <p>
* A renderer component must override isShowing() and unconditionally return
* true to work correctly because the Swing paint does nothing for components
* with isShowing false.
* <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 CellRendererPane extends Container implements Accessible
{
/** {@collect.stats}
* Construct a CellRendererPane object.
*/
public CellRendererPane() {
super();
setLayout(null);
setVisible(false);
}
/** {@collect.stats}
* Overridden to avoid propagating a invalidate up the tree when the
* cell renderer child is configured.
*/
public void invalidate() { }
/** {@collect.stats}
* Shouldn't be called.
*/
public void paint(Graphics g) { }
/** {@collect.stats}
* Shouldn't be called.
*/
public void update(Graphics g) { }
/** {@collect.stats}
* If the specified component is already a child of this then we don't
* bother doing anything - stacking order doesn't matter for cell
* renderer components (CellRendererPane doesn't paint anyway).<
*/
protected void addImpl(Component x, Object constraints, int index) {
if (x.getParent() == this) {
return;
}
else {
super.addImpl(x, constraints, index);
}
}
/** {@collect.stats}
* Paint a cell renderer component c on graphics object g. Before the component
* is drawn it's reparented to this (if that's necessary), it's bounds
* are set to w,h and the graphics object is (effectively) translated to x,y.
* If it's a JComponent, double buffering is temporarily turned off. After
* the component is painted it's bounds are reset to -w, -h, 0, 0 so that, if
* it's the last renderer component painted, it will not start consuming input.
* The Container p is the component we're actually drawing on, typically it's
* equal to this.getParent(). If shouldValidate is true the component c will be
* validated before painted.
*/
public void paintComponent(Graphics g, Component c, Container p, int x, int y, int w, int h, boolean shouldValidate) {
if (c == null) {
if (p != null) {
Color oldColor = g.getColor();
g.setColor(p.getBackground());
g.fillRect(x, y, w, h);
g.setColor(oldColor);
}
return;
}
if (c.getParent() != this) {
this.add(c);
}
c.setBounds(x, y, w, h);
if(shouldValidate) {
c.validate();
}
boolean wasDoubleBuffered = false;
if ((c instanceof JComponent) && ((JComponent)c).isDoubleBuffered()) {
wasDoubleBuffered = true;
((JComponent)c).setDoubleBuffered(false);
}
Graphics cg = g.create(x, y, w, h);
try {
c.paint(cg);
}
finally {
cg.dispose();
}
if (wasDoubleBuffered && (c instanceof JComponent)) {
((JComponent)c).setDoubleBuffered(true);
}
c.setBounds(-w, -h, 0, 0);
}
/** {@collect.stats}
* Calls this.paintComponent(g, c, p, x, y, w, h, false).
*/
public void paintComponent(Graphics g, Component c, Container p, int x, int y, int w, int h) {
paintComponent(g, c, p, x, y, w, h, false);
}
/** {@collect.stats}
* Calls this.paintComponent() with the rectangles x,y,width,height fields.
*/
public void paintComponent(Graphics g, Component c, Container p, Rectangle r) {
paintComponent(g, c, p, r.x, r.y, r.width, r.height);
}
private void writeObject(ObjectOutputStream s) throws IOException {
removeAll();
s.defaultWriteObject();
}
/////////////////
// Accessibility support
////////////////
protected AccessibleContext accessibleContext = null;
/** {@collect.stats}
* Gets the AccessibleContext associated with this CellRendererPane.
* For CellRendererPanes, the AccessibleContext takes the form of an
* AccessibleCellRendererPane.
* A new AccessibleCellRendererPane instance is created if necessary.
*
* @return an AccessibleCellRendererPane that serves as the
* AccessibleContext of this CellRendererPane
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleCellRendererPane();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>CellRendererPane</code> class.
*/
protected class AccessibleCellRendererPane extends AccessibleAWTContainer {
// AccessibleContext methods
//
/** {@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.PANEL;
}
} // inner class AccessibleCellRendererPane
}
|
Java
|
/*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.*;
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
import java.io.*;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.swing.event.EventListenerList;
/** {@collect.stats}
* Fires one or more {@code ActionEvent}s at specified
* intervals. An example use is an animation object that uses a
* <code>Timer</code> as the trigger for drawing its frames.
*<p>
* Setting up a timer
* involves creating a <code>Timer</code> object,
* registering one or more action listeners on it,
* and starting the timer using
* the <code>start</code> method.
* For example,
* the following code creates and starts a timer
* that fires an action event once per second
* (as specified by the first argument to the <code>Timer</code> constructor).
* The second argument to the <code>Timer</code> constructor
* specifies a listener to receive the timer's action events.
*
*<pre>
* int delay = 1000; //milliseconds
* ActionListener taskPerformer = new ActionListener() {
* public void actionPerformed(ActionEvent evt) {
* <em>//...Perform a task...</em>
* }
* };
* new Timer(delay, taskPerformer).start();</pre>
*
* <p>
* {@code Timers} are constructed by specifying both a delay parameter
* and an {@code ActionListener}. The delay parameter is used
* to set both the initial delay and the delay between event
* firing, in milliseconds. Once the timer has been started,
* it waits for the initial delay before firing its
* first <code>ActionEvent</code> to registered listeners.
* After this first event, it continues to fire events
* every time the between-event delay has elapsed, until it
* is stopped.
* <p>
* After construction, the initial delay and the between-event
* delay can be changed independently, and additional
* <code>ActionListeners</code> may be added.
* <p>
* If you want the timer to fire only the first time and then stop,
* invoke <code>setRepeats(false)</code> on the timer.
* <p>
* Although all <code>Timer</code>s perform their waiting
* using a single, shared thread
* (created by the first <code>Timer</code> object that executes),
* the action event handlers for <code>Timer</code>s
* execute on another thread -- the event-dispatching thread.
* This means that the action handlers for <code>Timer</code>s
* can safely perform operations on Swing components.
* However, it also means that the handlers must execute quickly
* to keep the GUI responsive.
*
* <p>
* In v 1.3, another <code>Timer</code> class was added
* to the Java platform: <code>java.util.Timer</code>.
* Both it and <code>javax.swing.Timer</code>
* provide the same basic functionality,
* but <code>java.util.Timer</code>
* is more general and has more features.
* The <code>javax.swing.Timer</code> has two features
* that can make it a little easier to use with GUIs.
* First, its event handling metaphor is familiar to GUI programmers
* and can make dealing with the event-dispatching thread
* a bit simpler.
* Second, its
* automatic thread sharing means that you don't have to
* take special steps to avoid spawning
* too many threads.
* Instead, your timer uses the same thread
* used to make cursors blink,
* tool tips appear,
* and so on.
*
* <p>
* You can find further documentation
* and several examples of using timers by visiting
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html"
* target = "_top">How to Use Timers</a>,
* a section in <em>The Java Tutorial.</em>
* For more examples and help in choosing between
* this <code>Timer</code> class and
* <code>java.util.Timer</code>,
* see
* <a href="http://java.sun.com/products/jfc/tsc/articles/timer/"
* target="_top">Using Timers in Swing Applications</a>,
* an article in <em>The Swing Connection.</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.util.Timer <code>java.util.Timer</code>
*
*
* @author Dave Moore
*/
public class Timer implements Serializable
{
/*
* NOTE: all fields need to be handled in readResolve
*/
protected EventListenerList listenerList = new EventListenerList();
// The following field strives to maintain the following:
// If coalesce is true, only allow one Runnable to be queued on the
// EventQueue and be pending (ie in the process of notifying the
// ActionListener). If we didn't do this it would allow for a
// situation where the app is taking too long to process the
// actionPerformed, and thus we'ld end up queing a bunch of Runnables
// and the app would never return: not good. This of course implies
// you can get dropped events, but such is life.
// notify is used to indicate if the ActionListener can be notified, when
// the Runnable is processed if this is true it will notify the listeners.
// notify is set to true when the Timer fires and the Runnable is queued.
// It will be set to false after notifying the listeners (if coalesce is
// true) or if the developer invokes stop.
private transient final AtomicBoolean notify = new AtomicBoolean(false);
private volatile int initialDelay, delay;
private volatile boolean repeats = true, coalesce = true;
private transient final Runnable doPostEvent;
private static volatile boolean logTimers;
private transient final Lock lock = new ReentrantLock();
/*
* The timer's AccessControlContext.
*/
private transient volatile AccessControlContext acc =
AccessController.getContext();
/** {@collect.stats}
* Returns the acc this timer was constructed with.
*/
final AccessControlContext getAccessControlContext() {
if (acc == null) {
throw new SecurityException(
"Timer is missing AccessControlContext");
}
return acc;
}
// This field is maintained by TimerQueue.
// eventQueued can also be reset by the TimerQueue, but will only ever
// happen in applet case when TimerQueues thread is destroyed.
// access to this field is synchronized on getLock() lock.
transient TimerQueue.DelayedTimer delayedTimer = null;
private volatile String actionCommand;
/** {@collect.stats}
* Creates a {@code Timer} and initializes both the initial delay and
* between-event delay to {@code delay} milliseconds. If {@code delay}
* is less than or equal to zero, the timer fires as soon as it
* is started. If <code>listener</code> is not <code>null</code>,
* it's registered as an action listener on the timer.
*
* @param delay milliseconds for the initial and between-event delay
* @param listener an initial listener; can be <code>null</code>
* @see #addActionListener
* @see #setInitialDelay
* @see #setRepeats
*/
public Timer(int delay, ActionListener listener) {
super();
this.delay = delay;
this.initialDelay = delay;
doPostEvent = new DoPostEvent();
if (listener != null) {
addActionListener(listener);
}
}
/** {@collect.stats}
* DoPostEvent is a runnable class that fires actionEvents to
* the listeners on the EventDispatchThread, via invokeLater.
* @see Timer#post
*/
class DoPostEvent implements Runnable
{
public void run() {
if (logTimers) {
System.out.println("Timer ringing: " + Timer.this);
}
if(notify.get()) {
fireActionPerformed(new ActionEvent(Timer.this, 0, getActionCommand(),
System.currentTimeMillis(),
0));
if (coalesce) {
cancelEvent();
}
}
}
Timer getTimer() {
return Timer.this;
}
}
/** {@collect.stats}
* Adds an action listener to the <code>Timer</code>.
*
* @param listener the listener to add
*
* @see #Timer
*/
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
/** {@collect.stats}
* Removes the specified action listener from the <code>Timer</code>.
*
* @param listener the listener to remove
*/
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
/** {@collect.stats}
* Returns an array of all the action listeners registered
* on this timer.
*
* @return all of the timer'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.
*
* @param e the action event to fire
* @see EventListenerList
*/
protected void fireActionPerformed(ActionEvent 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]==ActionListener.class) {
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
}
/** {@collect.stats}
* Returns an array of all the objects currently registered as
* <code><em>Foo</em>Listener</code>s
* upon this <code>Timer</code>.
* <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>Timer</code>
* instance <code>t</code>
* for its action listeners
* with the following code:
*
* <pre>ActionListener[] als = (ActionListener[])(t.getListeners(ActionListener.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 timer,
* 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 #getActionListeners
* @see #addActionListener
* @see #removeActionListener
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
/** {@collect.stats}
* Returns the timer queue.
*/
private TimerQueue timerQueue() {
return TimerQueue.sharedInstance();
}
/** {@collect.stats}
* Enables or disables the timer log. When enabled, a message
* is posted to <code>System.out</code> whenever the timer goes off.
*
* @param flag <code>true</code> to enable logging
* @see #getLogTimers
*/
public static void setLogTimers(boolean flag) {
logTimers = flag;
}
/** {@collect.stats}
* Returns <code>true</code> if logging is enabled.
*
* @return <code>true</code> if logging is enabled; otherwise, false
* @see #setLogTimers
*/
public static boolean getLogTimers() {
return logTimers;
}
/** {@collect.stats}
* Sets the <code>Timer</code>'s between-event delay, the number of milliseconds
* between successive action events. This does not affect the initial delay
* property, which can be set by the {@code setInitialDelay} method.
*
* @param delay the delay in milliseconds
* @see #setInitialDelay
*/
public void setDelay(int delay) {
if (delay < 0) {
throw new IllegalArgumentException("Invalid delay: " + delay);
}
else {
this.delay = delay;
}
}
/** {@collect.stats}
* Returns the delay, in milliseconds,
* between firings of action events.
*
* @see #setDelay
* @see #getInitialDelay
*/
public int getDelay() {
return delay;
}
/** {@collect.stats}
* Sets the <code>Timer</code>'s initial delay, the time
* in milliseconds to wait after the timer is started
* before firing the first event. Upon construction, this
* is set to be the same as the between-event delay,
* but then its value is independent and remains unaffected
* by changes to the between-event delay.
*
* @param initialDelay the initial delay, in milliseconds
* @see #setDelay
*/
public void setInitialDelay(int initialDelay) {
if (initialDelay < 0) {
throw new IllegalArgumentException("Invalid initial delay: " +
initialDelay);
}
else {
this.initialDelay = initialDelay;
}
}
/** {@collect.stats}
* Returns the <code>Timer</code>'s initial delay.
*
* @see #setInitialDelay
* @see #setDelay
*/
public int getInitialDelay() {
return initialDelay;
}
/** {@collect.stats}
* If <code>flag</code> is <code>false</code>,
* instructs the <code>Timer</code> to send only one
* action event to its listeners.
*
* @param flag specify <code>false</code> to make the timer
* stop after sending its first action event
*/
public void setRepeats(boolean flag) {
repeats = flag;
}
/** {@collect.stats}
* Returns <code>true</code> (the default)
* if the <code>Timer</code> will send
* an action event
* to its listeners multiple times.
*
* @see #setRepeats
*/
public boolean isRepeats() {
return repeats;
}
/** {@collect.stats}
* Sets whether the <code>Timer</code> coalesces multiple pending
* <code>ActionEvent</code> firings.
* A busy application may not be able
* to keep up with a <code>Timer</code>'s event generation,
* causing multiple
* action events to be queued. When processed,
* the application sends these events one after the other, causing the
* <code>Timer</code>'s listeners to receive a sequence of
* events with no delay between them. Coalescing avoids this situation
* by reducing multiple pending events to a single event.
* <code>Timer</code>s
* coalesce events by default.
*
* @param flag specify <code>false</code> to turn off coalescing
*/
public void setCoalesce(boolean flag) {
boolean old = coalesce;
coalesce = flag;
if (!old && coalesce) {
// We must do this as otherwise if the Timer once notified
// in !coalese mode notify will be stuck to true and never
// become false.
cancelEvent();
}
}
/** {@collect.stats}
* Returns <code>true</code> if the <code>Timer</code> coalesces
* multiple pending action events.
*
* @see #setCoalesce
*/
public boolean isCoalesce() {
return coalesce;
}
/** {@collect.stats}
* Sets the string that will be delivered as the action command
* in <code>ActionEvent</code>s fired by this timer.
* <code>null</code> is an acceptable value.
*
* @param command the action command
* @since 1.6
*/
public void setActionCommand(String command) {
this.actionCommand = command;
}
/** {@collect.stats}
* Returns the string that will be delivered as the action command
* in <code>ActionEvent</code>s fired by this timer. May be
* <code>null</code>, which is also the default.
*
* @return the action command used in firing events
* @since 1.6
*/
public String getActionCommand() {
return actionCommand;
}
/** {@collect.stats}
* Starts the <code>Timer</code>,
* causing it to start sending action events
* to its listeners.
*
* @see #stop
*/
public void start() {
timerQueue().addTimer(this, getInitialDelay());
}
/** {@collect.stats}
* Returns <code>true</code> if the <code>Timer</code> is running.
*
* @see #start
*/
public boolean isRunning() {
return timerQueue().containsTimer(this);
}
/** {@collect.stats}
* Stops the <code>Timer</code>,
* causing it to stop sending action events
* to its listeners.
*
* @see #start
*/
public void stop() {
getLock().lock();
try {
cancelEvent();
timerQueue().removeTimer(this);
} finally {
getLock().unlock();
}
}
/** {@collect.stats}
* Restarts the <code>Timer</code>,
* canceling any pending firings and causing
* it to fire with its initial delay.
*/
public void restart() {
getLock().lock();
try {
stop();
start();
} finally {
getLock().unlock();
}
}
/** {@collect.stats}
* Resets the internal state to indicate this Timer shouldn't notify
* any of its listeners. This does not stop a repeatable Timer from
* firing again, use <code>stop</code> for that.
*/
void cancelEvent() {
notify.set(false);
}
void post() {
if (notify.compareAndSet(false, true) || !coalesce) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
SwingUtilities.invokeLater(doPostEvent);
return null;
}
}, getAccessControlContext());
}
}
Lock getLock() {
return lock;
}
/*
* We have to use readResolve because we can not initialize final
* fields for deserialized object otherwise
*/
private Object readResolve() {
Timer timer = new Timer(getDelay(), null);
timer.listenerList = listenerList;
timer.initialDelay = initialDelay;
timer.delay = delay;
timer.repeats = repeats;
timer.coalesce = coalesce;
timer.actionCommand = actionCommand;
return timer;
}
private void readObject(ObjectInputStream in)
throws ClassNotFoundException, IOException
{
this.acc = AccessController.getContext();
in.defaultReadObject();
}
}
|
Java
|
/*
* Copyright (c) 1997, 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.undo;
import javax.swing.event.*;
/** {@collect.stats}
* An <code>UndoableEdit</code> represents an edit. The edit may
* be undone, or if already undone the edit may be redone.
* <p>
* <code>UndoableEdit</code> is designed to be used with the
* <code>UndoManager</code>. As <code>UndoableEdit</code>s are generated
* by an <code>UndoableEditListener</code> they are typically added to
* the <code>UndoManager</code>. When an <code>UndoableEdit</code>
* is added to an <code>UndoManager</code> the following occurs (assuming
* <code>end</code> has not been called on the <code>UndoManager</code>):
* <ol>
* <li>If the <code>UndoManager</code> contains edits it will call
* <code>addEdit</code> on the current edit passing in the new edit
* as the argument. If <code>addEdit</code> returns true the
* new edit is assumed to have been incorporated into the current edit and
* the new edit will not be added to the list of current edits.
* Edits can use <code>addEdit</code> as a way for smaller edits to
* be incorporated into a larger edit and treated as a single edit.
* <li>If <code>addEdit</code> returns false <code>replaceEdit</code>
* is called on the new edit with the current edit passed in as the
* argument. This is the inverse of <code>addEdit</code> —
* if the new edit returns true from <code>replaceEdit</code>, the new
* edit replaces the current edit.
* </ol>
* The <code>UndoManager</code> makes use of
* <code>isSignificant</code> to determine how many edits should be
* undone or redone. The <code>UndoManager</code> will undo or redo
* all insignificant edits (<code>isSignificant</code> returns false)
* between the current edit and the last or
* next significant edit. <code>addEdit</code> and
* <code>replaceEdit</code> can be used to treat multiple edits as
* a single edit, returning false from <code>isSignificant</code>
* allows for treating can be used to
* have many smaller edits undone or redone at once. Similar functionality
* can also be done using the <code>addEdit</code> method.
*
* @author Ray Ryan
*/
public interface UndoableEdit {
/** {@collect.stats}
* Undo the edit.
*
* @throws CannotUndoException if this edit can not be undone
*/
public void undo() throws CannotUndoException;
/** {@collect.stats}
* Returns true if this edit may be undone.
*
* @return true if this edit may be undone
*/
public boolean canUndo();
/** {@collect.stats}
* Re-applies the edit.
*
* @throws CannotRedoException if this edit can not be redone
*/
public void redo() throws CannotRedoException;
/** {@collect.stats}
* Returns true if this edit may be redone.
*
* @return true if this edit may be redone
*/
public boolean canRedo();
/** {@collect.stats}
* Informs the edit that it should no longer be used. Once an
* <code>UndoableEdit</code> has been marked as dead it can no longer
* be undone or redone.
* <p>
* This is a useful hook for cleaning up state no longer
* needed once undoing or redoing is impossible--for example,
* deleting file resources used by objects that can no longer be
* undeleted. <code>UndoManager</code> calls this before it dequeues edits.
* <p>
* Note that this is a one-way operation. There is no "un-die"
* method.
*
* @see CompoundEdit#die
*/
public void die();
/** {@collect.stats}
* Adds an <code>UndoableEdit</code> to this <code>UndoableEdit</code>.
* This method can be used to coalesce smaller edits into a larger
* compound edit. For example, text editors typically allow
* undo operations to apply to words or sentences. The text
* editor may choose to generate edits on each key event, but allow
* those edits to be coalesced into a more user-friendly unit, such as
* a word. In this case, the <code>UndoableEdit</code> would
* override <code>addEdit</code> to return true when the edits may
* be coalesced.
* <p>
* A return value of true indicates <code>anEdit</code> was incorporated
* into this edit. A return value of false indicates <code>anEdit</code>
* may not be incorporated into this edit.
* <p>Typically the receiver is already in the queue of a
* <code>UndoManager</code> (or other <code>UndoableEditListener</code>),
* and is being given a chance to incorporate <code>anEdit</code>
* rather than letting it be added to the queue in turn.</p>
*
* <p>If true is returned, from now on <code>anEdit</code> must return
* false from <code>canUndo</code> and <code>canRedo</code>,
* and must throw the appropriate exception on <code>undo</code> or
* <code>redo</code>.</p>
*
* @param anEdit the edit to be added
* @return true if <code>anEdit</code> may be incorporated into this
* edit
*/
public boolean addEdit(UndoableEdit anEdit);
/** {@collect.stats}
* Returns true if this <code>UndoableEdit</code> should replace
* <code>anEdit</code>. This method is used by <code>CompoundEdit</code>
* and the <code>UndoManager</code>; it is called if
* <code>anEdit</code> could not be added to the current edit
* (<code>addEdit</code> returns false).
* <p>
* This method provides a way for an edit to replace an existing edit.
* <p>This message is the opposite of addEdit--anEdit has typically
* already been queued in an <code>UndoManager</code> (or other
* UndoableEditListener), and the receiver is being given a chance
* to take its place.</p>
*
* <p>If true is returned, from now on anEdit must return false from
* canUndo() and canRedo(), and must throw the appropriate
* exception on undo() or redo().</p>
*
* @param anEdit the edit that replaces the current edit
* @return true if this edit should replace <code>anEdit</code>
*/
public boolean replaceEdit(UndoableEdit anEdit);
/** {@collect.stats}
* Returns true if this edit is considered significant. A significant
* edit is typically an edit that should be presented to the user, perhaps
* on a menu item or tooltip. The <code>UndoManager</code> will undo,
* or redo, all insignificant edits to the next significant edit.
*
* @return true if this edit is significant
*/
public boolean isSignificant();
/** {@collect.stats}
* Returns a localized, human-readable description of this edit, suitable
* for use in a change log, for example.
*
* @return description of this edit
*/
public String getPresentationName();
/** {@collect.stats}
* Returns a localized, human-readable description of the undoable form of
* this edit, suitable for use as an Undo menu item, for example.
* This is typically derived from <code>getPresentationName</code>.
*
* @return a description of the undoable form of this edit
*/
public String getUndoPresentationName();
/** {@collect.stats}
* Returns a localized, human-readable description of the redoable form of
* this edit, suitable for use as a Redo menu item, for example. This is
* typically derived from <code>getPresentationName</code>.
*
* @return a description of the redoable form of this edit
*/
public String getRedoPresentationName();
}
|
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.undo;
/** {@collect.stats}
* Thrown when an UndoableEdit is told to <code>undo()</code> and can't.
* <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 CannotUndoException extends RuntimeException {
}
|
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.undo;
import java.util.*;
/** {@collect.stats}
* A concrete subclass of AbstractUndoableEdit, used to assemble little
* UndoableEdits into great big ones.
*
* @author Ray Ryan
*/
public class CompoundEdit extends AbstractUndoableEdit {
/** {@collect.stats}
* True if this edit has never received <code>end</code>.
*/
boolean inProgress;
/** {@collect.stats}
* The collection of <code>UndoableEdit</code>s
* undone/redone en masse by this <code>CompoundEdit</code>.
*/
protected Vector<UndoableEdit> edits;
public CompoundEdit() {
super();
inProgress = true;
edits = new Vector<UndoableEdit>();
}
/** {@collect.stats}
* Sends <code>undo</code> to all contained
* <code>UndoableEdits</code> in the reverse of
* the order in which they were added.
*/
public void undo() throws CannotUndoException {
super.undo();
int i = edits.size();
while (i-- > 0) {
UndoableEdit e = (UndoableEdit)edits.elementAt(i);
e.undo();
}
}
/** {@collect.stats}
* Sends <code>redo</code> to all contained
* <code>UndoableEdit</code>s in the order in
* which they were added.
*/
public void redo() throws CannotRedoException {
super.redo();
Enumeration cursor = edits.elements();
while (cursor.hasMoreElements()) {
((UndoableEdit)cursor.nextElement()).redo();
}
}
/** {@collect.stats}
* Returns the last <code>UndoableEdit</code> in
* <code>edits</code>, or <code>null</code>
* if <code>edits</code> is empty.
*/
protected UndoableEdit lastEdit() {
int count = edits.size();
if (count > 0)
return (UndoableEdit)edits.elementAt(count-1);
else
return null;
}
/** {@collect.stats}
* Sends <code>die</code> to each subedit,
* in the reverse of the order that they were added.
*/
public void die() {
int size = edits.size();
for (int i = size-1; i >= 0; i--)
{
UndoableEdit e = (UndoableEdit)edits.elementAt(i);
// System.out.println("CompoundEdit(" + i + "): Discarding " +
// e.getUndoPresentationName());
e.die();
}
super.die();
}
/** {@collect.stats}
* If this edit is <code>inProgress</code>,
* accepts <code>anEdit</code> and returns true.
*
* <p>The last edit added to this <code>CompoundEdit</code>
* is given a chance to <code>addEdit(anEdit)</code>.
* If it refuses (returns false), <code>anEdit</code> is
* given a chance to <code>replaceEdit</code> the last edit.
* If <code>anEdit</code> returns false here,
* it is added to <code>edits</code>.
*
* @param anEdit the edit to be added
* @return true if the edit is <code>inProgress</code>;
* otherwise returns false
*/
public boolean addEdit(UndoableEdit anEdit) {
if (!inProgress) {
return false;
} else {
UndoableEdit last = lastEdit();
// If this is the first subedit received, just add it.
// Otherwise, give the last one a chance to absorb the new
// one. If it won't, give the new one a chance to absorb
// the last one.
if (last == null) {
edits.addElement(anEdit);
}
else if (!last.addEdit(anEdit)) {
if (anEdit.replaceEdit(last)) {
edits.removeElementAt(edits.size()-1);
}
edits.addElement(anEdit);
}
return true;
}
}
/** {@collect.stats}
* Sets <code>inProgress</code> to false.
*
* @see #canUndo
* @see #canRedo
*/
public void end() {
inProgress = false;
}
/** {@collect.stats}
* Returns false if <code>isInProgress</code> or if super
* returns false.
*
* @see #isInProgress
*/
public boolean canUndo() {
return !isInProgress() && super.canUndo();
}
/** {@collect.stats}
* Returns false if <code>isInProgress</code> or if super
* returns false.
*
* @see #isInProgress
*/
public boolean canRedo() {
return !isInProgress() && super.canRedo();
}
/** {@collect.stats}
* Returns true if this edit is in progress--that is, it has not
* received end. This generally means that edits are still being
* added to it.
*
* @see #end
*/
public boolean isInProgress() {
return inProgress;
}
/** {@collect.stats}
* Returns true if any of the <code>UndoableEdit</code>s
* in <code>edits</code> do.
* Returns false if they all return false.
*/
public boolean isSignificant() {
Enumeration cursor = edits.elements();
while (cursor.hasMoreElements()) {
if (((UndoableEdit)cursor.nextElement()).isSignificant()) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Returns <code>getPresentationName</code> from the
* last <code>UndoableEdit</code> added to
* <code>edits</code>. If <code>edits</code> is empty,
* calls super.
*/
public String getPresentationName() {
UndoableEdit last = lastEdit();
if (last != null) {
return last.getPresentationName();
} else {
return super.getPresentationName();
}
}
/** {@collect.stats}
* Returns <code>getUndoPresentationName</code>
* from the last <code>UndoableEdit</code>
* added to <code>edits</code>.
* If <code>edits</code> is empty, calls super.
*/
public String getUndoPresentationName() {
UndoableEdit last = lastEdit();
if (last != null) {
return last.getUndoPresentationName();
} else {
return super.getUndoPresentationName();
}
}
/** {@collect.stats}
* Returns <code>getRedoPresentationName</code>
* from the last <code>UndoableEdit</code>
* added to <code>edits</code>.
* If <code>edits</code> is empty, calls super.
*/
public String getRedoPresentationName() {
UndoableEdit last = lastEdit();
if (last != null) {
return last.getRedoPresentationName();
} else {
return super.getRedoPresentationName();
}
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public String toString()
{
return super.toString()
+ " inProgress: " + inProgress
+ " edits: " + edits;
}
}
|
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.undo;
import javax.swing.event.*;
import javax.swing.UIManager;
import java.util.*;
/** {@collect.stats}
* {@code UndoManager} manages a list of {@code UndoableEdits},
* providing a way to undo or redo the appropriate edits. There are
* two ways to add edits to an <code>UndoManager</code>. Add the edit
* directly using the <code>addEdit</code> method, or add the
* <code>UndoManager</code> to a bean that supports
* <code>UndoableEditListener</code>. The following examples creates
* an <code>UndoManager</code> and adds it as an
* <code>UndoableEditListener</code> to a <code>JTextField</code>:
* <pre>
* UndoManager undoManager = new UndoManager();
* JTextField tf = ...;
* tf.getDocument().addUndoableEditListener(undoManager);
* </pre>
* <p>
* <code>UndoManager</code> maintains an ordered list of edits and the
* index of the next edit in that list. The index of the next edit is
* either the size of the current list of edits, or if
* <code>undo</code> has been invoked it corresponds to the index
* of the last significant edit that was undone. When
* <code>undo</code> is invoked all edits from the index of the next
* edit to the last significant edit are undone, in reverse order.
* For example, consider an <code>UndoManager</code> consisting of the
* following edits: <b>A</b> <i>b</i> <i>c</i> <b>D</b>. Edits with a
* upper-case letter in bold are significant, those in lower-case
* and italicized are insignificant.
* <p>
* <a name="figure1"></a>
* <table border=0>
* <tr><td>
* <img src="doc-files/UndoManager-1.gif">
* <tr><td align=center>Figure 1
* </table>
* <p>
* As shown in <a href="#figure1">figure 1</a>, if <b>D</b> was just added, the
* index of the next edit will be 4. Invoking <code>undo</code>
* results in invoking <code>undo</code> on <b>D</b> and setting the
* index of the next edit to 3 (edit <i>c</i>), as shown in the following
* figure.
* <p>
* <a name="figure2"></a>
* <table border=0>
* <tr><td>
* <img src="doc-files/UndoManager-2.gif">
* <tr><td align=center>Figure 2
* </table>
* <p>
* The last significant edit is <b>A</b>, so that invoking
* <code>undo</code> again invokes <code>undo</code> on <i>c</i>,
* <i>b</i>, and <b>A</b>, in that order, setting the index of the
* next edit to 0, as shown in the following figure.
* <p>
* <a name="figure3"></a>
* <table border=0>
* <tr><td>
* <img src="doc-files/UndoManager-3.gif">
* <tr><td align=center>Figure 3
* </table>
* <p>
* Invoking <code>redo</code> results in invoking <code>redo</code> on
* all edits between the index of the next edit and the next
* significant edit (or the end of the list). Continuing with the previous
* example if <code>redo</code> were invoked, <code>redo</code> would in
* turn be invoked on <b>A</b>, <i>b</i> and <i>c</i>. In addition
* the index of the next edit is set to 3 (as shown in <a
* href="#figure2">figure 2</a>).
* <p>
* Adding an edit to an <code>UndoManager</code> results in
* removing all edits from the index of the next edit to the end of
* the list. Continuing with the previous example, if a new edit,
* <i>e</i>, is added the edit <b>D</b> is removed from the list
* (after having <code>die</code> invoked on it). If <i>c</i> is not
* incorporated by the next edit
* (<code><i>c</i>.addEdit(<i>e</i>)</code> returns true), or replaced
* by it (<code><i>e</i>.replaceEdit(<i>c</i>)</code> returns true),
* the new edit is added after <i>c</i>, as shown in the following
* figure.
* <p>
* <a name="figure4"></a>
* <table border=0>
* <tr><td>
* <img src="doc-files/UndoManager-4.gif">
* <tr><td align=center>Figure 4
* </table>
* <p>
* Once <code>end</code> has been invoked on an <code>UndoManager</code>
* the superclass behavior is used for all <code>UndoableEdit</code>
* methods. Refer to <code>CompoundEdit</code> for more details on its
* behavior.
* <p>
* Unlike the rest of Swing, this class is thread safe.
* <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 UndoManager extends CompoundEdit implements UndoableEditListener {
int indexOfNextAdd;
int limit;
/** {@collect.stats}
* Creates a new <code>UndoManager</code>.
*/
public UndoManager() {
super();
indexOfNextAdd = 0;
limit = 100;
edits.ensureCapacity(limit);
}
/** {@collect.stats}
* Returns the maximum number of edits this {@code UndoManager}
* holds. A value less than 0 indicates the number of edits is not
* limited.
*
* @return the maximum number of edits this {@code UndoManager} holds
* @see #addEdit
* @see #setLimit
*/
public synchronized int getLimit() {
return limit;
}
/** {@collect.stats}
* Empties the undo manager sending each edit a <code>die</code> message
* in the process.
*
* @see AbstractUndoableEdit#die
*/
public synchronized void discardAllEdits() {
Enumeration cursor = edits.elements();
while (cursor.hasMoreElements()) {
UndoableEdit e = (UndoableEdit)cursor.nextElement();
e.die();
}
edits = new Vector();
indexOfNextAdd = 0;
// PENDING(rjrjr) when vector grows a removeRange() method
// (expected in JDK 1.2), trimEdits() will be nice and
// efficient, and this method can call that instead.
}
/** {@collect.stats}
* Reduces the number of queued edits to a range of size limit,
* centered on the index of the next edit.
*/
protected void trimForLimit() {
if (limit >= 0) {
int size = edits.size();
// System.out.print("limit: " + limit +
// " size: " + size +
// " indexOfNextAdd: " + indexOfNextAdd +
// "\n");
if (size > limit) {
int halfLimit = limit/2;
int keepFrom = indexOfNextAdd - 1 - halfLimit;
int keepTo = indexOfNextAdd - 1 + halfLimit;
// These are ints we're playing with, so dividing by two
// rounds down for odd numbers, so make sure the limit was
// honored properly. Note that the keep range is
// inclusive.
if (keepTo - keepFrom + 1 > limit) {
keepFrom++;
}
// The keep range is centered on indexOfNextAdd,
// but odds are good that the actual edits Vector
// isn't. Move the keep range to keep it legal.
if (keepFrom < 0) {
keepTo -= keepFrom;
keepFrom = 0;
}
if (keepTo >= size) {
int delta = size - keepTo - 1;
keepTo += delta;
keepFrom += delta;
}
// System.out.println("Keeping " + keepFrom + " " + keepTo);
trimEdits(keepTo+1, size-1);
trimEdits(0, keepFrom-1);
}
}
}
/** {@collect.stats}
* Removes edits in the specified range.
* All edits in the given range (inclusive, and in reverse order)
* will have <code>die</code> invoked on them and are removed from
* the list of edits. This has no effect if
* <code>from</code> > <code>to</code>.
*
* @param from the minimum index to remove
* @param to the maximum index to remove
*/
protected void trimEdits(int from, int to) {
if (from <= to) {
// System.out.println("Trimming " + from + " " + to + " with index " +
// indexOfNextAdd);
for (int i = to; from <= i; i--) {
UndoableEdit e = (UndoableEdit)edits.elementAt(i);
// System.out.println("JUM: Discarding " +
// e.getUndoPresentationName());
e.die();
// PENDING(rjrjr) when Vector supports range deletion (JDK
// 1.2) , we can optimize the next line considerably.
edits.removeElementAt(i);
}
if (indexOfNextAdd > to) {
// System.out.print("...right...");
indexOfNextAdd -= to-from+1;
} else if (indexOfNextAdd >= from) {
// System.out.println("...mid...");
indexOfNextAdd = from;
}
// System.out.println("new index " + indexOfNextAdd);
}
}
/** {@collect.stats}
* Sets the maximum number of edits this <code>UndoManager</code>
* holds. A value less than 0 indicates the number of edits is not
* limited. If edits need to be discarded to shrink the limit,
* <code>die</code> will be invoked on them in the reverse
* order they were added. The default is 100.
*
* @param l the new limit
* @throws RuntimeException if this {@code UndoManager} is not in progress
* ({@code end} has been invoked)
* @see #isInProgress
* @see #end
* @see #addEdit
* @see #getLimit
*/
public synchronized void setLimit(int l) {
if (!inProgress) throw new RuntimeException("Attempt to call UndoManager.setLimit() after UndoManager.end() has been called");
limit = l;
trimForLimit();
}
/** {@collect.stats}
* Returns the the next significant edit to be undone if <code>undo</code>
* is invoked. This returns <code>null</code> if there are no edits
* to be undone.
*
* @return the next significant edit to be undone
*/
protected UndoableEdit editToBeUndone() {
int i = indexOfNextAdd;
while (i > 0) {
UndoableEdit edit = (UndoableEdit)edits.elementAt(--i);
if (edit.isSignificant()) {
return edit;
}
}
return null;
}
/** {@collect.stats}
* Returns the the next significant edit to be redone if <code>redo</code>
* is invoked. This returns <code>null</code> if there are no edits
* to be redone.
*
* @return the next significant edit to be redone
*/
protected UndoableEdit editToBeRedone() {
int count = edits.size();
int i = indexOfNextAdd;
while (i < count) {
UndoableEdit edit = (UndoableEdit)edits.elementAt(i++);
if (edit.isSignificant()) {
return edit;
}
}
return null;
}
/** {@collect.stats}
* Undoes all changes from the index of the next edit to
* <code>edit</code>, updating the index of the next edit appropriately.
*
* @throws CannotUndoException if one of the edits throws
* <code>CannotUndoException</code>
*/
protected void undoTo(UndoableEdit edit) throws CannotUndoException {
boolean done = false;
while (!done) {
UndoableEdit next = (UndoableEdit)edits.elementAt(--indexOfNextAdd);
next.undo();
done = next == edit;
}
}
/** {@collect.stats}
* Redoes all changes from the index of the next edit to
* <code>edit</code>, updating the index of the next edit appropriately.
*
* @throws CannotRedoException if one of the edits throws
* <code>CannotRedoException</code>
*/
protected void redoTo(UndoableEdit edit) throws CannotRedoException {
boolean done = false;
while (!done) {
UndoableEdit next = (UndoableEdit)edits.elementAt(indexOfNextAdd++);
next.redo();
done = next == edit;
}
}
/** {@collect.stats}
* Convenience method that invokes one of <code>undo</code> or
* <code>redo</code>. If any edits have been undone (the index of
* the next edit is less than the length of the edits list) this
* invokes <code>redo</code>, otherwise it invokes <code>undo</code>.
*
* @see #canUndoOrRedo
* @see #getUndoOrRedoPresentationName
* @throws CannotUndoException if one of the edits throws
* <code>CannotUndoException</code>
* @throws CannotRedoException if one of the edits throws
* <code>CannotRedoException</code>
*/
public synchronized void undoOrRedo() throws CannotRedoException,
CannotUndoException {
if (indexOfNextAdd == edits.size()) {
undo();
} else {
redo();
}
}
/** {@collect.stats}
* Returns true if it is possible to invoke <code>undo</code> or
* <code>redo</code>.
*
* @return true if invoking <code>canUndoOrRedo</code> is valid
* @see #undoOrRedo
*/
public synchronized boolean canUndoOrRedo() {
if (indexOfNextAdd == edits.size()) {
return canUndo();
} else {
return canRedo();
}
}
/** {@collect.stats}
* Undoes the appropriate edits. If <code>end</code> has been
* invoked this calls through to the superclass, otherwise
* this invokes <code>undo</code> on all edits between the
* index of the next edit and the last significant edit, updating
* the index of the next edit appropriately.
*
* @throws CannotUndoException if one of the edits throws
* <code>CannotUndoException</code> or there are no edits
* to be undone
* @see CompoundEdit#end
* @see #canUndo
* @see #editToBeUndone
*/
public synchronized void undo() throws CannotUndoException {
if (inProgress) {
UndoableEdit edit = editToBeUndone();
if (edit == null) {
throw new CannotUndoException();
}
undoTo(edit);
} else {
super.undo();
}
}
/** {@collect.stats}
* Returns true if edits may be undone. If <code>end</code> has
* been invoked, this returns the value from super. Otherwise
* this returns true if there are any edits to be undone
* (<code>editToBeUndone</code> returns non-<code>null</code>).
*
* @return true if there are edits to be undone
* @see CompoundEdit#canUndo
* @see #editToBeUndone
*/
public synchronized boolean canUndo() {
if (inProgress) {
UndoableEdit edit = editToBeUndone();
return edit != null && edit.canUndo();
} else {
return super.canUndo();
}
}
/** {@collect.stats}
* Redoes the appropriate edits. If <code>end</code> has been
* invoked this calls through to the superclass. Otherwise
* this invokes <code>redo</code> on all edits between the
* index of the next edit and the next significant edit, updating
* the index of the next edit appropriately.
*
* @throws CannotRedoException if one of the edits throws
* <code>CannotRedoException</code> or there are no edits
* to be redone
* @see CompoundEdit#end
* @see #canRedo
* @see #editToBeRedone
*/
public synchronized void redo() throws CannotRedoException {
if (inProgress) {
UndoableEdit edit = editToBeRedone();
if (edit == null) {
throw new CannotRedoException();
}
redoTo(edit);
} else {
super.redo();
}
}
/** {@collect.stats}
* Returns true if edits may be redone. If <code>end</code> has
* been invoked, this returns the value from super. Otherwise,
* this returns true if there are any edits to be redone
* (<code>editToBeRedone</code> returns non-<code>null</code>).
*
* @return true if there are edits to be redone
* @see CompoundEdit#canRedo
* @see #editToBeRedone
*/
public synchronized boolean canRedo() {
if (inProgress) {
UndoableEdit edit = editToBeRedone();
return edit != null && edit.canRedo();
} else {
return super.canRedo();
}
}
/** {@collect.stats}
* Adds an <code>UndoableEdit</code> to this
* <code>UndoManager</code>, if it's possible. This removes all
* edits from the index of the next edit to the end of the edits
* list. If <code>end</code> has been invoked the edit is not added
* and <code>false</code> is returned. If <code>end</code> hasn't
* been invoked this returns <code>true</code>.
*
* @param anEdit the edit to be added
* @return true if <code>anEdit</code> can be incorporated into this
* edit
* @see CompoundEdit#end
* @see CompoundEdit#addEdit
*/
public synchronized boolean addEdit(UndoableEdit anEdit) {
boolean retVal;
// Trim from the indexOfNextAdd to the end, as we'll
// never reach these edits once the new one is added.
trimEdits(indexOfNextAdd, edits.size()-1);
retVal = super.addEdit(anEdit);
if (inProgress) {
retVal = true;
}
// Maybe super added this edit, maybe it didn't (perhaps
// an in progress compound edit took it instead. Or perhaps
// this UndoManager is no longer in progress). So make sure
// the indexOfNextAdd is pointed at the right place.
indexOfNextAdd = edits.size();
// Enforce the limit
trimForLimit();
return retVal;
}
/** {@collect.stats}
* Turns this <code>UndoManager</code> into a normal
* <code>CompoundEdit</code>. This removes all edits that have
* been undone.
*
* @see CompoundEdit#end
*/
public synchronized void end() {
super.end();
this.trimEdits(indexOfNextAdd, edits.size()-1);
}
/** {@collect.stats}
* Convenience method that returns either
* <code>getUndoPresentationName</code> or
* <code>getRedoPresentationName</code>. If the index of the next
* edit equals the size of the edits list,
* <code>getUndoPresentationName</code> is returned, otherwise
* <code>getRedoPresentationName</code> is returned.
*
* @return undo or redo name
*/
public synchronized String getUndoOrRedoPresentationName() {
if (indexOfNextAdd == edits.size()) {
return getUndoPresentationName();
} else {
return getRedoPresentationName();
}
}
/** {@collect.stats}
* Returns a description of the undoable form of this edit.
* If <code>end</code> has been invoked this calls into super.
* Otherwise if there are edits to be undone, this returns
* the value from the next significant edit that will be undone.
* If there are no edits to be undone and <code>end</code> has not
* been invoked this returns the value from the <code>UIManager</code>
* property "AbstractUndoableEdit.undoText".
*
* @return a description of the undoable form of this edit
* @see #undo
* @see CompoundEdit#getUndoPresentationName
*/
public synchronized String getUndoPresentationName() {
if (inProgress) {
if (canUndo()) {
return editToBeUndone().getUndoPresentationName();
} else {
return UIManager.getString("AbstractUndoableEdit.undoText");
}
} else {
return super.getUndoPresentationName();
}
}
/** {@collect.stats}
* Returns a description of the redoable form of this edit.
* If <code>end</code> has been invoked this calls into super.
* Otherwise if there are edits to be redone, this returns
* the value from the next significant edit that will be redone.
* If there are no edits to be redone and <code>end</code> has not
* been invoked this returns the value from the <code>UIManager</code>
* property "AbstractUndoableEdit.redoText".
*
* @return a description of the redoable form of this edit
* @see #redo
* @see CompoundEdit#getRedoPresentationName
*/
public synchronized String getRedoPresentationName() {
if (inProgress) {
if (canRedo()) {
return editToBeRedone().getRedoPresentationName();
} else {
return UIManager.getString("AbstractUndoableEdit.redoText");
}
} else {
return super.getRedoPresentationName();
}
}
/** {@collect.stats}
* An <code>UndoableEditListener</code> method. This invokes
* <code>addEdit</code> with <code>e.getEdit()</code>.
*
* @param e the <code>UndoableEditEvent</code> the
* <code>UndoableEditEvent</code> will be added from
* @see #addEdit
*/
public void undoableEditHappened(UndoableEditEvent e) {
addEdit(e.getEdit());
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public String toString() {
return super.toString() + " limit: " + limit +
" indexOfNextAdd: " + indexOfNextAdd;
}
}
|
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.undo;
import java.util.Hashtable;
/** {@collect.stats}
* StateEditable defines the interface for objects that can have
* their state undone/redone by a StateEdit.
*
* @see StateEdit
*/
public interface StateEditable {
/** {@collect.stats} Resource ID for this class. */
public static final String RCSID = "$Id: StateEditable.java,v 1.2 1997/09/08 19:39:08 marklin Exp $";
/** {@collect.stats}
* Upon receiving this message the receiver should place any relevant
* state into <EM>state</EM>.
*/
public void storeState(Hashtable<Object,Object> state);
/** {@collect.stats}
* Upon receiving this message the receiver should extract any relevant
* state out of <EM>state</EM>.
*/
public void restoreState(Hashtable<?,?> state);
} // End of interface StateEditable
|
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.undo;
import java.io.Serializable;
import javax.swing.UIManager;
/** {@collect.stats}
* An abstract implementation of <code>UndoableEdit</code>,
* implementing simple responses to all boolean methods in
* that interface.
*
* @author Ray Ryan
*/
public class AbstractUndoableEdit implements UndoableEdit, Serializable {
/** {@collect.stats}
* String returned by <code>getUndoPresentationName</code>;
* as of Java 2 platform v1.3.1 this field is no longer used. This value
* is now localized and comes from the defaults table with key
* <code>AbstractUndoableEdit.undoText</code>.
*
* @see javax.swing.UIDefaults
*/
protected static final String UndoName = "Undo";
/** {@collect.stats}
* String returned by <code>getRedoPresentationName</code>;
* as of Java 2 platform v1.3.1 this field is no longer used. This value
* is now localized and comes from the defaults table with key
* <code>AbstractUndoableEdit.redoText</code>.
*
* @see javax.swing.UIDefaults
*/
protected static final String RedoName = "Redo";
/** {@collect.stats}
* Defaults to true; becomes false if this edit is undone, true
* again if it is redone.
*/
boolean hasBeenDone;
/** {@collect.stats}
* True if this edit has not received <code>die</code>; defaults
* to <code>true</code>.
*/
boolean alive;
/** {@collect.stats}
* Creates an <code>AbstractUndoableEdit</code> which defaults
* <code>hasBeenDone</code> and <code>alive</code> to <code>true</code>.
*/
public AbstractUndoableEdit() {
super();
hasBeenDone = true;
alive = true;
}
/** {@collect.stats}
* Sets <code>alive</code> to false. Note that this
* is a one way operation; dead edits cannot be resurrected.
* Sending <code>undo</code> or <code>redo</code> to
* a dead edit results in an exception being thrown.
*
* <p>Typically an edit is killed when it is consolidated by
* another edit's <code>addEdit</code> or <code>replaceEdit</code>
* method, or when it is dequeued from an <code>UndoManager</code>.
*/
public void die() {
alive = false;
}
/** {@collect.stats}
* Throws <code>CannotUndoException</code> if <code>canUndo</code>
* returns <code>false</code>. Sets <code>hasBeenDone</code>
* to <code>false</code>. Subclasses should override to undo the
* operation represented by this edit. Override should begin with
* a call to super.
*
* @exception CannotUndoException if <code>canUndo</code>
* returns <code>false</code>
* @see #canUndo
*/
public void undo() throws CannotUndoException {
if (!canUndo()) {
throw new CannotUndoException();
}
hasBeenDone = false;
}
/** {@collect.stats}
* Returns true if this edit is <code>alive</code>
* and <code>hasBeenDone</code> is <code>true</code>.
*
* @return true if this edit is <code>alive</code>
* and <code>hasBeenDone</code> is <code>true</code>
*
* @see #die
* @see #undo
* @see #redo
*/
public boolean canUndo() {
return alive && hasBeenDone;
}
/** {@collect.stats}
* Throws <code>CannotRedoException</code> if <code>canRedo</code>
* returns false. Sets <code>hasBeenDone</code> to <code>true</code>.
* Subclasses should override to redo the operation represented by
* this edit. Override should begin with a call to super.
*
* @exception CannotRedoException if <code>canRedo</code>
* returns <code>false</code>
* @see #canRedo
*/
public void redo() throws CannotRedoException {
if (!canRedo()) {
throw new CannotRedoException();
}
hasBeenDone = true;
}
/** {@collect.stats}
* Returns <code>true</code> if this edit is <code>alive</code>
* and <code>hasBeenDone</code> is <code>false</code>.
*
* @return <code>true</code> if this edit is <code>alive</code>
* and <code>hasBeenDone</code> is <code>false</code>
* @see #die
* @see #undo
* @see #redo
*/
public boolean canRedo() {
return alive && !hasBeenDone;
}
/** {@collect.stats}
* This default implementation returns false.
*
* @param anEdit the edit to be added
* @return false
*
* @see UndoableEdit#addEdit
*/
public boolean addEdit(UndoableEdit anEdit) {
return false;
}
/** {@collect.stats}
* This default implementation returns false.
*
* @param anEdit the edit to replace
* @return false
*
* @see UndoableEdit#replaceEdit
*/
public boolean replaceEdit(UndoableEdit anEdit) {
return false;
}
/** {@collect.stats}
* This default implementation returns true.
*
* @return true
* @see UndoableEdit#isSignificant
*/
public boolean isSignificant() {
return true;
}
/** {@collect.stats}
* This default implementation returns "". Used by
* <code>getUndoPresentationName</code> and
* <code>getRedoPresentationName</code> to
* construct the strings they return. Subclasses should override to
* return an appropriate description of the operation this edit
* represents.
*
* @return the empty string ""
*
* @see #getUndoPresentationName
* @see #getRedoPresentationName
*/
public String getPresentationName() {
return "";
}
/** {@collect.stats}
* Retreives the value from the defaults table with key
* <code>AbstractUndoableEdit.undoText</code> and returns
* that value followed by a space, followed by
* <code>getPresentationName</code>.
* If <code>getPresentationName</code> returns "",
* then the defaults value is returned alone.
*
* @return the value from the defaults table with key
* <code>AbstractUndoableEdit.undoText</code>, followed
* by a space, followed by <code>getPresentationName</code>
* unless <code>getPresentationName</code> is "" in which
* case, the defaults value is returned alone.
* @see #getPresentationName
*/
public String getUndoPresentationName() {
String name = getPresentationName();
if (!"".equals(name)) {
name = UIManager.getString("AbstractUndoableEdit.undoText") +
" " + name;
} else {
name = UIManager.getString("AbstractUndoableEdit.undoText");
}
return name;
}
/** {@collect.stats}
* Retreives the value from the defaults table with key
* <code>AbstractUndoableEdit.redoText</code> and returns
* that value followed by a space, followed by
* <code>getPresentationName</code>.
* If <code>getPresentationName</code> returns "",
* then the defaults value is returned alone.
*
* @return the value from the defaults table with key
* <code>AbstractUndoableEdit.redoText</code>, followed
* by a space, followed by <code>getPresentationName</code>
* unless <code>getPresentationName</code> is "" in which
* case, the defaults value is returned alone.
* @see #getPresentationName
*/
public String getRedoPresentationName() {
String name = getPresentationName();
if (!"".equals(name)) {
name = UIManager.getString("AbstractUndoableEdit.redoText") +
" " + name;
} else {
name = UIManager.getString("AbstractUndoableEdit.redoText");
}
return name;
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public String toString()
{
return super.toString()
+ " hasBeenDone: " + hasBeenDone
+ " alive: " + alive;
}
}
|
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.undo;
/** {@collect.stats}
* Thrown when an UndoableEdit is told to <code>redo()</code> and can't.
* <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 CannotRedoException extends RuntimeException {
}
|
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.undo;
import javax.swing.event.*;
import java.util.*;
/** {@collect.stats}
* A support class used for managing <code>UndoableEdit</code> listeners.
*
* @author Ray Ryan
*/
public class UndoableEditSupport {
protected int updateLevel;
protected CompoundEdit compoundEdit;
protected Vector<UndoableEditListener> listeners;
protected Object realSource;
/** {@collect.stats}
* Constructs an <code>UndoableEditSupport</code> object.
*/
public UndoableEditSupport() {
this(null);
}
/** {@collect.stats}
* Constructs an <code>UndoableEditSupport</code> object.
*
* @param r an <code>Object</code>
*/
public UndoableEditSupport(Object r) {
realSource = r == null ? this : r;
updateLevel = 0;
compoundEdit = null;
listeners = new Vector<UndoableEditListener>();
}
/** {@collect.stats}
* Registers an <code>UndoableEditListener</code>.
* The listener is notified whenever an edit occurs which can be undone.
*
* @param l an <code>UndoableEditListener</code> object
* @see #removeUndoableEditListener
*/
public synchronized void addUndoableEditListener(UndoableEditListener l) {
listeners.addElement(l);
}
/** {@collect.stats}
* Removes an <code>UndoableEditListener</code>.
*
* @param l the <code>UndoableEditListener</code> object to be removed
* @see #addUndoableEditListener
*/
public synchronized void removeUndoableEditListener(UndoableEditListener l)
{
listeners.removeElement(l);
}
/** {@collect.stats}
* Returns an array of all the <code>UndoableEditListener</code>s added
* to this UndoableEditSupport with addUndoableEditListener().
*
* @return all of the <code>UndoableEditListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public synchronized UndoableEditListener[] getUndoableEditListeners() {
return (UndoableEditListener[])(listeners.toArray(
new UndoableEditListener[0]));
}
/** {@collect.stats}
* Called only from <code>postEdit</code> and <code>endUpdate</code>. Calls
* <code>undoableEditHappened</code> in all listeners. No synchronization
* is performed here, since the two calling methods are synchronized.
*/
protected void _postEdit(UndoableEdit e) {
UndoableEditEvent ev = new UndoableEditEvent(realSource, e);
Enumeration cursor = ((Vector)listeners.clone()).elements();
while (cursor.hasMoreElements()) {
((UndoableEditListener)cursor.nextElement()).
undoableEditHappened(ev);
}
}
/** {@collect.stats}
* DEADLOCK WARNING: Calling this method may call
* <code>undoableEditHappened</code> in all listeners.
* It is unwise to call this method from one of its listeners.
*/
public synchronized void postEdit(UndoableEdit e) {
if (updateLevel == 0) {
_postEdit(e);
} else {
// PENDING(rjrjr) Throw an exception if this fails?
compoundEdit.addEdit(e);
}
}
/** {@collect.stats}
* Returns the update level value.
*
* @return an integer representing the update level
*/
public int getUpdateLevel() {
return updateLevel;
}
/** {@collect.stats}
*
*/
public synchronized void beginUpdate() {
if (updateLevel == 0) {
compoundEdit = createCompoundEdit();
}
updateLevel++;
}
/** {@collect.stats}
* Called only from <code>beginUpdate</code>.
* Exposed here for subclasses' use.
*/
protected CompoundEdit createCompoundEdit() {
return new CompoundEdit();
}
/** {@collect.stats}
* DEADLOCK WARNING: Calling this method may call
* <code>undoableEditHappened</code> in all listeners.
* It is unwise to call this method from one of its listeners.
*/
public synchronized void endUpdate() {
updateLevel--;
if (updateLevel == 0) {
compoundEdit.end();
_postEdit(compoundEdit);
compoundEdit = null;
}
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a <code>String</code> representation of this object
*/
public String toString() {
return super.toString() +
" updateLevel: " + updateLevel +
" listeners: " + listeners +
" compoundEdit: " + compoundEdit;
}
}
|
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.undo;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/** {@collect.stats}
* <P>StateEdit is a general edit for objects that change state.
* Objects being edited must conform to the StateEditable interface.</P>
*
* <P>This edit class works by asking an object to store it's state in
* Hashtables before and after editing occurs. Upon undo or redo the
* object is told to restore it's state from these Hashtables.</P>
*
* A state edit is used as follows:
* <PRE>
* // Create the edit during the "before" state of the object
* StateEdit newEdit = new StateEdit(myObject);
* // Modify the object
* myObject.someStateModifyingMethod();
* // "end" the edit when you are done modifying the object
* newEdit.end();
* </PRE>
*
* <P><EM>Note that when a StateEdit ends, it removes redundant state from
* the Hashtables - A state Hashtable is not guaranteed to contain all
* keys/values placed into it when the state is stored!</EM></P>
*
* @see StateEditable
*
* @author Ray Ryan
*/
public class StateEdit
extends AbstractUndoableEdit {
protected static final String RCSID = "$Id: StateEdit.java,v 1.6 1997/10/01 20:05:51 sandipc Exp $";
//
// Attributes
//
/** {@collect.stats}
* The object being edited
*/
protected StateEditable object;
/** {@collect.stats}
* The state information prior to the edit
*/
protected Hashtable<Object,Object> preState;
/** {@collect.stats}
* The state information after the edit
*/
protected Hashtable<Object,Object> postState;
/** {@collect.stats}
* The undo/redo presentation name
*/
protected String undoRedoName;
//
// Constructors
//
/** {@collect.stats}
* Create and return a new StateEdit.
*
* @param anObject The object to watch for changing state
*
* @see StateEdit
*/
public StateEdit(StateEditable anObject) {
super();
init (anObject,null);
}
/** {@collect.stats}
* Create and return a new StateEdit with a presentation name.
*
* @param anObject The object to watch for changing state
* @param name The presentation name to be used for this edit
*
* @see StateEdit
*/
public StateEdit(StateEditable anObject, String name) {
super();
init (anObject,name);
}
protected void init (StateEditable anObject, String name) {
this.object = anObject;
this.preState = new Hashtable(11);
this.object.storeState(this.preState);
this.postState = null;
this.undoRedoName = name;
}
//
// Operation
//
/** {@collect.stats}
* Gets the post-edit state of the StateEditable object and
* ends the edit.
*/
public void end() {
this.postState = new Hashtable(11);
this.object.storeState(this.postState);
this.removeRedundantState();
}
/** {@collect.stats}
* Tells the edited object to apply the state prior to the edit
*/
public void undo() {
super.undo();
this.object.restoreState(preState);
}
/** {@collect.stats}
* Tells the edited object to apply the state after the edit
*/
public void redo() {
super.redo();
this.object.restoreState(postState);
}
/** {@collect.stats}
* Gets the presentation name for this edit
*/
public String getPresentationName() {
return this.undoRedoName;
}
//
// Internal support
//
/** {@collect.stats}
* Remove redundant key/values in state hashtables.
*/
protected void removeRedundantState() {
Vector uselessKeys = new Vector();
Enumeration myKeys = preState.keys();
// Locate redundant state
while (myKeys.hasMoreElements()) {
Object myKey = myKeys.nextElement();
if (postState.containsKey(myKey) &&
postState.get(myKey).equals(preState.get(myKey))) {
uselessKeys.addElement(myKey);
}
}
// Remove redundant state
for (int i = uselessKeys.size()-1; i >= 0; i--) {
Object myKey = uselessKeys.elementAt(i);
preState.remove(myKey);
postState.remove(myKey);
}
}
} // End of class StateEdit
|
Java
|
/*
* Copyright (c) 1999, 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.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.lang.ref.WeakReference;
import java.lang.ref.ReferenceQueue;
/** {@collect.stats}
* A package-private PropertyChangeListener which listens for
* property changes on an Action and updates the properties
* of an ActionEvent source.
* <p>
* Subclasses must override the actionPropertyChanged method,
* which is invoked from the propertyChange method as long as
* the target is still valid.
* </p>
* <p>
* WARNING WARNING WARNING WARNING WARNING WARNING:<br>
* Do NOT create an annonymous inner class that extends this! If you do
* a strong reference will be held to the containing class, which in most
* cases defeats the purpose of this class.
*
* @param T the type of JComponent the underlying Action is attached to
*
* @author Georges Saab
* @see AbstractButton
*/
abstract class ActionPropertyChangeListener<T extends JComponent>
implements PropertyChangeListener, Serializable {
private static ReferenceQueue<JComponent> queue;
// WeakReference's aren't serializable.
private transient OwnedWeakReference<T> target;
// The Component's that reference an Action do so through a strong
// reference, so that there is no need to check for serialized.
private Action action;
private static ReferenceQueue<JComponent> getQueue() {
synchronized(ActionPropertyChangeListener.class) {
if (queue == null) {
queue = new ReferenceQueue<JComponent>();
}
}
return queue;
}
public ActionPropertyChangeListener(T c, Action a) {
super();
setTarget(c);
this.action = a;
}
/** {@collect.stats}
* PropertyChangeListener method. If the target has been gc'ed this
* will remove the <code>PropertyChangeListener</code> from the Action,
* otherwise this will invoke actionPropertyChanged.
*/
public final void propertyChange(PropertyChangeEvent e) {
T target = getTarget();
if (target == null) {
getAction().removePropertyChangeListener(this);
} else {
actionPropertyChanged(target, getAction(), e);
}
}
/** {@collect.stats}
* Invoked when a property changes on the Action and the target
* still exists.
*/
protected abstract void actionPropertyChanged(T target, Action action,
PropertyChangeEvent e);
private void setTarget(T c) {
ReferenceQueue<JComponent> queue = getQueue();
// Check to see whether any old buttons have
// been enqueued for GC. If so, look up their
// PCL instance and remove it from its Action.
OwnedWeakReference r;
while ((r = (OwnedWeakReference)queue.poll()) != null) {
ActionPropertyChangeListener oldPCL = r.getOwner();
Action oldAction = oldPCL.getAction();
if (oldAction!=null) {
oldAction.removePropertyChangeListener(oldPCL);
}
}
this.target = new OwnedWeakReference<T>(c, queue, this);
}
public T getTarget() {
if (target == null) {
// Will only happen if serialized and real target was null
return null;
}
return this.target.get();
}
public Action getAction() {
return action;
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeObject(getTarget());
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
T target = (T)s.readObject();
if (target != null) {
setTarget(target);
}
}
private static class OwnedWeakReference<U extends JComponent> extends
WeakReference<U> {
private ActionPropertyChangeListener owner;
OwnedWeakReference(U target, ReferenceQueue<? super U> queue,
ActionPropertyChangeListener owner) {
super(target, queue);
this.owner = owner;
}
public ActionPropertyChangeListener getOwner() {
return owner;
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 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;
import java.awt.event.*;
import java.util.Vector;
import java.util.Enumeration;
import java.io.Serializable;
/** {@collect.stats}
* This class is used to create a multiple-exclusion scope for
* a set of buttons. Creating a set of buttons with the
* same <code>ButtonGroup</code> object means that
* turning "on" one of those buttons
* turns off all other buttons in the group.
* <p>
* A <code>ButtonGroup</code> can be used with
* any set of objects that inherit from <code>AbstractButton</code>.
* Typically a button group contains instances of
* <code>JRadioButton</code>,
* <code>JRadioButtonMenuItem</code>,
* or <code>JToggleButton</code>.
* It wouldn't make sense to put an instance of
* <code>JButton</code> or <code>JMenuItem</code>
* in a button group
* because <code>JButton</code> and <code>JMenuItem</code>
* don't implement the selected state.
* <p>
* Initially, all buttons in the group are unselected.
* <p>
* For examples and further information on using button groups see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/button.html#radiobutton">How to Use Radio Buttons</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 Jeff Dinkins
*/
public class ButtonGroup implements Serializable {
// the list of buttons participating in this group
protected Vector<AbstractButton> buttons = new Vector();
/** {@collect.stats}
* The current selection.
*/
ButtonModel selection = null;
/** {@collect.stats}
* Creates a new <code>ButtonGroup</code>.
*/
public ButtonGroup() {}
/** {@collect.stats}
* Adds the button to the group.
* @param b the button to be added
*/
public void add(AbstractButton b) {
if(b == null) {
return;
}
buttons.addElement(b);
if (b.isSelected()) {
if (selection == null) {
selection = b.getModel();
} else {
b.setSelected(false);
}
}
b.getModel().setGroup(this);
}
/** {@collect.stats}
* Removes the button from the group.
* @param b the button to be removed
*/
public void remove(AbstractButton b) {
if(b == null) {
return;
}
buttons.removeElement(b);
if(b.getModel() == selection) {
selection = null;
}
b.getModel().setGroup(null);
}
/** {@collect.stats}
* Clears the selection such that none of the buttons
* in the <code>ButtonGroup</code> are selected.
*
* @since 1.6
*/
public void clearSelection() {
if (selection != null) {
ButtonModel oldSelection = selection;
selection = null;
oldSelection.setSelected(false);
}
}
/** {@collect.stats}
* Returns all the buttons that are participating in
* this group.
* @return an <code>Enumeration</code> of the buttons in this group
*/
public Enumeration<AbstractButton> getElements() {
return buttons.elements();
}
/** {@collect.stats}
* Returns the model of the selected button.
* @return the selected button model
*/
public ButtonModel getSelection() {
return selection;
}
/** {@collect.stats}
* Sets the selected value for the <code>ButtonModel</code>.
* Only one button in the group may be selected at a time.
* @param m the <code>ButtonModel</code>
* @param b <code>true</code> if this button is to be
* selected, otherwise <code>false</code>
*/
public void setSelected(ButtonModel m, boolean b) {
if (b && m != null && m != selection) {
ButtonModel oldSelection = selection;
selection = m;
if (oldSelection != null) {
oldSelection.setSelected(false);
}
m.setSelected(true);
}
}
/** {@collect.stats}
* Returns whether a <code>ButtonModel</code> is selected.
* @return <code>true</code> if the button is selected,
* otherwise returns <code>false</code>
*/
public boolean isSelected(ButtonModel m) {
return (m == selection);
}
/** {@collect.stats}
* Returns the number of buttons in the group.
* @return the button count
* @since 1.3
*/
public int getButtonCount() {
if (buttons == null) {
return 0;
} else {
return buttons.size();
}
}
}
|
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;
/** {@collect.stats}
* Drop modes, used to determine the method by which a component
* tracks and indicates a drop location during drag and drop.
*
* @author Shannon Hickey
* @see JTable#setDropMode
* @see JList#setDropMode
* @see JTree#setDropMode
* @see javax.swing.text.JTextComponent#setDropMode
* @since 1.6
*/
public enum DropMode {
/** {@collect.stats}
* A component's own internal selection mechanism (or caret for text
* components) should be used to track the drop location.
*/
USE_SELECTION,
/** {@collect.stats}
* The drop location should be tracked in terms of the index of
* existing items. Useful for dropping on items in tables, lists,
* and trees.
*/
ON,
/** {@collect.stats}
* The drop location should be tracked in terms of the position
* where new data should be inserted. For components that manage
* a list of items (list and tree for example), the drop location
* should indicate the index where new data should be inserted.
* For text components the location should represent a position
* between characters. For components that manage tabular data
* (table for example), the drop location should indicate
* where to insert new rows, columns, or both, to accommodate
* the dropped data.
*/
INSERT,
/** {@collect.stats}
* The drop location should be tracked in terms of the row index
* where new rows should be inserted to accommodate the dropped
* data. This is useful for components that manage tabular data.
*/
INSERT_ROWS,
/** {@collect.stats}
* The drop location should be tracked in terms of the column index
* where new columns should be inserted to accommodate the dropped
* data. This is useful for components that manage tabular data.
*/
INSERT_COLS,
/** {@collect.stats}
* This mode is a combination of <code>ON</code>
* and <code>INSERT</code>, specifying that data can be
* dropped on existing items, or in insert locations
* as specified by <code>INSERT</code>.
*/
ON_OR_INSERT,
/** {@collect.stats}
* This mode is a combination of <code>ON</code>
* and <code>INSERT_ROWS</code>, specifying that data can be
* dropped on existing items, or as insert rows
* as specified by <code>INSERT_ROWS</code>.
*/
ON_OR_INSERT_ROWS,
/** {@collect.stats}
* This mode is a combination of <code>ON</code>
* and <code>INSERT_COLS</code>, specifying that data can be
* dropped on existing items, or as insert columns
* as specified by <code>INSERT_COLS</code>.
*/
ON_OR_INSERT_COLS
}
|
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.io.Serializable;
/** {@collect.stats}
* For the convenience of layout managers,
* calculates information about the size and position of components.
* All size and position calculation methods are class methods
* that take arrays of SizeRequirements as arguments.
* The SizeRequirements class supports two types of layout:
*
* <blockquote>
* <dl>
* <dt> tiled
* <dd> The components are placed end-to-end,
* starting either at coordinate 0 (the leftmost or topmost position)
* or at the coordinate representing the end of the allocated span
* (the rightmost or bottommost position).
*
* <dt> aligned
* <dd> The components are aligned as specified
* by each component's X or Y alignment value.
* </dl>
* </blockquote>
*
* <p>
*
* Each SizeRequirements object contains information
* about either the width (and X alignment)
* or height (and Y alignment)
* of a single component or a group of components:
*
* <blockquote>
* <dl>
* <dt> <code>minimum</code>
* <dd> The smallest reasonable width/height of the component
* or component group, in pixels.
*
* <dt> <code>preferred</code>
* <dd> The natural width/height of the component
* or component group, in pixels.
*
* <dt> <code>maximum</code>
* <dd> The largest reasonable width/height of the component
* or component group, in pixels.
*
* <dt> <code>alignment</code>
* <dd> The X/Y alignment of the component
* or component group.
* </dl>
* </blockquote>
* <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 Component#getMinimumSize
* @see Component#getPreferredSize
* @see Component#getMaximumSize
* @see Component#getAlignmentX
* @see Component#getAlignmentY
*
* @author Timothy Prinzing
*/
public class SizeRequirements implements Serializable {
/** {@collect.stats}
* The minimum size required.
* For a component <code>comp</code>, this should be equal to either
* <code>comp.getMinimumSize().width</code> or
* <code>comp.getMinimumSize().height</code>.
*/
public int minimum;
/** {@collect.stats}
* The preferred (natural) size.
* For a component <code>comp</code>, this should be equal to either
* <code>comp.getPreferredSize().width</code> or
* <code>comp.getPreferredSize().height</code>.
*/
public int preferred;
/** {@collect.stats}
* The maximum size allowed.
* For a component <code>comp</code>, this should be equal to either
* <code>comp.getMaximumSize().width</code> or
* <code>comp.getMaximumSize().height</code>.
*/
public int maximum;
/** {@collect.stats}
* The alignment, specified as a value between 0.0 and 1.0,
* inclusive.
* To specify centering, the alignment should be 0.5.
*/
public float alignment;
/** {@collect.stats}
* Creates a SizeRequirements object with the minimum, preferred,
* and maximum sizes set to zero and an alignment value of 0.5
* (centered).
*/
public SizeRequirements() {
minimum = 0;
preferred = 0;
maximum = 0;
alignment = 0.5f;
}
/** {@collect.stats}
* Creates a SizeRequirements object with the specified minimum, preferred,
* and maximum sizes and the specified alignment.
*
* @param min the minimum size >= 0
* @param pref the preferred size >= 0
* @param max the maximum size >= 0
* @param a the alignment >= 0.0f && <= 1.0f
*/
public SizeRequirements(int min, int pref, int max, float a) {
minimum = min;
preferred = pref;
maximum = max;
alignment = a > 1.0f ? 1.0f : a < 0.0f ? 0.0f : a;
}
/** {@collect.stats}
* Returns a string describing the minimum, preferred, and maximum
* size requirements, along with the alignment.
*
* @return the string
*/
public String toString() {
return "[" + minimum + "," + preferred + "," + maximum + "]@" + alignment;
}
/** {@collect.stats}
* Determines the total space necessary to
* place a set of components end-to-end. The needs
* of each component in the set are represented by an entry in the
* passed-in SizeRequirements array.
* The returned SizeRequirements object has an alignment of 0.5
* (centered). The space requirement is never more than
* Integer.MAX_VALUE.
*
* @param children the space requirements for a set of components.
* The vector may be of zero length, which will result in a
* default SizeRequirements object instance being passed back.
* @return the total space requirements.
*/
public static SizeRequirements getTiledSizeRequirements(SizeRequirements[]
children) {
SizeRequirements total = new SizeRequirements();
for (int i = 0; i < children.length; i++) {
SizeRequirements req = children[i];
total.minimum = (int) Math.min((long) total.minimum + (long) req.minimum, Integer.MAX_VALUE);
total.preferred = (int) Math.min((long) total.preferred + (long) req.preferred, Integer.MAX_VALUE);
total.maximum = (int) Math.min((long) total.maximum + (long) req.maximum, Integer.MAX_VALUE);
}
return total;
}
/** {@collect.stats}
* Determines the total space necessary to
* align a set of components. The needs
* of each component in the set are represented by an entry in the
* passed-in SizeRequirements array. The total space required will
* never be more than Integer.MAX_VALUE.
*
* @param children the set of child requirements. If of zero length,
* the returns result will be a default instance of SizeRequirements.
* @return the total space requirements.
*/
public static SizeRequirements getAlignedSizeRequirements(SizeRequirements[]
children) {
SizeRequirements totalAscent = new SizeRequirements();
SizeRequirements totalDescent = new SizeRequirements();
for (int i = 0; i < children.length; i++) {
SizeRequirements req = children[i];
int ascent = (int) (req.alignment * req.minimum);
int descent = req.minimum - ascent;
totalAscent.minimum = Math.max(ascent, totalAscent.minimum);
totalDescent.minimum = Math.max(descent, totalDescent.minimum);
ascent = (int) (req.alignment * req.preferred);
descent = req.preferred - ascent;
totalAscent.preferred = Math.max(ascent, totalAscent.preferred);
totalDescent.preferred = Math.max(descent, totalDescent.preferred);
ascent = (int) (req.alignment * req.maximum);
descent = req.maximum - ascent;
totalAscent.maximum = Math.max(ascent, totalAscent.maximum);
totalDescent.maximum = Math.max(descent, totalDescent.maximum);
}
int min = (int) Math.min((long) totalAscent.minimum + (long) totalDescent.minimum, Integer.MAX_VALUE);
int pref = (int) Math.min((long) totalAscent.preferred + (long) totalDescent.preferred, Integer.MAX_VALUE);
int max = (int) Math.min((long) totalAscent.maximum + (long) totalDescent.maximum, Integer.MAX_VALUE);
float alignment = 0.0f;
if (min > 0) {
alignment = (float) totalAscent.minimum / min;
alignment = alignment > 1.0f ? 1.0f : alignment < 0.0f ? 0.0f : alignment;
}
return new SizeRequirements(min, pref, max, alignment);
}
/** {@collect.stats}
* Creates a set of offset/span pairs representing how to
* lay out a set of components end-to-end.
* This method requires that you specify
* the total amount of space to be allocated,
* the size requirements for each component to be placed
* (specified as an array of SizeRequirements), and
* the total size requirement of the set of components.
* You can get the total size requirement
* by invoking the getTiledSizeRequirements method. The components
* will be tiled in the forward direction with offsets increasing from 0.
*
* @param allocated the total span to be allocated >= 0.
* @param total the total of the children requests. This argument
* is optional and may be null.
* @param children the size requirements for each component.
* @param offsets the offset from 0 for each child where
* the spans were allocated (determines placement of the span).
* @param spans the span allocated for each child to make the
* total target span.
*/
public static void calculateTiledPositions(int allocated,
SizeRequirements total,
SizeRequirements[] children,
int[] offsets,
int[] spans) {
calculateTiledPositions(allocated, total, children, offsets, spans, true);
}
/** {@collect.stats}
* Creates a set of offset/span pairs representing how to
* lay out a set of components end-to-end.
* This method requires that you specify
* the total amount of space to be allocated,
* the size requirements for each component to be placed
* (specified as an array of SizeRequirements), and
* the total size requirement of the set of components.
* You can get the total size requirement
* by invoking the getTiledSizeRequirements method.
*
* This method also requires a flag indicating whether components
* should be tiled in the forward direction (offsets increasing
* from 0) or reverse direction (offsets decreasing from the end
* of the allocated space). The forward direction represents
* components tiled from left to right or top to bottom. The
* reverse direction represents components tiled from right to left
* or bottom to top.
*
* @param allocated the total span to be allocated >= 0.
* @param total the total of the children requests. This argument
* is optional and may be null.
* @param children the size requirements for each component.
* @param offsets the offset from 0 for each child where
* the spans were allocated (determines placement of the span).
* @param spans the span allocated for each child to make the
* total target span.
* @param forward tile with offsets increasing from 0 if true
* and with offsets decreasing from the end of the allocated space
* if false.
* @since 1.4
*/
public static void calculateTiledPositions(int allocated,
SizeRequirements total,
SizeRequirements[] children,
int[] offsets,
int[] spans,
boolean forward) {
// The total argument turns out to be a bad idea since the
// total of all the children can overflow the integer used to
// hold the total. The total must therefore be calculated and
// stored in long variables.
long min = 0;
long pref = 0;
long max = 0;
for (int i = 0; i < children.length; i++) {
min += children[i].minimum;
pref += children[i].preferred;
max += children[i].maximum;
}
if (allocated >= pref) {
expandedTile(allocated, min, pref, max, children, offsets, spans, forward);
} else {
compressedTile(allocated, min, pref, max, children, offsets, spans, forward);
}
}
private static void compressedTile(int allocated, long min, long pref, long max,
SizeRequirements[] request,
int[] offsets, int[] spans,
boolean forward) {
// ---- determine what we have to work with ----
float totalPlay = Math.min(pref - allocated, pref - min);
float factor = (pref - min == 0) ? 0.0f : totalPlay / (pref - min);
// ---- make the adjustments ----
int totalOffset;
if( forward ) {
// lay out with offsets increasing from 0
totalOffset = 0;
for (int i = 0; i < spans.length; i++) {
offsets[i] = totalOffset;
SizeRequirements req = request[i];
float play = factor * (req.preferred - req.minimum);
spans[i] = (int)(req.preferred - play);
totalOffset = (int) Math.min((long) totalOffset + (long) spans[i], Integer.MAX_VALUE);
}
} else {
// lay out with offsets decreasing from the end of the allocation
totalOffset = allocated;
for (int i = 0; i < spans.length; i++) {
SizeRequirements req = request[i];
float play = factor * (req.preferred - req.minimum);
spans[i] = (int)(req.preferred - play);
offsets[i] = totalOffset - spans[i];
totalOffset = (int) Math.max((long) totalOffset - (long) spans[i], 0);
}
}
}
private static void expandedTile(int allocated, long min, long pref, long max,
SizeRequirements[] request,
int[] offsets, int[] spans,
boolean forward) {
// ---- determine what we have to work with ----
float totalPlay = Math.min(allocated - pref, max - pref);
float factor = (max - pref == 0) ? 0.0f : totalPlay / (max - pref);
// ---- make the adjustments ----
int totalOffset;
if( forward ) {
// lay out with offsets increasing from 0
totalOffset = 0;
for (int i = 0; i < spans.length; i++) {
offsets[i] = totalOffset;
SizeRequirements req = request[i];
int play = (int)(factor * (req.maximum - req.preferred));
spans[i] = (int) Math.min((long) req.preferred + (long) play, Integer.MAX_VALUE);
totalOffset = (int) Math.min((long) totalOffset + (long) spans[i], Integer.MAX_VALUE);
}
} else {
// lay out with offsets decreasing from the end of the allocation
totalOffset = allocated;
for (int i = 0; i < spans.length; i++) {
SizeRequirements req = request[i];
int play = (int)(factor * (req.maximum - req.preferred));
spans[i] = (int) Math.min((long) req.preferred + (long) play, Integer.MAX_VALUE);
offsets[i] = totalOffset - spans[i];
totalOffset = (int) Math.max((long) totalOffset - (long) spans[i], 0);
}
}
}
/** {@collect.stats}
* Creates a bunch of offset/span pairs specifying how to
* lay out a set of components with the specified alignments.
* The resulting span allocations will overlap, with each one
* fitting as well as possible into the given total allocation.
* This method requires that you specify
* the total amount of space to be allocated,
* the size requirements for each component to be placed
* (specified as an array of SizeRequirements), and
* the total size requirements of the set of components
* (only the alignment field of which is actually used).
* You can get the total size requirement by invoking
* getAlignedSizeRequirements.
*
* Normal alignment will be done with an alignment value of 0.0f
* representing the left/top edge of a component.
*
* @param allocated the total span to be allocated >= 0.
* @param total the total of the children requests.
* @param children the size requirements for each component.
* @param offsets the offset from 0 for each child where
* the spans were allocated (determines placement of the span).
* @param spans the span allocated for each child to make the
* total target span.
*/
public static void calculateAlignedPositions(int allocated,
SizeRequirements total,
SizeRequirements[] children,
int[] offsets,
int[] spans) {
calculateAlignedPositions( allocated, total, children, offsets, spans, true );
}
/** {@collect.stats}
* Creates a set of offset/span pairs specifying how to
* lay out a set of components with the specified alignments.
* The resulting span allocations will overlap, with each one
* fitting as well as possible into the given total allocation.
* This method requires that you specify
* the total amount of space to be allocated,
* the size requirements for each component to be placed
* (specified as an array of SizeRequirements), and
* the total size requirements of the set of components
* (only the alignment field of which is actually used)
* You can get the total size requirement by invoking
* getAlignedSizeRequirements.
*
* This method also requires a flag indicating whether normal or
* reverse alignment should be performed. With normal alignment
* the value 0.0f represents the left/top edge of the component
* to be aligned. With reverse alignment, 0.0f represents the
* right/bottom edge.
*
* @param allocated the total span to be allocated >= 0.
* @param total the total of the children requests.
* @param children the size requirements for each component.
* @param offsets the offset from 0 for each child where
* the spans were allocated (determines placement of the span).
* @param spans the span allocated for each child to make the
* total target span.
* @param normal when true, the alignment value 0.0f means
* left/top; when false, it means right/bottom.
* @since 1.4
*/
public static void calculateAlignedPositions(int allocated,
SizeRequirements total,
SizeRequirements[] children,
int[] offsets,
int[] spans,
boolean normal) {
float totalAlignment = normal ? total.alignment : 1.0f - total.alignment;
int totalAscent = (int)(allocated * totalAlignment);
int totalDescent = allocated - totalAscent;
for (int i = 0; i < children.length; i++) {
SizeRequirements req = children[i];
float alignment = normal ? req.alignment : 1.0f - req.alignment;
int maxAscent = (int)(req.maximum * alignment);
int maxDescent = req.maximum - maxAscent;
int ascent = Math.min(totalAscent, maxAscent);
int descent = Math.min(totalDescent, maxDescent);
offsets[i] = totalAscent - ascent;
spans[i] = (int) Math.min((long) ascent + (long) descent, Integer.MAX_VALUE);
}
}
// This method was used by the JTable - which now uses a different technique.
/** {@collect.stats}
* Adjust a specified array of sizes by a given amount.
*
* @param delta an int specifying the size difference
* @param children an array of SizeRequirements objects
* @return an array of ints containing the final size for each item
*/
public static int[] adjustSizes(int delta, SizeRequirements[] children) {
return new int[0];
}
}
|
Java
|
/*
* Copyright (c) 2000, 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.text;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
/** {@collect.stats}
* DateFormatter is an <code>InternationalFormatter</code> that does its
* formatting by way of an instance of <code>java.text.DateFormat</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}.
*
* @see java.text.DateFormat
*
* @since 1.4
*/
public class DateFormatter extends InternationalFormatter {
/** {@collect.stats}
* This is shorthand for
* <code>new DateFormatter(DateFormat.getDateInstance())</code>.
*/
public DateFormatter() {
this(DateFormat.getDateInstance());
}
/** {@collect.stats}
* Returns a DateFormatter configured with the specified
* <code>Format</code> instance.
*
* @param format Format used to dictate legal values
*/
public DateFormatter(DateFormat format) {
super(format);
setFormat(format);
}
/** {@collect.stats}
* Sets the format that dictates the legal values that can be edited
* and displayed.
* <p>
* If you have used the nullary constructor the value of this property
* will be determined for the current locale by way of the
* <code>Dateformat.getDateInstance()</code> method.
*
* @param format DateFormat instance used for converting from/to Strings
*/
public void setFormat(DateFormat format) {
super.setFormat(format);
}
/** {@collect.stats}
* Returns the Calendar that <code>DateFormat</code> is associated with,
* or if the <code>Format</code> is not a <code>DateFormat</code>
* <code>Calendar.getInstance</code> is returned.
*/
private Calendar getCalendar() {
Format f = getFormat();
if (f instanceof DateFormat) {
return ((DateFormat)f).getCalendar();
}
return Calendar.getInstance();
}
/** {@collect.stats}
* Returns true, as DateFormatterFilter will support
* incrementing/decrementing of the value.
*/
boolean getSupportsIncrement() {
return true;
}
/** {@collect.stats}
* Returns the field that will be adjusted by adjustValue.
*/
Object getAdjustField(int start, Map attributes) {
Iterator attrs = attributes.keySet().iterator();
while (attrs.hasNext()) {
Object key = attrs.next();
if ((key instanceof DateFormat.Field) &&
(key == DateFormat.Field.HOUR1 ||
((DateFormat.Field)key).getCalendarField() != -1)) {
return key;
}
}
return null;
}
/** {@collect.stats}
* Adjusts the Date if FieldPosition identifies a known calendar
* field.
*/
Object adjustValue(Object value, Map attributes, Object key,
int direction) throws
BadLocationException, ParseException {
if (key != null) {
int field;
// HOUR1 has no corresponding calendar field, thus, map
// it to HOUR0 which will give the correct behavior.
if (key == DateFormat.Field.HOUR1) {
key = DateFormat.Field.HOUR0;
}
field = ((DateFormat.Field)key).getCalendarField();
Calendar calendar = getCalendar();
if (calendar != null) {
calendar.setTime((Date)value);
int fieldValue = calendar.get(field);
try {
calendar.add(field, direction);
value = calendar.getTime();
} catch (Throwable th) {
value = null;
}
return value;
}
}
return null;
}
}
|
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.text;
import java.awt.event.ActionEvent;
import java.awt.KeyboardFocusManager;
import java.awt.Component;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.swing.Action;
import javax.swing.AbstractAction;
import javax.swing.KeyStroke;
/** {@collect.stats}
* An Action implementation useful for key bindings that are
* shared across a number of different text components. Because
* the action is shared, it must have a way of getting it's
* target to act upon. This class provides support to try and
* find a text component to operate on. The preferred way of
* getting the component to act upon is through the ActionEvent
* that is received. If the Object returned by getSource can
* be narrowed to a text component, it will be used. If the
* action event is null or can't be narrowed, the last focused
* text component is tried. This is determined by being
* used in conjunction with a JTextController which
* arranges to share that information with a TextAction.
* <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 TextAction extends AbstractAction {
/** {@collect.stats}
* Creates a new JTextAction object.
*
* @param name the name of the action
*/
public TextAction(String name) {
super(name);
}
/** {@collect.stats}
* Determines the component to use for the action.
* This if fetched from the source of the ActionEvent
* if it's not null and can be narrowed. Otherwise,
* the last focused component is used.
*
* @param e the ActionEvent
* @return the component
*/
protected final JTextComponent getTextComponent(ActionEvent e) {
if (e != null) {
Object o = e.getSource();
if (o instanceof JTextComponent) {
return (JTextComponent) o;
}
}
return getFocusedComponent();
}
/** {@collect.stats}
* Takes one list of
* commands and augments it with another list
* of commands. The second list takes precedence
* over the first list; that is, when both lists
* contain a command with the same name, the command
* from the second list is used.
*
* @param list1 the first list, may be empty but not
* <code>null</code>
* @param list2 the second list, may be empty but not
* <code>null</code>
* @return the augmented list
*/
public static final Action[] augmentList(Action[] list1, Action[] list2) {
Hashtable h = new Hashtable();
for (int i = 0; i < list1.length; i++) {
Action a = list1[i];
String value = (String)a.getValue(Action.NAME);
h.put((value!=null ? value:""), a);
}
for (int i = 0; i < list2.length; i++) {
Action a = list2[i];
String value = (String)a.getValue(Action.NAME);
h.put((value!=null ? value:""), a);
}
Action[] actions = new Action[h.size()];
int index = 0;
for (Enumeration e = h.elements() ; e.hasMoreElements() ;) {
actions[index++] = (Action) e.nextElement();
}
return actions;
}
/** {@collect.stats}
* Fetches the text component that currently has focus.
* This allows actions to be shared across text components
* which is useful for key-bindings where a large set of
* actions are defined, but generally used the same way
* across many different components.
*
* @return the component
*/
protected final JTextComponent getFocusedComponent() {
return JTextComponent.getFocusedComponent();
}
}
|
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.text;
import java.io.Serializable;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
/** {@collect.stats}
* An implementation of
* <code>JFormattedTextField.AbstractFormatterFactory</code>.
* <code>DefaultFormatterFactory</code> allows specifying a number of
* different <code>JFormattedTextField.AbstractFormatter</code>s that are to
* be used.
* The most important one is the default one
* (<code>setDefaultFormatter</code>). The default formatter will be used
* if a more specific formatter could not be found. The following process
* is used to determine the appropriate formatter to use.
* <ol>
* <li>Is the passed in value null? Use the null formatter.
* <li>Does the <code>JFormattedTextField</code> have focus? Use the edit
* formatter.
* <li>Otherwise, use the display formatter.
* <li>If a non-null <code>AbstractFormatter</code> has not been found, use
* the default formatter.
* </ol>
* <p>
* The following code shows how to configure a
* <code>JFormattedTextField</code> with two
* <code>JFormattedTextField.AbstractFormatter</code>s, one for display and
* one for editing.
* <pre>
* JFormattedTextField.AbstractFormatter editFormatter = ...;
* JFormattedTextField.AbstractFormatter displayFormatter = ...;
* DefaultFormatterFactory factory = new DefaultFormatterFactory(
* displayFormatter, displayFormatter, editFormatter);
* JFormattedTextField tf = new JFormattedTextField(factory);
* </pre>
* <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.JFormattedTextField
*
* @since 1.4
*/
public class DefaultFormatterFactory extends JFormattedTextField.AbstractFormatterFactory implements Serializable {
/** {@collect.stats}
* Default <code>AbstractFormatter</code> to use if a more specific one has
* not been specified.
*/
private JFormattedTextField.AbstractFormatter defaultFormat;
/** {@collect.stats}
* <code>JFormattedTextField.AbstractFormatter</code> to use for display.
*/
private JFormattedTextField.AbstractFormatter displayFormat;
/** {@collect.stats}
* <code>JFormattedTextField.AbstractFormatter</code> to use for editing.
*/
private JFormattedTextField.AbstractFormatter editFormat;
/** {@collect.stats}
* <code>JFormattedTextField.AbstractFormatter</code> to use if the value
* is null.
*/
private JFormattedTextField.AbstractFormatter nullFormat;
public DefaultFormatterFactory() {
}
/** {@collect.stats}
* Creates a <code>DefaultFormatterFactory</code> with the specified
* <code>JFormattedTextField.AbstractFormatter</code>.
*
* @param defaultFormat JFormattedTextField.AbstractFormatter to be used
* if a more specific
* JFormattedTextField.AbstractFormatter can not be
* found.
*/
public DefaultFormatterFactory(JFormattedTextField.
AbstractFormatter defaultFormat) {
this(defaultFormat, null);
}
/** {@collect.stats}
* Creates a <code>DefaultFormatterFactory</code> with the specified
* <code>JFormattedTextField.AbstractFormatter</code>s.
*
* @param defaultFormat JFormattedTextField.AbstractFormatter to be used
* if a more specific
* JFormattedTextField.AbstractFormatter can not be
* found.
* @param displayFormat JFormattedTextField.AbstractFormatter to be used
* when the JFormattedTextField does not have focus.
*/
public DefaultFormatterFactory(
JFormattedTextField.AbstractFormatter defaultFormat,
JFormattedTextField.AbstractFormatter displayFormat) {
this(defaultFormat, displayFormat, null);
}
/** {@collect.stats}
* Creates a DefaultFormatterFactory with the specified
* JFormattedTextField.AbstractFormatters.
*
* @param defaultFormat JFormattedTextField.AbstractFormatter to be used
* if a more specific
* JFormattedTextField.AbstractFormatter can not be
* found.
* @param displayFormat JFormattedTextField.AbstractFormatter to be used
* when the JFormattedTextField does not have focus.
* @param editFormat JFormattedTextField.AbstractFormatter to be used
* when the JFormattedTextField has focus.
*/
public DefaultFormatterFactory(
JFormattedTextField.AbstractFormatter defaultFormat,
JFormattedTextField.AbstractFormatter displayFormat,
JFormattedTextField.AbstractFormatter editFormat) {
this(defaultFormat, displayFormat, editFormat, null);
}
/** {@collect.stats}
* Creates a DefaultFormatterFactory with the specified
* JFormattedTextField.AbstractFormatters.
*
* @param defaultFormat JFormattedTextField.AbstractFormatter to be used
* if a more specific
* JFormattedTextField.AbstractFormatter can not be
* found.
* @param displayFormat JFormattedTextField.AbstractFormatter to be used
* when the JFormattedTextField does not have focus.
* @param editFormat JFormattedTextField.AbstractFormatter to be used
* when the JFormattedTextField has focus.
* @param nullFormat JFormattedTextField.AbstractFormatter to be used
* when the JFormattedTextField has a null value.
*/
public DefaultFormatterFactory(
JFormattedTextField.AbstractFormatter defaultFormat,
JFormattedTextField.AbstractFormatter displayFormat,
JFormattedTextField.AbstractFormatter editFormat,
JFormattedTextField.AbstractFormatter nullFormat) {
this.defaultFormat = defaultFormat;
this.displayFormat = displayFormat;
this.editFormat = editFormat;
this.nullFormat = nullFormat;
}
/** {@collect.stats}
* Sets the <code>JFormattedTextField.AbstractFormatter</code> to use as
* a last resort, eg in case a display, edit or null
* <code>JFormattedTextField.AbstractFormatter</code> has not been
* specified.
*
* @param atf JFormattedTextField.AbstractFormatter used if a more
* specific is not specified
*/
public void setDefaultFormatter(JFormattedTextField.AbstractFormatter atf){
defaultFormat = atf;
}
/** {@collect.stats}
* Returns the <code>JFormattedTextField.AbstractFormatter</code> to use
* as a last resort, eg in case a display, edit or null
* <code>JFormattedTextField.AbstractFormatter</code>
* has not been specified.
*
* @return JFormattedTextField.AbstractFormatter used if a more specific
* one is not specified.
*/
public JFormattedTextField.AbstractFormatter getDefaultFormatter() {
return defaultFormat;
}
/** {@collect.stats}
* Sets the <code>JFormattedTextField.AbstractFormatter</code> to use if
* the <code>JFormattedTextField</code> is not being edited and either
* the value is not-null, or the value is null and a null formatter has
* has not been specified.
*
* @param atf JFormattedTextField.AbstractFormatter to use when the
* JFormattedTextField does not have focus
*/
public void setDisplayFormatter(JFormattedTextField.AbstractFormatter atf){
displayFormat = atf;
}
/** {@collect.stats}
* Returns the <code>JFormattedTextField.AbstractFormatter</code> to use
* if the <code>JFormattedTextField</code> is not being edited and either
* the value is not-null, or the value is null and a null formatter has
* has not been specified.
*
* @return JFormattedTextField.AbstractFormatter to use when the
* JFormattedTextField does not have focus
*/
public JFormattedTextField.AbstractFormatter getDisplayFormatter() {
return displayFormat;
}
/** {@collect.stats}
* Sets the <code>JFormattedTextField.AbstractFormatter</code> to use if
* the <code>JFormattedTextField</code> is being edited and either
* the value is not-null, or the value is null and a null formatter has
* has not been specified.
*
* @param atf JFormattedTextField.AbstractFormatter to use when the
* component has focus
*/
public void setEditFormatter(JFormattedTextField.AbstractFormatter atf) {
editFormat = atf;
}
/** {@collect.stats}
* Returns the <code>JFormattedTextField.AbstractFormatter</code> to use
* if the <code>JFormattedTextField</code> is being edited and either
* the value is not-null, or the value is null and a null formatter has
* has not been specified.
*
* @return JFormattedTextField.AbstractFormatter to use when the
* component has focus
*/
public JFormattedTextField.AbstractFormatter getEditFormatter() {
return editFormat;
}
/** {@collect.stats}
* Sets the formatter to use if the value of the JFormattedTextField is
* null.
*
* @param atf JFormattedTextField.AbstractFormatter to use when
* the value of the JFormattedTextField is null.
*/
public void setNullFormatter(JFormattedTextField.AbstractFormatter atf) {
nullFormat = atf;
}
/** {@collect.stats}
* Returns the formatter to use if the value is null.
*
* @return JFormattedTextField.AbstractFormatter to use when the value is
* null
*/
public JFormattedTextField.AbstractFormatter getNullFormatter() {
return nullFormat;
}
/** {@collect.stats}
* Returns either the default formatter, display formatter, editor
* formatter or null formatter based on the state of the
* JFormattedTextField.
*
* @param source JFormattedTextField requesting
* JFormattedTextField.AbstractFormatter
* @return JFormattedTextField.AbstractFormatter to handle
* formatting duties.
*/
public JFormattedTextField.AbstractFormatter getFormatter(
JFormattedTextField source) {
JFormattedTextField.AbstractFormatter format = null;
if (source == null) {
return null;
}
Object value = source.getValue();
if (value == null) {
format = getNullFormatter();
}
if (format == null) {
if (source.hasFocus()) {
format = getEditFormatter();
}
else {
format = getDisplayFormatter();
}
if (format == null) {
format = getDefaultFormatter();
}
}
return format;
}
}
|
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.text;
import java.util.Enumeration;
/** {@collect.stats}
* A collection of unique attributes. This is a read-only,
* immutable interface. An attribute is basically a key and
* a value assigned to the key. The collection may represent
* something like a style run, a logical style, etc. These
* are generally used to describe features that will contribute
* to some graphical representation such as a font. The
* set of possible keys is unbounded and can be anything.
* Typically View implementations will respond to attribute
* definitions and render something to represent the attributes.
* <p>
* Attributes can potentially resolve in a hierarchy. If a
* key doesn't resolve locally, and a resolving parent
* exists, the key will be resolved through the parent.
*
* @author Timothy Prinzing
* @see MutableAttributeSet
*/
public interface AttributeSet {
/** {@collect.stats}
* This interface is the type signature that is expected
* to be present on any attribute key that contributes to
* the determination of what font to use to render some
* text. This is not considered to be a closed set, the
* definition can change across version of the platform and can
* be amended by additional user added entries that
* correspond to logical settings that are specific to
* some type of content.
*/
public interface FontAttribute {
}
/** {@collect.stats}
* This interface is the type signature that is expected
* to be present on any attribute key that contributes to
* presentation of color.
*/
public interface ColorAttribute {
}
/** {@collect.stats}
* This interface is the type signature that is expected
* to be present on any attribute key that contributes to
* character level presentation. This would be any attribute
* that applies to a so-called <term>run</term> of
* style.
*/
public interface CharacterAttribute {
}
/** {@collect.stats}
* This interface is the type signature that is expected
* to be present on any attribute key that contributes to
* the paragraph level presentation.
*/
public interface ParagraphAttribute {
}
/** {@collect.stats}
* Returns the number of attributes that are defined locally in this set.
* Attributes that are defined in the parent set are not included.
*
* @return the number of attributes >= 0
*/
public int getAttributeCount();
/** {@collect.stats}
* Checks whether the named attribute has a value specified in
* the set without resolving through another attribute
* set.
*
* @param attrName the attribute name
* @return true if the attribute has a value specified
*/
public boolean isDefined(Object attrName);
/** {@collect.stats}
* Determines if the two attribute sets are equivalent.
*
* @param attr an attribute set
* @return true if the sets are equivalent
*/
public boolean isEqual(AttributeSet attr);
/** {@collect.stats}
* Returns an attribute set that is guaranteed not
* to change over time.
*
* @return a copy of the attribute set
*/
public AttributeSet copyAttributes();
/** {@collect.stats}
* Fetches the value of the given attribute. If the value is not found
* locally, the search is continued upward through the resolving
* parent (if one exists) until the value is either
* found or there are no more parents. If the value is not found,
* null is returned.
*
* @param key the non-null key of the attribute binding
* @return the value of the attribute, or {@code null} if not found
*/
public Object getAttribute(Object key);
/** {@collect.stats}
* Returns an enumeration over the names of the attributes that are
* defined locally in the set. Names of attributes defined in the
* resolving parent, if any, are not included. The values of the
* <code>Enumeration</code> may be anything and are not constrained to
* a particular <code>Object</code> type.
* <p>
* This method never returns {@code null}. For a set with no attributes, it
* returns an empty {@code Enumeration}.
*
* @return the names
*/
public Enumeration<?> getAttributeNames();
/** {@collect.stats}
* Returns {@code true} if this set defines an attribute with the same
* name and an equal value. If such an attribute is not found locally,
* it is searched through in the resolving parent hierarchy.
*
* @param name the non-null attribute name
* @param value the value
* @return {@code true} if the set defines the attribute with an
* equal value, either locally or through its resolving parent
* @throws NullPointerException if either {@code name} or
* {@code value} is {@code null}
*/
public boolean containsAttribute(Object name, Object value);
/** {@collect.stats}
* Returns {@code true} if this set defines all the attributes from the
* given set with equal values. If an attribute is not found locally,
* it is searched through in the resolving parent hierarchy.
*
* @param attributes the set of attributes to check against
* @return {@code true} if this set defines all the attributes with equal
* values, either locally or through its resolving parent
* @throws NullPointerException if {@code attributes} is {@code null}
*/
public boolean containsAttributes(AttributeSet attributes);
/** {@collect.stats}
* Gets the resolving parent.
*
* @return the parent
*/
public AttributeSet getResolveParent();
/** {@collect.stats}
* Attribute name used to name the collection of
* attributes.
*/
public static final Object NameAttribute = StyleConstants.NameAttribute;
/** {@collect.stats}
* Attribute name used to identify the resolving parent
* set of attributes, if one is defined.
*/
public static final Object ResolveAttribute = StyleConstants.ResolveAttribute;
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.