alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.openide.explorer.propertysheet.editors;

import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.*;
import java.net.URL;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.border.*;

import org.openide.*;
import org.openide.loaders.*;
import org.openide.nodes.*;
import org.openide.util.HelpCtx;
import org.openide.explorer.propertysheet.editors.EnhancedCustomPropertyEditor;
import org.openide.explorer.propertysheet.*;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileStateInvalidException;
import org.openide.filesystems.Repository;
import org.openide.util.Lookup;

/**
* PropertyEditor for Icons. Depends on existing DataObject for images.
* Images must be represented by some DataObject which returns itselv
* as cookie, and has image file as a primary file. File extensions
* for images is specified in isImage method.
*
* @author Jan Jancura
*/
public class IconEditor extends PropertyEditorSupport implements PropertyEditor, XMLPropertyEditor, ExPropertyEditor {

    public static final int TYPE_URL = 1;
    public static final int TYPE_FILE = 2;
    public static final int TYPE_CLASSPATH = 3;

    static final String URL_PREFIX = "URL"; // NOI18N
    static final String FILE_PREFIX = "File"; // NOI18N
    static final String CLASSPATH_PREFIX = "Classpath"; // NOI18N

    private static String getString(String key) {
        return org.openide.util.NbBundle.getBundle(IconEditor.class).getString(key);
    }

    public static boolean isImage(String s) {
        s = s.toLowerCase();
        return s.endsWith(".jpg") || s.endsWith(".gif") || // NOI18N
               s.endsWith(".jpeg") || s.endsWith(".jpe") || // NOI18N
               s.equals("jpg") || s.equals("gif") || // NOI18N
               s.equals("jpeg") || s.equals("jpe"); // NOI18N
    }

    static String convert(String s) {
        StringTokenizer st = new StringTokenizer(s, "\\"); // NOI18N
        StringBuffer sb = new StringBuffer();
        if (st.hasMoreElements()) {
            sb.append(st.nextElement());
            while (st.hasMoreElements())
                sb.append("\\\\").append(st.nextElement()); // NOI18N
        }
        return new String(sb);
    }


    // variables .................................................................................

    private Icon icon;
    private PropertyEnv propertyEnv;

    // init .......................................................................................

    public IconEditor() {
    }

    // Special access methods......................................................................

    /** @return the type of image source - one of TYPE_CLASSPATH, TYPE_FILE, TYPE_URL */
    public int getSourceType() {
        if (getValue() instanceof NbImageIcon)
            return ((NbImageIcon)getValue()).type;
        else
            return TYPE_FILE;
    }

    /** @return the name of image's source - depending on the type it can be a URL, file name or
    * resource path to the image on classpath */
    public String getSourceName() {
        if (getValue() instanceof NbImageIcon)
            return ((NbImageIcon)getValue()).name;
        else
            return null;
    }

    // PropertyEditor methods .....................................................................

    /**
    * @return The value of the property.  Builtin types such as "int" will
    * be wrapped as the corresponding object type such as "java.lang.Integer".
    */
    public Object getValue() {
        return super.getValue();
    }

    /**
    * Set (or change) the object that is to be edited.  Builtin types such
    * as "int" must be wrapped as the corresponding object type such as
    * "java.lang.Integer".
    *
    * @param object The new target object to be edited.  Note that this
    *     object should not be modified by the PropertyEditor, rather
    *     the PropertyEditor should create a new object to hold any
    *     modified value.
    */
    public void setValue(Object object) {
        if (propertyEnv != null) {
            if ( object == null || ((object instanceof NbImageIcon) && ((NbImageIcon)object).stateValid) ) {
                propertyEnv.setState(PropertyEnv.STATE_VALID);
            } else {
                propertyEnv.setState(PropertyEnv.STATE_INVALID);
            }
        } 
        
        icon = (Icon) object;
        super.setValue(icon);
    }

    /**
    * @return The property value as a human editable string.
    * 

Returns null if the value can't be expressed as an editable string. *

If a non-null value is returned, then the PropertyEditor should * be prepared to parse that string back in setAsText(). */ public String getAsText() { Object val = getValue(); if (val == null) return "null"; // NOI18N if (val instanceof NbImageIcon) { NbImageIcon ii = (NbImageIcon)val; switch (ii.type) { case TYPE_URL: return URL_PREFIX + ": " + ii.name; // NOI18N case TYPE_FILE: return FILE_PREFIX + ": " + ii.name; // NOI18N case TYPE_CLASSPATH: return CLASSPATH_PREFIX + ": " + ii.name; // NOI18N } } return null; } /** * Set the property value by parsing a given String. May raise * java.lang.IllegalArgumentException if either the String is * badly formatted or if this kind of property can't be expressed * as text. * @param string The string to be parsed. */ public void setAsText(String string) throws IllegalArgumentException { setValue(iconFromText(string)); } // XXX CLASSPATH API VIOLATION!!! private static URL findResource(String resource) { FileObject fo = Repository.getDefault().findResource(resource); if (fo == null) { return null; } else { try { return fo.getURL(); } catch (FileStateInvalidException fsie) { ErrorManager.getDefault().notify(fsie); return null; } } } private NbImageIcon iconFromText(String string) throws IllegalArgumentException { NbImageIcon ii; try { if (string.startsWith(FILE_PREFIX)) { String s = string.substring(FILE_PREFIX.length() + 1).trim(); ii = new NbImageIcon(s); ii.type = TYPE_FILE; ii.name = s; } else if (string.startsWith(CLASSPATH_PREFIX)) { String s = string.substring(CLASSPATH_PREFIX.length() + 1).trim(); if((s == null)|| ("".equals(s)) || ("/".equals(s)) // NOI18N || ("///".equals(s)) || (s.endsWith("#"))) { // NOI18N // #13035 // the empty string and couple of others has to be treated specially // since TopManager.getDefault().currentClassLoader().getResource(s); // is able to return non null value for the . And that // wrong non-null value causes problems in new NbImageIcon(...) return null; } URL u = findResource(s); // XXX CLASSPATH API VIOLATION! if (u == null) ii = new NbImageIcon(); else ii = new NbImageIcon(u); ii.type = TYPE_CLASSPATH; ii.name = s; } else if (string.startsWith(URL_PREFIX)) { String s = string.substring(URL_PREFIX.length() + 1).trim(); URL url = new URL(s); ii = new NbImageIcon(url); ii.type = TYPE_URL; ii.name = s; } else if (string.equals("null")) { // NOI18N ii = null; } else { ii = new NbImageIcon(string.trim()); ii.type = TYPE_FILE; ii.name = string; } } catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException(); ErrorManager.getDefault().annotate(iae, e); throw iae; } return ii; } /** * This method is intended for use when generating Java code to set * the value of the property. It should return a fragment of Java code * that can be used to initialize a variable with the current property * value. *

* Example results are "2", "new Color(127,127,34)", "Color.orange", etc. * * @return A fragment of Java code representing an initializer for the * current value. */ public String getJavaInitializationString() { if (getValue() instanceof NbImageIcon) { NbImageIcon ii = (NbImageIcon)getValue(); switch (ii.type) { case TYPE_URL: return "new javax.swing.JLabel() {\n" + // NOI18N " public javax.swing.Icon getIcon() {\n" + // NOI18N " try {\n" + // NOI18N " return new javax.swing.ImageIcon(\n" + // NOI18N " new java.net.URL(\"" + convert(ii.name) + "\")\n" + // NOI18N " );\n" + // NOI18N " } catch (java.net.MalformedURLException e) {\n" + // NOI18N " }\n" + // NOI18N " return null;\n" + // NOI18N " }\n" + // NOI18N "}.getIcon()"; // NOI18N case TYPE_FILE: return "new javax.swing.ImageIcon(\"" + convert(ii.name) + "\")"; // NOI18N case TYPE_CLASSPATH: return "new javax.swing.ImageIcon(getClass().getResource(\"" + convert(ii.name) + "\"))"; // NOI18N } } return "null"; // NOI18N } /** * If the property value must be one of a set of known tagged values, * then this method should return an array of the tags. This can * be used to represent (for example) enum values. If a PropertyEditor * supports tags, then it should support the use of setAsText with * a tag value as a way of setting the value and the use of getAsText * to identify the current value. * * @return The tag values for this property. May be null if this * property cannot be represented as a tagged value. * */ public String[] getTags() { return null; } /** * @return True if the class will honor the paintValue method. */ public boolean isPaintable() { return false; } /** * Paint a representation of the value into a given area of screen * real estate. Note that the propertyEditor is responsible for doing * its own clipping so that it fits into the given rectangle. *

* If the PropertyEditor doesn't honor paint requests (see isPaintable) * this method should be a silent noop. *

* The given Graphics object will have the default font, color, etc of * the parent container. The PropertyEditor may change graphics attributes * such as font and color and doesn't need to restore the old values. * * @param g Graphics object to paint into. * @param rectangle Rectangle within graphics object into which we should paint. */ public void paintValue(Graphics g, Rectangle rectangle) { } /** * @return True if the propertyEditor can provide a custom editor. */ public boolean supportsCustomEditor() { return true; } /** * A PropertyEditor may choose to make available a full custom Component * that edits its property value. It is the responsibility of the * PropertyEditor to hook itself up to its editor Component itself and * to report property value changes by firing a PropertyChange event. *

* The higher-level code that calls getCustomEditor may either embed * the Component in some larger property sheet, or it may put it in * its own individual dialog, or ... * * @return A java.awt.Component that will allow a human to directly * edit the current property value. May be null if this is * not supported. */ public java.awt.Component getCustomEditor() { return new IconPanel(); } // innerclasses ............................................................... public static class NbImageIcon extends ImageIcon implements Externalizable { /** generated Serialized Version UID */ static final long serialVersionUID = 7018807466471349466L; int type; String name; boolean stateValid; public NbImageIcon() { super(""); stateValid = false; } NbImageIcon(URL url) { super(url); type = TYPE_URL; stateValid = true; } NbImageIcon(String file) { super(file); type = TYPE_FILE; stateValid = true; } String getName() { return name; } public void writeExternal(ObjectOutput oo) throws IOException { oo.writeObject(new Integer(type)); oo.writeObject(name); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { type = ((Integer)in.readObject()).intValue(); name = (String) in.readObject(); ImageIcon ii = null; switch (type) { case TYPE_URL: try { ii = new ImageIcon(new URL(name)); } catch (java.net.MalformedURLException e) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); return; } break; case TYPE_FILE: ii = new ImageIcon(name); break; case TYPE_CLASSPATH: ii = new ImageIcon(findResource(name)); break; } setImage(ii.getImage()); } } class IconPanel extends javax.swing.JPanel implements EnhancedCustomPropertyEditor { static final long serialVersionUID = -6904264999063788703L; private javax.swing.JPanel jPanel1; private javax.swing.JLabel jLabel1; private javax.swing.JRadioButton rbUrl; private javax.swing.JRadioButton rbFile; private javax.swing.JRadioButton rbClasspath; private javax.swing.JRadioButton rbNoPicture; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel2; private javax.swing.JLabel lName; private javax.swing.JTextField tfName; private javax.swing.JButton bSelect; private javax.swing.JPanel jPanel3; private javax.swing.JLabel jLabel7; private javax.swing.JScrollPane spImage; private javax.swing.JLabel iconLabel; // ====================================== private Icon localIcon; /** Creates new form IconPanel */ public IconPanel() { iconLabel = new JLabel() { public boolean isFocusTraversable() { return true; } }; iconLabel.setPreferredSize(new java.awt.Dimension(32, 32)); iconLabel.setHorizontalAlignment( SwingConstants.CENTER ); iconLabel.setVerticalAlignment( SwingConstants.CENTER ); initComponents(); spImage.setViewportView(iconLabel); jLabel1.setText(getString("CTL_ImageSourceType")); rbUrl.setText(getString("CTL_URL")); rbFile.setText(getString("CTL_File")); rbClasspath.setText(getString("CTL_Classpath")); rbNoPicture.setText(getString("CTL_NoPicture")); jLabel2.setText(getString("CTL_URLExample")); jLabel3.setText(getString("CTL_FileExample")); jLabel4.setText(getString("CTL_ClasspathExample")); jLabel5.setText(getString("CTL_Null")); lName.setText(getString("CTL_ImageSourceName")); lName.setDisplayedMnemonic(getString("CTL_ImageSourceName_mnemonic").charAt(0)); lName.setLabelFor(tfName); jLabel7.setText(getString("CTL_Preview")); jLabel7.setDisplayedMnemonic(getString("CTL_Preview_mnemonic").charAt(0)); bSelect.setText(getString("CTL_ButtonSelect")); bSelect.setMnemonic(getString("CTL_ButtonSelect_mnemonic").charAt(0)); jLabel1.setLabelFor(jPanel1); jLabel2.setLabelFor(rbUrl); jLabel3.setLabelFor(rbFile); jLabel4.setLabelFor(rbClasspath); jLabel5.setLabelFor(rbNoPicture); jLabel7.setLabelFor(iconLabel); rbUrl.setMnemonic(getString("CTL_URL_mnemonic").charAt(0)); rbFile.setMnemonic(getString("CTL_File_mnemonic").charAt(0)); rbClasspath.setMnemonic(getString("CTL_Classpath_mnemonic").charAt(0)); rbNoPicture.setMnemonic(getString("CTL_NoPicture_mnemonic").charAt(0)); tfName.getAccessibleContext().setAccessibleDescription(getString("ACSD_CTL_ImageSourceName")); bSelect.getAccessibleContext().setAccessibleDescription(getString("ACSD_CTL_ButtonSelect")); iconLabel.getAccessibleContext().setAccessibleDescription(getString("ACSD_CTL_Preview")); rbUrl.getAccessibleContext().setAccessibleDescription(jLabel2.getText()); rbFile.getAccessibleContext().setAccessibleDescription(jLabel3.getText()); rbClasspath.getAccessibleContext().setAccessibleDescription(jLabel4.getText()); rbNoPicture.getAccessibleContext().setAccessibleDescription(jLabel5.getText()); getAccessibleContext().setAccessibleDescription(getString("ACSD_IconCustomEditor")); ButtonGroup bg = new ButtonGroup(); bg.add(rbUrl); bg.add(rbFile); bg.add(rbClasspath); bg.add(rbNoPicture); localIcon = (Icon)getValue(); if (propertyEnv != null) propertyEnv.setState(PropertyEnv.STATE_NEEDS_VALIDATION); if (localIcon == null || !(localIcon instanceof NbImageIcon)) { rbNoPicture.setSelected(true); bSelect.setEnabled(false); tfName.setEnabled(false); return; } switch (((NbImageIcon)localIcon).type) { case TYPE_URL: rbUrl.setSelected(true); bSelect.setEnabled(false); break; case TYPE_FILE: rbFile.setSelected(true); bSelect.setEnabled(true); break; case TYPE_CLASSPATH: rbClasspath.setSelected(true); bSelect.setEnabled(true); break; } tfName.setText(((NbImageIcon)localIcon).name); HelpCtx.setHelpIDString(this, "gui.csh.icon"); // NOI18N updateIcon(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); rbUrl = new javax.swing.JRadioButton(); rbFile = new javax.swing.JRadioButton(); rbClasspath = new javax.swing.JRadioButton(); rbNoPicture = new javax.swing.JRadioButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); lName = new javax.swing.JLabel(); tfName = new javax.swing.JTextField(); bSelect = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); spImage = new javax.swing.JScrollPane(); setLayout(new java.awt.GridBagLayout()); java.awt.GridBagConstraints gridBagConstraints2; jPanel1.setLayout(new java.awt.GridBagLayout()); java.awt.GridBagConstraints gridBagConstraints1; gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.insets = new java.awt.Insets(12, 12, 0, 0); gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST; jPanel1.add(jLabel1, gridBagConstraints1); gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.gridx = 0; gridBagConstraints1.gridy = 1; gridBagConstraints1.insets = new java.awt.Insets(12, 24, 0, 0); gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST; jPanel1.add(rbUrl, gridBagConstraints1); gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.gridx = 0; gridBagConstraints1.gridy = 2; gridBagConstraints1.insets = new java.awt.Insets(0, 24, 0, 0); gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST; jPanel1.add(rbFile, gridBagConstraints1); gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.gridx = 0; gridBagConstraints1.gridy = 3; gridBagConstraints1.insets = new java.awt.Insets(0, 24, 0, 0); gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST; jPanel1.add(rbClasspath, gridBagConstraints1); gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.gridx = 0; gridBagConstraints1.gridy = 4; gridBagConstraints1.insets = new java.awt.Insets(0, 24, 0, 0); gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST; jPanel1.add(rbNoPicture, gridBagConstraints1); gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.gridx = 1; gridBagConstraints1.gridy = 1; gridBagConstraints1.insets = new java.awt.Insets(12, 5, 0, 12); gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST; jPanel1.add(jLabel2, gridBagConstraints1); gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.gridx = 1; gridBagConstraints1.gridy = 2; gridBagConstraints1.insets = new java.awt.Insets(5, 5, 0, 12); gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST; jPanel1.add(jLabel3, gridBagConstraints1); gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.gridx = 1; gridBagConstraints1.gridy = 3; gridBagConstraints1.insets = new java.awt.Insets(5, 5, 0, 12); gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST; jPanel1.add(jLabel4, gridBagConstraints1); gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.gridx = 1; gridBagConstraints1.gridy = 4; gridBagConstraints1.insets = new java.awt.Insets(5, 5, 0, 12); gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints1.weightx = 1.0; gridBagConstraints1.weighty = 1.0; jPanel1.add(jLabel5, gridBagConstraints1); gridBagConstraints2 = new java.awt.GridBagConstraints(); gridBagConstraints2.fill = java.awt.GridBagConstraints.BOTH; add(jPanel1, gridBagConstraints2); jPanel2.setLayout(new java.awt.GridBagLayout()); java.awt.GridBagConstraints gridBagConstraints3; gridBagConstraints3 = new java.awt.GridBagConstraints(); gridBagConstraints3.insets = new java.awt.Insets(12, 12, 0, 0); gridBagConstraints3.anchor = java.awt.GridBagConstraints.WEST; jPanel2.add(lName, gridBagConstraints3); gridBagConstraints3 = new java.awt.GridBagConstraints(); gridBagConstraints3.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints3.insets = new java.awt.Insets(12, 5, 0, 0); gridBagConstraints3.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints3.weightx = 1.0; jPanel2.add(tfName, gridBagConstraints3); gridBagConstraints3 = new java.awt.GridBagConstraints(); gridBagConstraints3.insets = new java.awt.Insets(12, 5, 0, 17); gridBagConstraints3.anchor = java.awt.GridBagConstraints.WEST; jPanel2.add(bSelect, gridBagConstraints3); gridBagConstraints2 = new java.awt.GridBagConstraints(); gridBagConstraints2.gridx = 0; gridBagConstraints2.gridy = 1; gridBagConstraints2.fill = java.awt.GridBagConstraints.BOTH; add(jPanel2, gridBagConstraints2); jPanel3.setLayout(new java.awt.GridBagLayout()); java.awt.GridBagConstraints gridBagConstraints4; gridBagConstraints4 = new java.awt.GridBagConstraints(); gridBagConstraints4.insets = new java.awt.Insets(12, 12, 0, 0); gridBagConstraints4.anchor = java.awt.GridBagConstraints.WEST; jPanel3.add(jLabel7, gridBagConstraints4); gridBagConstraints4 = new java.awt.GridBagConstraints(); gridBagConstraints4.gridx = 0; gridBagConstraints4.gridy = 1; gridBagConstraints4.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints4.insets = new java.awt.Insets(5, 12, 0, 12); gridBagConstraints4.weightx = 1.0; gridBagConstraints4.weighty = 1.0; jPanel3.add(spImage, gridBagConstraints4); gridBagConstraints2 = new java.awt.GridBagConstraints(); gridBagConstraints2.gridx = 0; gridBagConstraints2.gridy = 2; gridBagConstraints2.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints2.weightx = 1.0; gridBagConstraints2.weighty = 1.0; add(jPanel3, gridBagConstraints2); // listeners ................................................. tfName.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setValue(); } }); rbUrl.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bSelect.setEnabled(false); tfName.setEnabled(true); setValue(); } }); rbFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bSelect.setEnabled(true); tfName.setEnabled(true); setValue(); updateIcon(); } }); rbClasspath.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bSelect.setEnabled(true); tfName.setEnabled(true); setValue(); } }); rbNoPicture.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bSelect.setEnabled(false); tfName.setEnabled(false); localIcon = null; updateIcon(); } }); bSelect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(rbFile.isSelected()) { File f = selectFile(); if (f == null) { return; } tfName.setText(f.getAbsolutePath()); setValue(); } else if (rbClasspath.isSelected()) { // InputPanel ip = new InputPanel(); Places places = (Places)Lookup.getDefault().lookup(Places.class); Node ds = places.nodes().repository(new DataFilter() { public boolean acceptDataObject(DataObject obj) { // accept only data folders but ignore read only roots of file systems if (obj instanceof DataFolder) return !obj.getPrimaryFile().isReadOnly() || obj.getPrimaryFile().getParent() != null; return isImage(obj.getPrimaryFile().getExt()); } }); String name; try { // selects one folder from data systems DataObject d = (DataObject) NodeOperation.getDefault().select( getString("CTL_OpenDialogName"), getString("CTL_FileSystemName"), ((Places)Lookup.getDefault().lookup(Places.class)).nodes().repository(), new NodeAcceptor() { public boolean acceptNodes(Node[] nodes) { if ((nodes == null) || (nodes.length != 1)) return false; return nodes[0].getCookie(DataFolder.class) == null; } }, null )[0].getCookie(DataObject.class); name = (d.getPrimaryFile().getPath()); } catch (org.openide.util.UserCancelException ex) { return; } tfName.setText("/" + name); // NOI18N setValue(); } } }); } /** Presents the user with the file chooser type dialog * @returns the file selected of null */ private File selectFile() { final File[] ff = new File[1]; final FeatureDescriptor fd = new FeatureDescriptor(); ExPropertyModel epm = new ExPropertyModel() { public void setValue(Object val) { ff[0] = (File)val; } public Object getValue() { return ff[0]; } public Class getPropertyType() { return File.class; } public Class getPropertyEditorClass() { return null; } public void addPropertyChangeListener(PropertyChangeListener l) { } public void removePropertyChangeListener(PropertyChangeListener l) { } public Object[] getBeans() { return new Object[0]; } public FeatureDescriptor getFeatureDescriptor() { return fd; } }; FileFilter filter = new FileFilter() { public boolean accept(java.io.File f) { return isImage(f.getName()) || f.isDirectory(); } public String getDescription() { return getString("CTL_ImagesExtensionName"); } }; fd.setValue("directories", Boolean.FALSE); // NOI18N fd.setValue("files", Boolean.TRUE); // NOI18N fd.setValue("filter", filter); // NOI18N PropertyPanel panel = new PropertyPanel(epm, PropertyPanel.PREF_CUSTOM_EDITOR); // NOI18N DialogDescriptor dd = new DialogDescriptor(panel, getString("CTL_OpenDialogName"), true, null); dd.setHelpCtx(new HelpCtx("csh.openimage")); // NOI18N Object res = DialogDisplayer.getDefault().notify(dd); if (res == DialogDescriptor.OK_OPTION) { return ff[0]; } else { return null; } } /** * @return Returns the property value that is result of the CustomPropertyEditor. * @exception InvalidStateException when the custom property editor does not * represent valid property value (and thus it should not be set) */ public Object getPropertyValue() throws IllegalStateException { NbImageIcon ii = null; String s = tfName.getText().trim(); if ((s == null)|| ("".equals(s)) || ("/".equals(s)) || // NOI18N ("///".equals(s)) || (s.endsWith("#"))) { // NOI18N // #13035 // the empty string and couple of others has to be treated specially // since TopManager.getDefault().currentClassLoader().getResource(s); // is able to return non null value for the . And that // wrong non-null value causes problems in new NbImageIcon(...) return null; } try { if (rbFile.isSelected()) { ii = new NbImageIcon(s); ii.type = TYPE_FILE; ii.name = s; } else if (rbClasspath.isSelected()) { URL url = findResource(s); ii = new NbImageIcon(url); ii.type = TYPE_CLASSPATH; ii.name = s; } else if (rbUrl.isSelected()) { URL url = new URL(s); ii = new NbImageIcon(url); ii.type = TYPE_URL; ii.name = s; } } catch (Exception e) { IllegalStateException ise = new IllegalStateException(e.toString()); ErrorManager.getDefault().annotate(ise, ErrorManager.USER, getString("MSG_IllegalValue"), getString("MSG_IllegalValue"), null, new java.util.Date()); throw ise; } return ii; } void updateIcon() { IconEditor.this.setValue(localIcon); iconLabel.setIcon(localIcon); iconLabel.setEnabled(localIcon != null); validate(); } void setValue() { String val = tfName.getText(); val.trim(); if ("".equals(val)) { // NOI18N localIcon = null; updateIcon(); return; } String pref = ""; // NOI18N if (rbUrl.isSelected()) pref = URL_PREFIX + ": "; // NOI18N else if (rbFile.isSelected()) pref = FILE_PREFIX + ": "; // NOI18N else if (rbClasspath.isSelected()) pref = CLASSPATH_PREFIX + ": "; // NOI18N try { localIcon = iconFromText(pref + val); } catch (IllegalArgumentException ee) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ee); localIcon = null; } updateIcon(); } } // end of IconPanel //-------------------------------------------------------------------------- // XMLPropertyEditor implementation public static final String XML_IMAGE = "Image"; // NOI18N public static final String ATTR_TYPE = "iconType"; // NOI18N public static final String ATTR_NAME = "name"; // NOI18N /** Called to load property value from specified XML subtree. If succesfully loaded, * the value should be available via the getValue method. * An IOException should be thrown when the value cannot be restored from the specified XML element * @param element the XML DOM element representing a subtree of XML from which the value should be loaded * @exception IOException thrown when the value cannot be restored from the specified XML element */ public void readFromXML(org.w3c.dom.Node element) throws java.io.IOException { if (!XML_IMAGE.equals(element.getNodeName())) { throw new java.io.IOException(); } org.w3c.dom.NamedNodeMap attributes = element.getAttributes(); try { int type = Integer.parseInt(attributes.getNamedItem(ATTR_TYPE).getNodeValue()); String name = attributes.getNamedItem(ATTR_NAME).getNodeValue(); switch (type) { case 0: setValue(null); break; case TYPE_URL: setAsText(URL_PREFIX + ": " + name); break; // NOI18N case TYPE_FILE: setAsText(FILE_PREFIX + ": " + name); break; // NOI18N case TYPE_CLASSPATH: setAsText(CLASSPATH_PREFIX + ": " + name); break; // NOI18N } } catch (NullPointerException e) { java.io.IOException ioe = new java.io.IOException(); ErrorManager.getDefault().annotate(ioe, e); throw ioe; } } /** Called to store current property value into XML subtree. The property value should be set using the * setValue method prior to calling this method. * @param doc The XML document to store the XML in - should be used for creating nodes only * @return the XML DOM element representing a subtree of XML from which the value should be loaded */ public org.w3c.dom.Node storeToXML(org.w3c.dom.Document doc) { org.w3c.dom.Element el = doc.createElement(XML_IMAGE); if (getValue() instanceof NbImageIcon) { NbImageIcon ii = (NbImageIcon)getValue(); el.setAttribute(ATTR_TYPE, Integer.toString(ii.type)); el.setAttribute(ATTR_NAME, ii.name); } else { el.setAttribute(ATTR_TYPE, "0"); // NOI18N el.setAttribute(ATTR_NAME, "null"); // NOI18N } return el; } // ======================================= // ExPropertyEditor implementation /** * This method is called by the IDE to pass * the environment to the property editor. */ public void attachEnv(PropertyEnv env) { propertyEnv = env; } }

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.