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.netbeans.editor.ext.java;

import java.awt.Dialog;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.TreeSet;
import javax.swing.ListCellRenderer;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.netbeans.editor.BaseDocument;
import org.netbeans.editor.DialogSupport;
import org.netbeans.editor.LocaleSupport;
import org.netbeans.editor.SettingsUtil;
import org.netbeans.editor.Utilities;
import org.netbeans.editor.ext.ExtSettingsDefaults;
import org.netbeans.editor.ext.ExtSettingsNames;
import org.netbeans.editor.ext.ListCompletionView;


/**
 *
 * @author Miloslav Metelka
 * @version 1.0
 */

abstract public class JavaFastImport implements ActionListener {
    
    public static final int IMPORT_CLASS = 0;
    public static final int IMPORT_PACKAGE = 1;
    public static final int IMPORT_FQN = 2;
    
    protected JTextComponent target;
    
    private String exp;
    
    private JavaFastImportPanel panel;
    
    private ListCellRenderer cellRenderer;
    
    private JList resultList;
    
    private Dialog dialog;
    
    private JButton[] buttons;
    
    private int[] block;
    
    private int importType;

    public JavaFastImport(JTextComponent target) {
        this.target = target;

        try{
            block = Utilities.getIdentifierBlock (target, target.getCaret().getDot());
            javax.swing.text.Document doc = target.getDocument();
            exp = (block != null) ? doc.getText(block[0], block[1] - block[0]) : null;
        }catch(BadLocationException ble){
            ble.printStackTrace();
        }
        
        importType = getPackageImportSetting();
        
        // Bugfix for #26966
        if (exp != null) {
          // Eliminating extra spaces
          String untrimmedExp = exp;
          exp = exp.trim();

          // Recalculating block beginning and ending
          int nLeadingSpaces = untrimmedExp.indexOf(exp);
          int nTrailingSpaces = untrimmedExp.length() - exp.length() - nLeadingSpaces;
          block[0] += nLeadingSpaces;
          block[1] -= nTrailingSpaces;
        }
    }
    
    
    private int getPackageImportSetting(){
        Class kitClass = Utilities.getKitClass(target);
        if (kitClass != null) {
            return SettingsUtil.getInteger(kitClass,
                ExtSettingsNames.FAST_IMPORT_SELECTION,
                ExtSettingsDefaults.defaultFastImportSelection);
        }
        return ExtSettingsDefaults.defaultFastImportSelection.intValue();
    }
    
    
    public void setDialogVisible(boolean visible) {
        List result = null;
        if (visible) {
            result = evaluate();
            if (result == null || result.size() == 0) { // no data
                return;
            }
            populate(result);
        }
        
        if (dialog == null) {
            dialog = createDialog();
        }
        

        getResultList().requestFocus();
        dialog.setVisible(visible);
        if (visible) {
            getPanel().popupNotify();

        } else {
            dialog.dispose();
        }
    }
    
    /** 
     * Checks whether class is already imported
     * @param cls JCClass
     **/
    protected boolean isAlreadyImported(JCClass cls){
        BaseDocument doc = Utilities.getDocument(target);
        if (doc == null) return false;
        JavaSyntaxSupport sup = (JavaSyntaxSupport)doc.getSyntaxSupport().get(JavaSyntaxSupport.class);
        if (sup == null) return false;
        sup.refreshJavaImport();
        return sup.isImported(cls);
    }
    
    protected void updateImport(Object item) {
    }
    
    protected ListCellRenderer createCellRenderer() {
        JCCellRenderer rr = new JCCellRenderer();
        //rr.setClassDisplayFullName(true);
        //rr.setPackageLastNameOnly(false);
        return rr;
    }
    
    protected JList createResultList() {
        JList list = new ListCompletionView(getCellRenderer());
        list.addMouseListener(new MouseAdapter() {
             public void mouseClicked(MouseEvent e) {
                 if (e.getClickCount() == 2) {
                     actionPerformed(new ActionEvent(getButtons()[0], 0, ""));
                 }
             }
        });
        return list;
    }
    
    private JButton[] getButtons() {
        if (buttons == null) {
            buttons = new JButton[] {
                new JButton(LocaleSupport.getString("JFI_import", "Import")),  //NOI18N
                new JButton(LocaleSupport.getString("JFI_cancelButton", "Cancel")) // NOI18N
            };
            buttons[0].getAccessibleContext().setAccessibleDescription(LocaleSupport.getString("ACSD_JFI_import")); // NOI18N
            buttons[1].getAccessibleContext().setAccessibleDescription(LocaleSupport.getString("ACSD_JFI_cancelButton")); // NOI18N
        }
        
        return buttons;
    }
    
    private Dialog createDialog() {
        String title = LocaleSupport.getString("JFI_title", "Import Class"); //NOI18N

        Dialog dialog = DialogSupport.createDialog(title,
            getPanel(), true, getButtons(), false, 0, 1, this);
        
        dialog.addWindowListener(new WindowAdapter(){
            public void windowClosed(WindowEvent evt) {
                Utilities.returnFocus();
            }
        });
        return dialog;
    }
    
    private JavaFastImportPanel getPanel() {
        if (panel == null) {
            panel = new JavaFastImportPanel(this, importType);
        }
        return panel;
    }
    
    ListCellRenderer getCellRenderer() {
        if (cellRenderer == null) {
            cellRenderer = createCellRenderer();
        }
        return cellRenderer;
    }
    
    JList getResultList() {
        if (resultList == null) {
            resultList = createResultList();
        }
        return resultList;
    }
    
    protected abstract List findClasses(String exp, int importType);

    List evaluate() {
       return (exp != null && exp.length() > 0) ? findClasses(exp, getPanel().getImportType()) : null;
    }

    void populate(List result) {
        if (result != null) {
            if (getResultList() instanceof ListCompletionView) {
                ((ListCompletionView)getResultList()).setResult(result);
            }
        }
    }
    
    protected void setFastImportSettings(int importType){
    }

    protected String getItemFQN(Object item) {
        if (item instanceof JCClass)
            return ((JCClass)item).getFullName();
        if (item instanceof JCResultItem)
            return ((JCResultItem)item).getItemText();
        return item.toString ();
    }

    public void actionPerformed(ActionEvent evt) {
        Object src = evt.getSource();

        if (src == buttons[0]) { // Open button
            int selIndex;
            int importType = getPanel ().getImportType ();
            switch (importType) {
            case IMPORT_CLASS: 
            case IMPORT_PACKAGE: 
                selIndex = getResultList().getSelectedIndex();
                if (selIndex >= 0) {
                    updateImport(getResultList().getModel().getElementAt(selIndex));
                }
                break;
            case IMPORT_FQN:
                selIndex = getResultList().getSelectedIndex();
                if (selIndex < 0) {
                    return;
                }
                Object item = getResultList().getModel().getElementAt(selIndex);
                String clsName = getItemFQN(item);

                try {
                    Document document = target.getDocument();
                    if (document instanceof BaseDocument){
                        BaseDocument doc = (BaseDocument) document;
                        try {
                            doc.atomicLock();
                            try {
                                doc.remove (block[0], block[1] - block[0]);
                                doc.insertString (block[0], clsName, null);
                                target.getCaret().setDot(block[0] + clsName.length());
                            } finally {
                                doc.atomicUnlock();
                            }
                        } catch( BadLocationException ble ) {
                        }
                    }else{
                        document.remove (block[0], block[1] - block[0]);
                        document.insertString (block[0], clsName, null);
                        target.getCaret().setDot(block[0] + clsName.length());
                    }
                } catch (BadLocationException ex) {
                    throw new IllegalStateException ();
                }
                break;
            }
            
            setFastImportSettings(importType);
            setDialogVisible(false);
            
        } else if (src == buttons[buttons.length - 1]) { // Close button
            setDialogVisible(false);
        }
    }
    
}
... 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.