Package DisplayProject.controls

Source Code of DisplayProject.controls.ScrollList$ScrollListCellRenderer$DashedLineBorder

/*
Copyright (c) 2003-2008 ITerative Consulting Pty Ltd. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

o Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
 
o Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
   
o This jcTOOL Helper Class software, whether in binary or source form may not be used within,
or to derive, any other product without the specific prior written permission of the copyright holder

 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/
package DisplayProject.controls;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.border.AbstractBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionListener;

import DisplayProject.Constants;
import DisplayProject.ListField;
import DisplayProject.ScrollListModel;
import DisplayProject.UIutils;
import DisplayProject.factory.ListFieldFactory;
import Framework.Array_Of_ListElement;
import Framework.CloneHelper;
import Framework.ListElement;
import Framework.TextData;
/**
* The ScrollList class defines a scroll list, a fixed group of choices (list elements) in a scrolling vertical display from which a user makes one selection.
*/
@SuppressWarnings("serial")
public class ScrollList extends JList implements ListField, ListDataListener {
  private int widthForData = 0;
    /**
     * Cache the fixed row height. A value of -1 implies that it is not set yet.
     */
    private int rowHeight = -1// DET-135
 
    public ScrollList() {
        super();
        setSelectionModel(createSelectionModel());
        //PM: 17/8/07 addMouseListener(new ForteMouseAdapter());
        this.setCellRenderer(new ScrollListCellRenderer());
      // TF:15/12/2009:DET-141:Set this up to allow inheriting of popup menu
      this.setInheritsPopupMenu(true);
    }

    @Override
    public void setVisibleRowCount(int visibleRowCount) {
      // TF:14/10/2009:Added this to allow a list view to be dynamically resized in height
      super.setVisibleRowCount(visibleRowCount);
      Component comp = this;
     
      if (comp.getParent() instanceof JViewport && comp.getParent().getParent() instanceof JScrollPane) {
        comp = comp.getParent().getParent();
      }
     
      if (comp instanceof JComponent) {
        int height = UIutils.rowsToPixels(visibleRowCount, this);
        Dimension d = new Dimension(comp.getWidth(), height);
        Dimension minD = new Dimension(comp.getMinimumSize().width, height);
       
        comp.setSize(d);
       
        ((JComponent)comp).setMinimumSize(minD);
        ((JComponent)comp).setPreferredSize(d);
      }
    }
    @Override
    public void setFont(Font font) {
      super.setFont(font);
      // Clear the rowHeight cache
      this.rowHeight = -1;
      // Set the fixed cell height for this font. Necessary to fire the correct property change event
      this.setFixedCellHeight(this.getFixedCellHeight());
    }
   
    @Override
    public int getFixedCellHeight() {
      if (rowHeight == -1) {
        FontMetrics fm = this.getFontMetrics(this.getFont());
        this.rowHeight = fm.getHeight() + 1;
      }
      return this.rowHeight;
    }
   
    /**
     * Implement a custom cell renderer to make the scroll list look a lot more like the forte one, especially
     * when it is disabled. Also provides a margin to move the text off the very left hand edge
     * @author Tim Faulkes
     *
     */
    class ScrollListCellRenderer extends JLabel implements ListCellRenderer, PropertyChangeListener
    {
        private boolean drawGradient = false;

        public ScrollListCellRenderer() {
            super();
            setOpaque( true );
            // Pull the component off the left hand edge a little bit
            setFont(ScrollList.this.getFont());
            ScrollList.this.addPropertyChangeListener("font", this);
        }

        /**
         * Create a dashed border class for the selected item
         * @author Tim
         *
         */
        private class DashedLineBorder extends AbstractBorder {
          private BasicStroke stroke = new BasicStroke(1, BasicStroke.CAP_BUTT,
              BasicStroke.JOIN_BEVEL, 1, new
              float[]{2, 2}, 0);
          private Insets insets;
          private Color colour;
         
          public DashedLineBorder(int top, int left, int bottom, int right, Color colour ) {
            this.insets = new Insets(top, left, bottom, right);
            this.colour = colour;
      }
         
          public void paintBorder(Component c, Graphics g, int x, int y, int
              width, int height) {
            Graphics2D g2d = (Graphics2D)g.create();
            g2d.setStroke(stroke);
            g2d.setColor(colour);
            g2d.drawRect(x, y, width-1, height-1);
            g2d.dispose();
          }
          @Override
          public Insets getBorderInsets(Component c) {
            return new Insets(insets.top, insets.left, insets.bottom, insets.right);
          }
          @Override
          public Insets getBorderInsets(Component c, Insets insets) {
            insets.top = this.insets.top;
            insets.bottom = this.insets.bottom;
            insets.left = this.insets.left;
            insets.right = this.insets.right;
            return insets;
          }
        }
       
        public Component getListCellRendererComponent(JList list,
                                Object value,
                                int index,
                                boolean isSelected,
                                boolean cellHasFocus)
        {
            setText(value.toString());

            if (isSelected) {
                    setBackground(list.getSelectionBackground());
                    setForeground(list.getSelectionForeground());
            } else {
                    setBackground(list.getBackground());
                    setForeground(list.getForeground());
            }

            if (cellHasFocus) {
                // setBorder(BorderFactory.createMatteBorder(1,3,1,1,Color.lightGray));
                setBorder(new DashedLineBorder(1,3,1,1,Color.lightGray));
            }
            else {
                setBorder(new EmptyBorder(1,3,0,0));
            }
            return this;
        }

        protected void paintComponent(Graphics g) {
            if (drawGradient) {
                Graphics2D gfx = (Graphics2D)g.create();
                GradientPaint gradient = new GradientPaint(0,0, Color.BLUE, 0,10,Color.BLACK);
                gfx.setPaint(gradient);
                gfx.fillRect(0,0,getWidth(),getHeight());
                gfx.dispose();
            }
            super.paintComponent(g);
            }  


        /* (non-Javadoc)
         * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
         */
        public void propertyChange(PropertyChangeEvent pEvt) {
            if (pEvt.getPropertyName().equalsIgnoreCase("font")) {
                this.setFont((Font)pEvt.getNewValue());
            }
        }
    }

    public TextData getTextValue() {
        if (getModel() instanceof ScrollListModel) {
            return ((ScrollListModel)getModel()).getTextValue();
        }
        else {
            return null;
        }
    }

    public void setTextValue(TextData value) {
        if (getModel() instanceof ScrollListModel) {
            ((ScrollListModel)getModel()).setTextValue(value);
        }
    }
   
    //PM:14/3/08 properties for binding the text value
    public void setText(String value){
      this.setTextValue(new TextData(value));
    }
    //PM:14/3/08 properties for binding the text value
    public String getText(){
      return getTextValue().toString();
    }

    // TF:19/07/2009:Cleaned this up
    public int getIntegerValue() {
        if (getModel() instanceof ScrollListModel) {
            return ((ScrollListModel)getModel()).getIntegerValue();
        }
        else {
            return -1;
        }
    }

    // TF:19/07/2009:Cleaned this up
    public void setIntegerValue(int value) {
        if (getModel() instanceof ScrollListModel) {
            ((ScrollListModel)getModel()).setIntegerValue(value);
        }
    }

    // TF:19/07/2009:Cleaned this up
    public Object getObjectValue() {
        if (getModel() instanceof ScrollListModel) {
            return ((ScrollListModel)getModel()).getObjectValue();
        }
        else {
            return null;
        }
    }

    // TF:19/07/2009:Cleaned this up
    public void setObjectValue(Object value) {
        if (getModel() instanceof ScrollListModel) {
            ((ScrollListModel)getModel()).setObjectValue(value);
        }
    }

    // TF:19/07/2009:Cleaned this up
    public Array_Of_ListElement<ListElement> getElementList() {
        if (getModel() instanceof ScrollListModel) {
            return ((ScrollListModel)getModel()).getElementList();
        }
        else {
            return null;
        }
    }

    // TF:19/07/2009:Cleaned this up
    public void setElementList(Array_Of_ListElement<ListElement> les) {
        if (getModel() instanceof ScrollListModel) {
            ((ScrollListModel)getModel()).setElementList(les);
        }
    }
    protected void processKeyEvent(KeyEvent ke) {
        if (ke.getKeyChar() == KeyEvent.VK_TAB) {
            if (ke.getID() == KeyEvent.KEY_TYPED) {
                KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                if (ke.isShiftDown()) {
                    focusManager.focusPreviousComponent();
                } else {
                    focusManager.focusNextComponent();
                }
            }
            ke.consume();
        } else {
            super.processKeyEvent(ke);
        }
    }
   
    //FIX:JJ:M Implementation of requestScroll method
    public void requestScroll(int line, int scrollPolicy){
        int offset = this.getVisibleRowCount();

        if(scrollPolicy==Constants.AF_TOP){       
            this.ensureIndexIsVisible(line);
        }
        else if(scrollPolicy==Constants.AF_BOTTOM){       
            this.ensureIndexIsVisible(line - offset);
        }
        else if(scrollPolicy==Constants.AF_DEFAULT || scrollPolicy==Constants.AF_AUTOMATIC){       
            if(line < this.getFirstVisibleIndex()){          
                this.ensureIndexIsVisible(line);
            }else if(line > this.getLastVisibleIndex()){         
                this.ensureIndexIsVisible(line - offset);
            }
        }
        else if(scrollPolicy==Constants.AF_MIDDLE){       
            this.ensureIndexIsVisible(line - (offset/2));
        }     

    }
    public ScrollList cloneComponent(){
        ScrollList clone = ListFieldFactory.newScrollList();
        CloneHelper.cloneComponent(this, clone, new String[]{//"UI", // class javax.swing.plaf.LabelUI
                //"UIClassID", // class java.lang.String
                //"accessibleContext", // class javax.accessibility.AccessibleContext
                //"actionMap", // class javax.swing.ActionMap
                "alignmentX", // float
                "alignmentY", // float
                //"ancestorListeners", // class [Ljavax.swing.event.AncestorListener;
                "appData", // class java.lang.Object
                "autoscrolls", // boolean
                "background", // class java.awt.Color
                "border", // interface javax.swing.border.Border
                "component", // null
                "componentCount", // int
                "componentPopupMenu", // class javax.swing.JPopupMenu
                //"components", // class [Ljava.awt.Component;
                //"containerListeners", // class [Ljava.awt.event.ContainerListener;
                "debugGraphicsOptions", // int
                "disabledIcon", // interface javax.swing.Icon
                "displayedMnemonic", // int
                "displayedMnemonicIndex", // int
                "doubleBuffered", // boolean
                "enabled", // boolean
                //"focusCycleRoot", // boolean
                //"focusTraversalKeys", // null
                //"focusTraversalPolicy", // class java.awt.FocusTraversalPolicy
                //"focusTraversalPolicyProvider", // boolean
                //"focusTraversalPolicySet", // boolean
                "focusable", // boolean
                "font", // class java.awt.Font
                "foreground", // class java.awt.Color
                //"graphics", // class java.awt.Graphics
                "height", // int
                "horizontalAlignment", // int
                "horizontalTextPosition", // int
                //"icon", // interface javax.swing.Icon
                "iconTextGap", // int
                "inheritsPopupMenu", // boolean
                "inputMap", // null
                //"inputVerifier", // class javax.swing.InputVerifier
                "insets", // class java.awt.Insets
                //"labelFor", // class java.awt.Component
                //"layout", // interface java.awt.LayoutManager
                //"managingFocus", // boolean
                "maximumSize", // class java.awt.Dimension
                "minimumSize", // class java.awt.Dimension
                "name", // class java.lang.String
                //"nextFocusableComponent", // class java.awt.Component
                "opaque", // boolean
                "optimizedDrawingEnabled", // boolean
                "paintingTile", // boolean
                "preferredSize", // class java.awt.Dimension
                //"registeredKeyStrokes", // class [Ljavax.swing.KeyStroke;
                "requestFocusEnabled", // boolean
                //"rootPane", // class javax.swing.JRootPane
                "selected", // boolean
                "text", // class java.lang.String
                "toolTipText", // class java.lang.String
                //"topLevelAncestor", // class java.awt.Container
                //"transferHandler", // class javax.swing.TransferHandler
                "transparent", // boolean
                "validateRoot", // boolean
                "verifyInputWhenFocusTarget", // boolean
                "verticalAlignment", // int
                "verticalTextPosition", // int
                //"vetoableChangeListeners", // class [Ljava.beans.VetoableChangeListener;
                "visible", // boolean
                //"visibleRect", // class java.awt.Rectangle
                "width", // int
                "x", // int
                "y" // int
                });
        clone.setElementList(this.getElementList());
        return clone;
    }

  /* (non-Javadoc)
   * @see com.lumley.gennetica.genneticaframework.displayproject.ListField#setElementSelected(int, boolean)
     * @author AD:26/5/2008
   */
  public void setElementSelected(int index, boolean isSelected) {
        if (isSelected) {
            addSelectionInterval(index, index);
        }
        else {
            removeSelectionInterval(index, index);
        }
  }
 
  /**
   * Add a list selection listener to this list. This method overrides the default implementation of this
   * in order to ensure that the same listener is only added once. This is important to overcome an issue
   * with the generator which used to explicitly add the model as a listener to the control. As this code
   * has now been put into the model, we would insert the listener twice under the old code, which is
   * undesirable.
   */
  @Override
  public void addListSelectionListener(ListSelectionListener listener) {
    super.removeListSelectionListener(listener);
    super.addListSelectionListener(listener);
  }

  /**
   * Implementation of the ListDataListener interface
   */
  public void contentsChanged(ListDataEvent e) {
    this.updateList();
  }

  /**
   * Implementation of the ListDataListener interface
   */
  public void intervalAdded(ListDataEvent e) {
    this.updateList();
  }

  /**
   * Implementation of the ListDataListener interface
   */
  public void intervalRemoved(ListDataEvent e) {
    this.updateList();
  }
 
  private void updateList() {
      // CraigM:21/01/2009 - Compute the new min width for the model and relayout
      this.widthForData = 0;
     
      FontMetrics fm = this.getFontMetrics(this.getFont());
      int length = this.getModel().getSize();
      for (int i = 0; i < length; i++) {
        Object thisElement = this.getModel().getElementAt(i);
        int width = SwingUtilities.computeStringWidth(fm, thisElement.toString()) + 15; // +15 for the margins
        if (width > this.widthForData) {
          this.widthForData = width;
        }
      }
      this.doLayout();
  }
 
    /**
     * CraigM:08/01/2009 - Return the required width to show the data
     */
    public int getWidthForData() {
        return widthForData;
    }
   
    @Override
    public void setModel(ListModel model) {
      ListModel oldModel = this.getModel();
      if (oldModel != null) {
        oldModel.removeListDataListener(this);
      }
      super.setModel(model);
      model.addListDataListener(this);
      // We have a new model, update it's data
      this.updateList();
    }
}
TOP

Related Classes of DisplayProject.controls.ScrollList$ScrollListCellRenderer$DashedLineBorder

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.