SJasperViewScreen.java :  » J2EE » Sofia » com » salmonllc » jasperReports » Java Open Source

Java Open Source » J2EE » Sofia 
Sofia » com » salmonllc » jasperReports » SJasperViewScreen.java
//The Salmon Open Framework for Internet Applications (SOFIA)
//Copyright (C) 1999 - 2003, Salmon LLC
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License version 2
//as published by the Free Software Foundation;
//
//This program 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 for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//
//For more information please visit http://www.salmonllc.com
//** End Copyright Statement ***************************************************
package com.salmonllc.jasperReports;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingConstants;

import dori.jasper.engine.JRException;
import dori.jasper.engine.JRHyperlink;
import dori.jasper.engine.JRPrintAnchor;
import dori.jasper.engine.JRPrintAnchorIndex;
import dori.jasper.engine.JRPrintElement;
import dori.jasper.engine.JRPrintHyperlink;
import dori.jasper.engine.JRPrintPage;
import dori.jasper.engine.JRPrintText;
import dori.jasper.engine.JasperPrint;
import dori.jasper.engine.JasperPrintManager;

/**
 * This class serves as the basic GUI element for a SOFIA Based Jasper Report Viewer. It provides an unembelished user interface that allows for the viewing of a page in a Jasper print and a few helper methods to query or change the state of the page being viewed.  
 */
public class SJasperViewScreen extends JPanel  {
  private JasperPrint _pr;
  private JLabel _main;
  private JPanel _noData;
  private JLabel _noDataLabel;
  private int _page = 0;
  private JScrollPane _pane;
  private float _zoom = 1.0F;
  private ArrayList _links = new ArrayList();
  private ArrayList _sorts = new ArrayList();
  private URLOpener _urlOpener;
  
  
  /**
   * Creates a view screen for a particular JasperPrint object. The page will be set to zero and the zoom to 100%
   */
  public SJasperViewScreen(JasperPrint pr) {
    buildComponents(pr,-1,0.0F);
  }

  /**
   * Creates a view screen for a particular JasperPrint object. The page will be set to zero and the zoom to 100%
   */
  public SJasperViewScreen(JasperPrint pr, URLOpener urlOpener) {
    _urlOpener = urlOpener;
    buildComponents(pr,-1,0.0F);
  }
  
  /**
   * Creates a view screen for a particular JasperPrint object. 
   */
  public SJasperViewScreen(JasperPrint pr, int pageNo, float zoomPercent, URLOpener urlOpener) {
    _urlOpener = urlOpener;
    buildComponents(pr,pageNo,zoomPercent);
  }

  private void buildComponents(JasperPrint pr, int pageNo, float zoomPercent) {
    setLayout(new GridLayout(1, 1));
    _pr = pr;
    _main = new JLabel();
    _pane = new JScrollPane(_main);
    
    _noData = new JPanel(new GridLayout(1,1));
    _noData.setBorder(BorderFactory.createEtchedBorder());
    _noDataLabel = new JLabel("No Data Found",SwingConstants.CENTER);
    _noDataLabel.setFont(new Font("Helvetica",Font.BOLD,24));
    _noDataLabel.setBackground(Color.white);
    _noDataLabel.setOpaque(true);
    _noData.add(_noDataLabel);
    if (pageNo != -1) {
      _page = pageNo;
      _zoom = zoomPercent;
    }  
    refreshScreen();    
  }  
  /**
   * Gets the current page number
   */
  public int getPageNo() {
    return _page;
  }

  /**
   * Gets the JasperPrint that the viewer is using 
   */
  public JasperPrint getJasperPrint() {
    return _pr;
  }

  /**
   * gets the zoom percent for the report 1.0F = 100%
   */
  public float getZoomPercent() {
    return _zoom;
  }

  /**
   * Sets the JasperPrint that the viewer is using 
   */
  public void setJasperPrint(JasperPrint print) {
    _pr = print;
    _page = 0;
    refreshScreen();
  }

  /**
   * sets the zoom percent for the report 1.0F = 100%
   */
  public void setZoomPercent(float f) {
    _zoom = f;
    refreshScreen();
  }

  /**
   * Returns the conponent representing the report page viewer 
   */
  public JComponent getMainViewer() {
    return _main;
  }

  /**
   * Returns true if the specified page number exists 
   */

  public boolean isPageValid(int pageNo) {
    if (pageNo < 0)
      return false;
    List l = _pr.getPages();
    if (l == null)
      return false;
    return pageNo < l.size();
  }

  /**
   * Returns true if the viewer is on the last page of the report or if the report is empty
   */

  public boolean isOnLastPage() {
    List l = _pr.getPages();
    if (l == null || l.size() == 0)
      return true;
    return _page == (l.size() - 1);
  }

  /**
   * Returns true if the viewer is on the first page of the report or if the report is empty
   */

  public boolean isOnFirstPage() {
    List l = _pr.getPages();
    if (l == null || l.size() == 0)
      return true;
    return _page == 0;
  }

  /**
   * Cause the viewer to display the next page in the report
   */
  public void gotoNextPage() {
    gotoPage(_page + 1);
  }

  /**
   * Cause the viewer to display the prior page in the report
   */

  public void gotoPriorPage() {
    gotoPage(_page - 1);
  }

  /**
   * Cause the viewer to display the first page in the report
   */
  public void gotoFirstPage() {
    gotoPage(0);
  }

  /**
   * Cause the viewer to display the last page in the report
   */
  public void gotoLastPage() {
    gotoPage(getPageCount() - 1);
  }

  /**
   * Cause the viewer to display the specified page in the report
   */
  public void gotoPage(int page) {
    if (isPageValid(page)) {
      _page = page;
      refreshScreen();
    }
  }

  /**
   * Returns the number of pages in the print
   */
  public int getPageCount() {
    List l = _pr.getPages();
    if (l == null)
      return 0;
    else
      return l.size();
  }


  /**
   * Returns the column name(s) of the fields in the sort anchor at the specified point or null if there is no sort anchor at that point. Sort anchors are Jasper Report constructs specific to The SOFIA Viewer which allow the user to click on a title and sort by it. They are text fields with the anchor link expression set using the convention "sort:comma seperated list of field names to sort by"
   * @param p Point relative to the main viewer in the component
   * @see SJasperViewScreen#getMainViewer()
   */
  public String getSortColumnsAtPoint(Point p) {
    Object item[] = null;
    Rectangle r = null;
    for (int i = 0; i < _sorts.size(); i++) {
      item = (Object[]) _sorts.get(i);
      r = (Rectangle) item[0];
      if (r.contains(p))
        return (String) item[1];
    }
    return null;
  }

  /**
   * Returns the text for the sort anchor at a specified point or null if there is no sort anchor at that point. Sort anchors are Jasper Report constructs specific to The SOFIA Viewer which allow the user to click on a title and sort by it. They are text fields with the anchor link expression set using the convention "sort:comma seperated list of field names to sort by"
   * @param p Point relative to the main viewer in the component
   * @see SJasperViewScreen#getMainViewer()
   */
  public String getSortNameAtPoint(Point p) {
    Object item[] = null;
    Rectangle r = null;
    for (int i = 0; i < _sorts.size(); i++) {
      item = (Object[]) _sorts.get(i);
      r = (Rectangle) item[0];
      if (r.contains(p))
        return (String) item[2];
    }
    return null;
  }
  
  /**
   * Returns the hyperlink at the current point or null if there isn't one at the point.
   * @param p Point relative to the main viewer in the component
   * @see SJasperViewScreen#getMainViewer()
   */
  public JRPrintHyperlink getHyperlinkAtPoint(Point p) {
    Object item[] = null;
    Rectangle r = null;
    for (int i = 0; i < _links.size(); i++) {
      item = (Object[]) _links.get(i);
      r = (Rectangle) item[0];
      if (r.contains(p))
        return (JRPrintHyperlink) item[1];
    }
    return null;
  }


  /**
   * Returns the position of upper right hand corner of the main viewer in the panel
   */
  public Point getMainViewPosition() {
    return new Point(_pane.getViewport().getX(),_pane.getViewport().getY());
  }
  /**
   * For JRPrintHyperLinks that are local to this report JRHyperlink.HYPERLINK_TYPE_LOCAL_ANCHOR or JRHyperlink.HYPERLINK_TYPE_LOCAL_PAGE, this method will zoom to the correct spot in the document
   * @return true if the link could be processed and false if not
   */
  public boolean gotoHyperLinkLocation(JRPrintHyperlink link, boolean ctrlDown) {
    if (link.getHyperlinkType() == JRHyperlink.HYPERLINK_TYPE_LOCAL_ANCHOR) {
      if (link.getHyperlinkAnchor() != null) {
        Map anchorIndexes = _pr.getAnchorIndexes();
        JRPrintAnchorIndex anchorIndex = (JRPrintAnchorIndex) anchorIndexes.get(link.getHyperlinkAnchor());
        if (anchorIndex.getPageIndex() != _page)
          gotoPage(anchorIndex.getPageIndex());
        Container container = _main.getParent();
        if (container instanceof JViewport) {
          JViewport viewport = (JViewport) container;
          int newX = (int) (anchorIndex.getElement().getX() * _zoom);
          int newY = (int) (anchorIndex.getElement().getY() * _zoom);
          int maxX = _main.getWidth() - viewport.getWidth();
          int maxY = _main.getHeight() - viewport.getHeight();
          if (newX < 0)
            newX = 0;
          if (newX > maxX)
            newX = maxX;
          if (newY < 0)
            newY = 0;
          if (newY > maxY)
            newY = maxY;
          viewport.setViewPosition(new Point(newX, newY));
        }
        return true;
      }
    } else if (link.getHyperlinkType() == JRHyperlink.HYPERLINK_TYPE_LOCAL_PAGE) {
      int page = _page + 1;
      if (link.getHyperlinkPage() != null)
        page = link.getHyperlinkPage().intValue();

      if (page >= 1 && page <= _pr.getPages().size() && page != _page + 1) {
        this.gotoPage(page - 1);
        Container container = _main.getParent();
        if (container instanceof JViewport) {
          JViewport viewport = (JViewport) container;
          viewport.setViewPosition(new Point(0, 0));
        }
      }
      return true;
    } else if (link.getHyperlinkType() == JRHyperlink.HYPERLINK_TYPE_REFERENCE) {
        if (_urlOpener != null) {
          try {
            if (! ctrlDown)
              _urlOpener.openURL(link.getHyperlinkReference());
            else
              _urlOpener.openURL(link.getHyperlinkReference(),"newFrame");
          } catch (MalformedURLException e) {
            e.printStackTrace();
          }  
        }  
    }  
    
    return false;
  }
  /**
   * Sets the message to be displayed when there is no data in the report
   * @param message
   */
  public void setNoDataMessage(String message) {
    _noDataLabel.setText(message);
  }  
  
  private void refreshScreen() {
    try {
      removeAll();
      if (getPageCount() == 0) 
        add(_noData);
      else {      
        add(_pane);  
        java.awt.Image image = JasperPrintManager.printPageToImage(_pr, _page, _zoom);
        ImageIcon imageIcon = new ImageIcon(image);
        _main.setText(null);
        _main.setIcon(imageIcon);
        _main.setVisible(true);
        setUpLinksAndSorts();
      }  
      revalidate();
      repaint();
    } catch (JRException ex) {
      ex.printStackTrace();
    }
  }

  private void setUpLinksAndSorts() {
    _links.clear();
    _sorts.clear();
    java.util.List pages = _pr.getPages();
    JRPrintPage page = (JRPrintPage) pages.get(_page);
    Collection elements = page.getElements();

    if (elements != null && elements.size() > 0) {
      JRPrintElement element = null;
      JRPrintHyperlink hyperlink = null;
      Rectangle rect = null;
      for (Iterator it = elements.iterator(); it.hasNext();) {
        element = (JRPrintElement) it.next();
        if (element instanceof JRPrintHyperlink && ((JRPrintHyperlink) element).getHyperlinkType() != JRHyperlink.HYPERLINK_TYPE_NONE) {
          hyperlink = (JRPrintHyperlink) element;
          rect = new Rectangle((int) (element.getX() * _zoom), (int) (element.getY() * _zoom), (int) (element.getWidth() * _zoom), (int) (element.getHeight() * _zoom));
          Object item[] = { rect, hyperlink };
          _links.add(item);
        }
        else if (element instanceof JRPrintAnchor) {
          String anchorName = ((JRPrintAnchor) element).getAnchorName();
          if (anchorName != null) {
            if (anchorName.toLowerCase().startsWith("sort:")) {
              rect = new Rectangle((int) (element.getX() * _zoom), (int) (element.getY() * _zoom), (int) (element.getWidth() * _zoom), (int) (element.getHeight() * _zoom));
              Object item[] = { rect, anchorName.substring(5), ""};
              if (element instanceof JRPrintText)
                item[2] = ((JRPrintText)element).getText(); 
              _sorts.add(item);
            }
          }
        }
      }
    }

  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.