⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ngclabel.java

📁 Novocode的 SWT 控件框架 丰富了MDI功能
💻 JAVA
字号:
/*******************************************************************************
 * Copyright (c) 2004 Stefan Zeiger and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.novocode.com/legal/epl-v10.html
 * 
 * Contributors:
 *     Stefan Zeiger (szeiger@novocode.com) - initial API and implementation
 *******************************************************************************/

package com.novocode.naf.gui;

import java.util.*;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;
import org.w3c.dom.*;

import com.novocode.naf.app.*;
import com.novocode.naf.color.ColorData;
import com.novocode.naf.data.Alignment;
import com.novocode.naf.data.DataDecoder;
import com.novocode.naf.data.ModelBinding;
import com.novocode.naf.data.Orientation;
import com.novocode.naf.data.Shadow;
import com.novocode.naf.data.XMLProperty;
import com.novocode.naf.gui.event.*;
import com.novocode.naf.model.*;
import com.novocode.naf.resource.*;


/**
 * A non-native text and/or image label with advanced features.
 * 
 * @author Stefan Zeiger (szeiger@novocode.com)
 * @since Jan 4, 2004
 */

public final class NGCLabel extends NGWidget
{
  private Shadow shadow = Shadow.NONE;
  private Alignment alignment = Alignment.LEFT;
  private String text, attrText, imageResource;
  private Map<String, String> images;
  private LinkedList<String> childTokens;
  private ColorData[] gradientColors;
  private Orientation gradientOrientation = Orientation.HORIZONTAL;
  private int[] gradientWeights;


  @XMLProperty("image") public void setImageResource(String imageResource) { this.imageResource = imageResource; }
  public String getImageResource() { return imageResource; }


  @XMLProperty public void setText(String text) { this.text = text; this.attrText = text; }
  public String getText() { return text; }


  @XMLProperty("align") public void setAlignment(Alignment alignment) { this.alignment = alignment; }
  public Alignment getAlignment() { return alignment; }


  @XMLProperty public void setShadow(Shadow s) throws NAFException
  {
    s.checkStyleMask(SWT.SHADOW_NONE|SWT.SHADOW_IN|SWT.SHADOW_OUT, false);
    this.shadow = s;
  }
  public Shadow getShadow() { return shadow; }


  @XMLProperty public void setGradientOrientation(Orientation ori) { this.gradientOrientation = ori; }
  public Orientation getGradientOrientation() { return gradientOrientation; }


  @XMLProperty public void setGradientColors(ColorData[] cda) { this.gradientColors = cda; }
  public ColorData[] getGradientColors() { return gradientColors; }


  @XMLProperty public void setGradientWeights(int[] weights) { this.gradientWeights = weights; }
  public int[] getGradientWeights() { return gradientWeights; }


  protected void init() throws NAFException
  {
    if(gradientWeights != null && gradientColors != null)
    {
      if(gradientColors.length != gradientWeights.length+1)
        throw new NAFException("Length of gradientWeights must be one less than length of gradientColors");
    }
    if(gradientColors != null && gradientWeights == null)
    {
      gradientWeights = new int[gradientColors.length-1];
      for(int i=0; i<gradientWeights.length-1; i++)
        gradientWeights[i] = (int)(100.0 / gradientWeights.length * (i+1));
      if(gradientWeights.length != 0) gradientWeights[gradientWeights.length-1] = 100;
      /*StringBuffer buf = new StringBuffer();
      buf.append("NGCLabel: Constructed gradientWeights array:");
      for(int i=0; i<gradientWeights.length; i++) buf.append(' ').append(gradientWeights[i]);
      System.out.println(buf);*/
    }
    super.init();
    if(attrText == null && childTokens != null)
    {
      StringBuffer b = new StringBuffer();
      for(String s : childTokens) b.append(s);
      text = b.toString().trim().replace((char)160,' ');
      if(text.length() == 0) text = null;
    }
    if(gradientColors != null) setBackgroundColor(ColorData.DEFAULT);
  }


  protected void parseChild(Node n) throws NAFException // [TODO] Don't decode backslash sequences
  {
    if(n.getNodeType() == Node.TEXT_NODE)
    {
      if(childTokens == null) childTokens = new LinkedList<String>();
      String text = ((org.w3c.dom.Text)n).getData();
      text = text.replace('\r', ' ').replace('\n', ' ').replace('\r', ' ');
      if(text.startsWith(" ") && childTokens.size() != 0 && (!" ".equals(childTokens.getLast())) && (!"\n".equals(childTokens.getLast())))
        childTokens.add(" ");
      boolean first = true;
      for(StringTokenizer tok = new StringTokenizer(text); tok.hasMoreTokens();)
      {
        String s = tok.nextToken();
        if(s.length() == 0) continue;
        if(!first) childTokens.add(" ");
        childTokens.add(s);
        first = false;
      }
      if(text.endsWith(" ")) childTokens.add(" ");
    }
    else if(n.getNodeType() == Node.ELEMENT_NODE
            && GUIResourceManager.NAF_NAMESPACE_URI.equals(n.getNamespaceURI())
            && n.getLocalName().equals("br"))
    {
      if(childTokens == null) childTokens = new LinkedList<String>();
      if(childTokens.size() != 0 && " ".equals(childTokens.getLast())) childTokens.removeLast();
      childTokens.add("\n");
    }
    else super.parseChild(n);
  }


  protected void parseNAFChildElement(Element e) throws NAFException
  {
    String ln = e.getLocalName();
    if("image".equals(ln))
    {
      String iid = e.getAttribute("id");
      String ires = e.getAttribute("image");
      if(iid != null && ires != null)
      {
        if(images == null) images = new HashMap<String, String>();
        images.put(iid, ires);
      }
    }
    else super.parseNAFChildElement(e);
  }


  public Control createControl(Composite parent, NGComponent parentComp, ShellWindowInstance wi, WidgetData pwd) throws NAFException
  {
    int style = alignment.style | shadow.style;
    final int[] maxImgHeight = new int[1];
    Map<String, Image> imageInstances = null;

    final CLabel label = new CLabel(parent, style)
    {
      public Point computeSize(int wHint, int hHint, boolean changed)
      {
        Point p = super.computeSize(wHint, hHint, changed);
        int mih = maxImgHeight[0];
        if(mih != 0)
        {
          mih += 6; // 6 = 2 * Clabel.vIndent
          //System.out.println("p.y = "+p.y+", mih = "+mih);
          if(mih > p.y) p.y = mih;
        }
        return p;
      }
    };
    if(images != null && getModel("clabel", wi.models) != null)
    {
      imageInstances = new HashMap<String, Image>();
      for(Map.Entry<String, String> entry : images.entrySet())
      {
        Image img = SWTUtil.getRegisteredImage(entry.getValue(), getResourceURL(), label, wi.imageManager, false);
        imageInstances.put(entry.getKey(), img);
        if(img != null)
        {
          int ih = img.getBounds().height;
          if(ih > maxImgHeight[0]) maxImgHeight[0] = ih;
        }
      }
    }
    SWTUtil.setRegisteredImage(imageResource, getResourceURL(), label, wi.imageManager, true);
    if(text != null) label.setText(DataDecoder.decodeBackslashEscapes(text));

    if(gradientColors != null)
    {
      final ArrayList<Color> allocList = new ArrayList<Color>();
      Color[] colors = new Color[gradientColors.length];
      for(int i=0; i<colors.length; i++)
      {
        ColorData c = gradientColors[i];
        if(c.getType() == ColorData.TYPE_SYSTEM_COLOR) colors[i] = wi.display.getSystemColor(c.systemColorCode);
        else if(c.getType() == ColorData.TYPE_CUSTOM_COLOR)
        {
          colors[i] = c.createCustomColor(wi.display);
          allocList.add(colors[i]);
        }
        else if(c.getType() == ColorData.TYPE_INHERIT)
        {
          if(pwd != null && pwd.givenBG != null) colors[i] = pwd.givenBG;
          else colors[i] = label.getBackground();
        }
        else // TYPE_DEFAULT
        {
          colors[i] = label.getBackground();
        }
        if(allocList.size() != 0)
        {
          label.addDisposeListener(new DisposeListener()
          {
            public void widgetDisposed(DisposeEvent e)
            {
              for(Color c : allocList) c.dispose();
            }
          });
        }
      }
      label.setBackground(colors, gradientWeights, gradientOrientation == Orientation.VERTICAL);
    }

    final IObjectReadModel<String> textModel = getModel("text", wi.models);
    final ICLabelModel clabelModel = getModel("clabel", wi.models);
    final Map<String, Image> finalImageInstances = imageInstances;

    if(textModel != null && clabelModel != null)
      throw new NAFException("Only one of clabel model and text model may be specified for a NGCLabel");

    if(textModel != null)
    {
      final IChangeListener cl = new IChangeListener()
      {
        public void stateChanged(ChangeEvent e)
        {
          String s = textModel.getValue();
          if(s == null) s = "";
          if(s.equals(label.getText())) return;
          label.setText(s);
        }
      };
      SWTUtil.registerModel(label, textModel, cl);
      cl.stateChanged(null);
    }

    if(clabelModel != null)
    {
      final IChangeListener cl = new IChangeListener()
      {
        public void stateChanged(ChangeEvent e)
        {
          String text = clabelModel.getText();
          Image img = null;
          if(finalImageInstances != null)
            img = finalImageInstances.get(clabelModel.getImageID());
          if(text == null) text = "";
          if(!text.equals(label.getText())) label.setText(text);
          if(img != label.getImage()) label.setImage(img);
        }
      };
      SWTUtil.registerModel(label, clabelModel, cl);
      cl.stateChanged(null);
    }

    return label;
  }


  protected Object createDefaultModel(ModelBinding mb)
  {
    if("text".equals(mb.type)) return new DefaultStringModel();
    else if("clabel".equals(mb.type)) return new DefaultCLabelModel();
    else return super.createDefaultModel(mb);
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -