Java Code Examples for java.awt.Graphics.setClip()

The following are Jave code examples for showing how to use setClip() of the java.awt.Graphics class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: rapidminer   File: RoundedRectanglePopup.java   View Source Code Vote up 6 votes
private void drawRemaining(Rectangle rectangle, Component lp, BufferedImage pic) {
	if ((rectangle.x + rectangle.width) > lp.getWidth()) {
		rectangle.width = lp.getWidth() - rectangle.x;
	}
	if ((rectangle.y + rectangle.height) > lp.getHeight()) {
		rectangle.height = lp.getHeight() - rectangle.y;
	}
	if (!rectangle.isEmpty()) {
		Graphics g = pic.createGraphics();
		g.translate(-rectangle.x, -rectangle.y);
		g.setClip(rectangle);
		boolean doubleBuffered = lp.isDoubleBuffered();
		if (lp instanceof JComponent) {
			((JComponent) lp).setDoubleBuffered(false);
			lp.paint(g);
			((JComponent) lp).setDoubleBuffered(doubleBuffered);
		} else {
			lp.paint(g);
		}
		g.dispose();
	}
}
 
Example 2
Project: myster   File: AWTMCList.java   View Source Code Vote up 6 votes
private void updatey(Graphics g) { //done.
    if (pane.getViewportSize().height - header.getHeight() < 0)
        return;
    if (previousimagex != pane.getViewportSize().width || //makes sure the
            // image buffer is
            // up to date!
            previousimagey != pane.getViewportSize().height
            || false) {
        im = createImage(pane.getViewportSize().width, pane.getViewportSize().height
                - header.getHeight());//new
        // BufferedImage(pane.getViewportSize().width,pane.getViewportSize().height-header.getHeight(),BufferedImage.TYPE_INT_BGR);//
        previousimagex = pane.getViewportSize().width;
        previousimagey = pane.getViewportSize().height;
    }
    paint(im.getGraphics(), pane.getScrollPosition().x, pane.getScrollPosition().x
            + pane.getViewportSize().width, pane.getScrollPosition().y, pane
            .getScrollPosition().y
            + pane.getViewportSize().height);
    g.setClip(pane.getScrollPosition().x, pane.getScrollPosition().y,
            pane.getViewportSize().width, pane.getViewportSize().height);
    g.drawImage(im, pane.getScrollPosition().x,
            pane.getScrollPosition().y + header.getHeight(), this);
}
 
Example 3
Project: TrabalhoFinalEDA2   File: mxGraphComponent.java   View Source Code Vote up 6 votes
/**
 * 
 */
protected void paintBackground(Graphics g)
{
	Rectangle clip = g.getClipBounds();
	Rectangle rect = paintBackgroundPage(g);

	if (isPageVisible())
	{
		g.clipRect(rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1);
	}

	// Paints the clipped background image
	paintBackgroundImage(g);

	// Paints the grid directly onto the graphics
	paintGrid(g);
	g.setClip(clip);
}
 
Example 4
Project: Tarski   File: mxGraphComponent.java   View Source Code Vote up 6 votes
/**
 * 
 */
protected void paintBackground(Graphics g) {
  Rectangle clip = g.getClipBounds();
  Rectangle rect = paintBackgroundPage(g);

  if (isPageVisible()) {
    g.clipRect(rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1);
  }

  // Paints the clipped background image
  paintBackgroundImage(g);

  // Paints the grid directly onto the graphics
  paintGrid(g);
  g.setClip(clip);
}
 
Example 5
Project: brModelo   File: InspectorExtenderEditor.java   View Source Code Vote up 5 votes
@Override
public void paint(Graphics g) {
    super.paint(g);
    //Color bkp = g.getColor();
    Rectangle r = this.getBounds();
    g.setColor(Color.BLACK);
    int re = 0;
    String bonito = "?";
    if (getAcaoTipo() == TipoDeAcao.tpAcaoDlgCor || getAcaoTipo() == TipoDeAcao.tpReadOnlyCor) {
        g.setColor(Color.BLACK);
        g.fillRect(3, 3, r.height - 7, r.height - 7);
        try {
            Color c = util.Utilidades.StringToColor(getTexto());
            g.setColor(c);
            bonito = getTexto();
        } catch (Exception e) {
        }
        g.fillRect(4, 4, r.height - 8, r.height - 8);
        //g.setColor(Color.BLACK);
        //g.drawRect(3, 3, r.height - 7, r.height - 7);
        re = r.height - 1;
    } else {
        bonito = getTexto().replaceAll("\n", " | ");
    }
    //g.setColor(bkp);
    
    Rectangle obkp = g.getClipBounds();

    g.setColor(Color.DARK_GRAY);
    g.setFont(new Font(this.getFont().getFontName(), Font.BOLD, getFont().getSize()));
    g.clipRect(re, 0, r.width - r.height -re - (re == 0? 4: 8), r.height);
    g.drawString(bonito, re + 2, (int) (r.height * 0.72) + 1);
    g.drawLine(0, 0, 0, getHeight());
    g.setClip(obkp);
}
 
Example 6
Project: incubator-netbeans   File: TimelineTooltipOverlay.java   View Source Code Vote up 5 votes
public void paint(Graphics g) {
    if (getComponentCount() == 0) return;

    Rectangle bounds = new Rectangle(0, 0, getWidth(), getHeight());
    Rectangle clip = g.getClipBounds();
    if (clip == null) g.setClip(bounds);
    else g.setClip(clip.intersection(bounds));

    super.paint(g);
}
 
Example 7
Project: openjdk-jdk10   File: Test6978482.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
    Component c = new Component() {};
    c.setBackground(Color.WHITE);
    c.setForeground(Color.BLACK);
    Graphics g = new BufferedImage(1024, 768, BufferedImage.TYPE_INT_RGB).getGraphics();
    g.setClip(0, 0, 1024, 768);
    for (Border border : BORDERS) {
        System.out.println(border.getClass());
        border.getBorderInsets(c);
        border.paintBorder(c, g, 0, 0, 1024, 768);
    }
}
 
Example 8
Project: incubator-netbeans   File: DropdownButton.java   View Source Code Vote up 5 votes
public void paint(Graphics g) {
    if (pushed || !button.isEnabled() || container.getComponent(0) == this) {
        Rectangle c = g.getClipBounds();
        g.setClip(getWidth() - POPUP_EXTENT, 0, POPUP_EXTENT, getHeight());
        super.paint(g);
        g.setClip(c);
    }
}
 
Example 9
Project: incubator-netbeans   File: ProfilerXYTooltipOverlay.java   View Source Code Vote up 5 votes
public void paint(Graphics g) {
    if (tooltipPainter == null) return;

    Rectangle bounds = new Rectangle(0, 0, getWidth(), getHeight());
    Rectangle clip = g.getClipBounds();
    if (clip == null) g.setClip(bounds);
    else g.setClip(clip.intersection(bounds));

    super.paint(g);
}
 
Example 10
Project: jdk8u-jdk   File: Test6978482.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
    Component c = new Component() {};
    c.setBackground(Color.WHITE);
    c.setForeground(Color.BLACK);
    Graphics g = new BufferedImage(1024, 768, BufferedImage.TYPE_INT_RGB).getGraphics();
    g.setClip(0, 0, 1024, 768);
    for (Border border : BORDERS) {
        System.out.println(border.getClass());
        border.getBorderInsets(c);
        border.paintBorder(c, g, 0, 0, 1024, 768);
    }
}
 
Example 11
Project: incubator-netbeans   File: DrawEngineLineView.java   View Source Code Vote up 4 votes
public void paint(Graphics g, Shape a) {
    if (!(getDocument() instanceof BaseDocument)) return; //#48134
    // When painting make sure the estimated span is set to false
    setEstimatedSpan(false);
    // No modifications to allocReadOnly variable!
    Rectangle allocReadOnly = (a instanceof Rectangle) ? (Rectangle)a : a.getBounds();
    int startOffset = getStartOffset();
    int endOffset = getAdjustedEOLOffset();
    try{
        if (isFragment()){
            Rectangle oldClipRect = g.getClipBounds();                
            Rectangle newClip = new Rectangle(oldClipRect);
            Rectangle startOffsetClip = modelToView(startOffset, a, Position.Bias.Forward).getBounds();
            Rectangle endOffsetClip = modelToView(endOffset, a, Position.Bias.Forward).getBounds();
            View parent = getParent();
            if (parent instanceof FoldMultiLineView && !equals(parent.getView(parent.getViewCount() - 1))) {
                newClip.width = Math.min(oldClipRect.width, endOffsetClip.x);
                
                if (newClip.width + newClip.x > endOffsetClip.x) {
                    newClip.width = newClip.width - (newClip.width + newClip.x - endOffsetClip.x);
                }
                
                g.setClip(newClip);
            }

            int shift = startOffsetClip.x - getEditorUI().getTextMargin().left - allocReadOnly.x;
            g.translate(-shift,0);
            
            DrawEngine.getDrawEngine().draw(this, new DrawGraphics.GraphicsDG(g),
            getEditorUI(), startOffset, endOffset,
            getBaseX(allocReadOnly.x), allocReadOnly.y, Integer.MAX_VALUE);
            
            g.translate(shift,0);                
            g.setClip(oldClipRect);

        }else{
            JTextComponent component = getComponent();
            if (component!=null){
                long ts1 = 0, ts2 = 0;
                if (loggable) {
                    ts1 = System.currentTimeMillis();
                }
                
                // Translate the graphics clip region to the document offsets
                // and their view region
                Rectangle clip = g.getClipBounds();
                int fromOffset = viewToModel(clip.x, clip.y, allocReadOnly, null);
                int toOffset = viewToModel(clip.x + clip.width, clip.y, allocReadOnly, null);
                
                fromOffset = Math.max(fromOffset - 1, getStartOffset());
                toOffset = Math.min(toOffset + 1, getAdjustedEOLOffset());
                
                Rectangle rr = modelToView(fromOffset, allocReadOnly, Position.Bias.Forward).getBounds();
                
                DrawEngine.getDrawEngine().draw(this, new DrawGraphics.GraphicsDG(g),
                    getEditorUI(), fromOffset, toOffset,
                    rr.x, rr.y, Integer.MAX_VALUE);
                
                if (loggable) {
                    ts2 = System.currentTimeMillis();
                    if (ts2 - ts1 > PERF_TRESHOLD) {
                        LOG.finest("paint: " + //NOI18N
                            "<" + fromOffset + ", " + toOffset + ">, " + //NOI18N
                            "DrawEngine.startX = " + rr.x + ", DrawEngine.startY = " + rr.y + ", " + //NOI18N
                            "shape = [" + allocReadOnly.x + ", " + allocReadOnly.y + ", " + allocReadOnly.width + ", " + allocReadOnly.height + "], " + //NOI18N
                            "clip = [" + clip.x + ", " + clip.y + ", " + clip.width + ", " + clip.height + "] " + //NOI18N
                            "took " + (ts2 - ts1) + " msec"); //NOI18N
                    }
                }
            }
        }
    } catch (BadLocationException ble) {
        LOG.log(Level.INFO, "Painting the view failed", ble); //NOI18N
    }
}
 
Example 12
Project: incubator-netbeans   File: NimbusViewTabDisplayerUI.java   View Source Code Vote up 4 votes
@Override
protected void paintTabBackground(Graphics g, int index, int x, int y,
                                  int width, int height) {
    boolean isLast = index == getDataModel().size()-1;
    if (!isLast) {
        width++;
    }

    Shape clip = g.getClip();
    boolean isPreviousTabSelected = index-1 == displayer.getSelectionModel().getSelectedIndex();
    if (isPreviousTabSelected) {
        g.setClip(x+1, y, width-1, height);
    }

    final boolean attention = isAttention(index);
    Object o = null;
    if (isSelected(index)) {
        String mouseOver = "TabbedPane:TabbedPaneTab[MouseOver+Selected].backgroundPainter";
        String selected = "TabbedPane:TabbedPaneTab[Selected].backgroundPainter";
        if (isActive()) {
            o = UIManager.get( attention ? selected : mouseOver);
        } else {
            o = UIManager.get( attention ? mouseOver: selected);
        }
    } else {
        if( attention ) {
            o = UIManager.get("TabbedPane:TabbedPaneTab[Disabled].backgroundPainter");
        } else {
            o = UIManager.get("TabbedPane:TabbedPaneTab[Enabled].backgroundPainter");
        }
    }

    if ((o != null) && (o instanceof javax.swing.Painter)) {
        javax.swing.Painter painter = (javax.swing.Painter) o;
        BufferedImage bufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufIm.createGraphics();
        g2d.setBackground(UIManager.getColor("Panel.background"));
        g2d.clearRect(0, 0, width, height);
        painter.paint(g2d, null, width, height);
        g.drawImage(bufIm, x, y, null);
    }

    if (isPreviousTabSelected) {
        g.setClip(clip);
    }
}
 
Example 13
Project: incubator-netbeans   File: InnerPanelSupport.java   View Source Code Vote up 4 votes
private boolean updateTooltipImage(RenderedImage contents, int row, int col) {
            TableCellRenderer renderer = listClasses.getCellRenderer(row, col); 
            Component component = listClasses.prepareRenderer(renderer, row, col);
            
            if (!(component instanceof JComponent)) {
                // sorry.
                return false;
            }
            Rectangle cellRect = listClasses.getCellRect(row, col, false);
            Dimension size = component.getPreferredSize();
            Rectangle visibleRect = listClasses.getVisibleRect();
            
            // The visible region is wide enough, hide the tooltip
            if (cellRect.width >= size.width) {
                hidePopup();
                return false;
            }           
            // Hide if the cell does not vertically fit
            if (cellRect.y + size.height > visibleRect.y + visibleRect.height + 1) {
                hidePopup();
                return false;
            }
            BufferedImage img = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
            Graphics g = img.getGraphics();
            g.setClip(null);
            g.setColor(listClasses.getBackground());
            g.fillRect(0, 0, size.width, size.height);
            g.translate(-cellRect.x, -cellRect.y);
//            g.translate(-visibleRect.x, -visibleRect.y);
            
            cellRect.width = size.width;
            // prevent some repaing issues, see javadoc for CellRendererPane.
            rendererPane.paintComponent(g, component, listClasses, cellRect);
            
            // if table displays lines, frame the cell's display using lines.
            if (listClasses.getShowHorizontalLines()) {
                int rightX = size.width - 1;
                g.translate(cellRect.x, cellRect.y);
                g.setColor(listClasses.getForeground());
                g.drawLine(0, 0, rightX, 0);
                g.drawLine(rightX, 0, rightX, size.height);
                g.drawLine(rightX, size.height - 1, 0, size.height - 1);
            }
            g.dispose();
            rendererPane.remove(component);
            contents.setImage(img);
            return true;
        }
 
Example 14
Project: VASSAL-src   File: Region.java   View Source Code Vote up 4 votes
public void draw(Graphics g, Rectangle bounds, Rectangle visibleRect, double scale, boolean reversed, int xOffset, int yOffset) {
  if (!bounds.intersects(visibleRect)) {
    return;
  }

  final int labelOffset = 7;

  int size = (int) (scale * myGrid.getFontSize() + 0.5);
  Font f = new Font("Dialog", Font.PLAIN, size); //$NON-NLS-1$

  Color fg = selected ? Color.white : Color.black;
  Color bg = selected ? Color.black : Color.white;

  Rectangle region = bounds.intersection(visibleRect);

  Shape oldClip = g.getClip();
  if (oldClip != null) {
    Area clipArea = new Area(oldClip);
    clipArea.intersect(new Area(region));
    g.setClip(clipArea);
  }

  int posX = (int) (scale * origin.x + 0.5) + bounds.x - 1 + xOffset;
  int posY = (int) (scale * origin.y + 0.5) + bounds.y - 1 + yOffset;

  Color saveColor = g.getColor();

  g.setColor(bg);
  g.fillRect(posX, posY, 3, 3);
  g.setColor(fg);
  g.drawRect(posX, posY, 3, 3);

  g.setColor(saveColor);

  Labeler.drawLabel(g, getLocalizedConfigureName(), posX, posY + labelOffset, f, Labeler.CENTER,
                    Labeler.TOP, fg, bg, fg);
  g.setClip(oldClip);

  // Calculate and store the selection rectangle
  int width = g.getFontMetrics().stringWidth(getConfigureName() + "  ")+1; //$NON-NLS-1$
  int height = g.getFontMetrics().getHeight()+1;

  selectionRect.setLocation(posX - (width / 2), posY - 1);
  selectionRect.setSize(width, height + labelOffset + 1);

}
 
Example 15
Project: OpenJSharp   File: RepaintArea.java   View Source Code Vote up 4 votes
/**
 * Invokes paint and update on target Component with optimal
 * rectangular clip region.
 * If PAINT bounding rectangle is less than
 * MAX_BENEFIT_RATIO times the benefit, then the vertical and horizontal unions are
 * painted separately.  Otherwise the entire bounding rectangle is painted.
 *
 * @param   target Component to <code>paint</code> or <code>update</code>
 * @since   1.4
 */
public void paint(Object target, boolean shouldClearRectBeforePaint) {
    Component comp = (Component)target;

    if (isEmpty()) {
        return;
    }

    if (!comp.isVisible()) {
        return;
    }

    RepaintArea ra = this.cloneAndReset();

    if (!subtract(ra.paintRects[VERTICAL], ra.paintRects[HORIZONTAL])) {
        subtract(ra.paintRects[HORIZONTAL], ra.paintRects[VERTICAL]);
    }

    if (ra.paintRects[HORIZONTAL] != null && ra.paintRects[VERTICAL] != null) {
        Rectangle paintRect = ra.paintRects[HORIZONTAL].union(ra.paintRects[VERTICAL]);
        int square = paintRect.width * paintRect.height;
        int benefit = square - ra.paintRects[HORIZONTAL].width
            * ra.paintRects[HORIZONTAL].height - ra.paintRects[VERTICAL].width
            * ra.paintRects[VERTICAL].height;
        // if benefit is comparable with bounding box
        if (MAX_BENEFIT_RATIO * benefit < square) {
            ra.paintRects[HORIZONTAL] = paintRect;
            ra.paintRects[VERTICAL] = null;
        }
    }
    for (int i = 0; i < paintRects.length; i++) {
        if (ra.paintRects[i] != null
            && !ra.paintRects[i].isEmpty())
        {
            // Should use separate Graphics for each paint() call,
            // since paint() can change Graphics state for next call.
            Graphics g = comp.getGraphics();
            if (g != null) {
                try {
                    g.setClip(ra.paintRects[i]);
                    if (i == UPDATE) {
                        updateComponent(comp, g);
                    } else {
                        if (shouldClearRectBeforePaint) {
                            g.clearRect( ra.paintRects[i].x,
                                         ra.paintRects[i].y,
                                         ra.paintRects[i].width,
                                         ra.paintRects[i].height);
                        }
                        paintComponent(comp, g);
                    }
                } finally {
                    g.dispose();
                }
            }
        }
    }
}
 
Example 16
Project: TrabalhoFinalEDA2   File: mxGraph.java   View Source Code Vote up 4 votes
/**
 * Draws the cell state with the given label onto the canvas. No
 * children or descendants are painted here. This method invokes
 * cellDrawn after the cell, but not its descendants have been
 * painted.
 * 
 * @param canvas Canvas onto which the cell should be drawn.
 * @param state State of the cell to be drawn.
 * @param drawLabel Indicates if the label should be drawn.
 */
public void drawState(mxICanvas canvas, mxCellState state, boolean drawLabel)
{
	Object cell = (state != null) ? state.getCell() : null;

	if (cell != null && cell != view.getCurrentRoot()
			&& cell != model.getRoot()
			&& (model.isVertex(cell) || model.isEdge(cell)))
	{
		Object obj = canvas.drawCell(state);
		Object lab = null;

		// Holds the current clipping region in case the label will
		// be clipped
		Shape clip = null;
		Rectangle newClip = state.getRectangle();

		// Indirection for image canvas that contains a graphics canvas
		mxICanvas clippedCanvas = (isLabelClipped(state.getCell())) ? canvas
				: null;

		if (clippedCanvas instanceof mxImageCanvas)
		{
			clippedCanvas = ((mxImageCanvas) clippedCanvas)
					.getGraphicsCanvas();
			// TODO: Shift newClip to match the image offset
			//Point pt = ((mxImageCanvas) canvas).getTranslate();
			//newClip.translate(-pt.x, -pt.y);
		}

		if (clippedCanvas instanceof mxGraphics2DCanvas)
		{
			Graphics g = ((mxGraphics2DCanvas) clippedCanvas).getGraphics();
			clip = g.getClip();

			// Ensure that our new clip resides within our old clip
			if (clip instanceof Rectangle)
			{
				g.setClip(newClip.intersection((Rectangle) clip));
			}
			// Otherwise, default to original implementation
			else
			{
				g.setClip(newClip);
			}
		}

		if (drawLabel)
		{
			String label = state.getLabel();

			if (label != null && state.getLabelBounds() != null)
			{
				lab = canvas.drawLabel(label, state, isHtmlLabel(cell));
			}
		}

		// Restores the previous clipping region
		if (clippedCanvas instanceof mxGraphics2DCanvas)
		{
			((mxGraphics2DCanvas) clippedCanvas).getGraphics()
					.setClip(clip);
		}

		// Invokes the cellDrawn callback with the object which was created
		// by the canvas to represent the cell graphically
		if (obj != null)
		{
			cellDrawn(canvas, state, obj, lab);
		}
	}
}
 
Example 17
Project: Tarski   File: mxGraph.java   View Source Code Vote up 4 votes
/**
 * Draws the cell state with the given label onto the canvas. No children or descendants are
 * painted here. This method invokes cellDrawn after the cell, but not its descendants have been
 * painted.
 *
 * @param canvas Canvas onto which the cell should be drawn.
 * @param state State of the cell to be drawn.
 * @param drawLabel Indicates if the label should be drawn.
 */
public void drawState(final mxICanvas canvas, final mxCellState state, final boolean drawLabel) {
  final Object cell = state != null ? state.getCell() : null;

  if (cell != null && cell != this.view.getCurrentRoot() && cell != this.model.getRoot()
      && (this.model.isVertex(cell) || this.model.isEdge(cell))) {
    final Object obj = canvas.drawCell(state);
    Object lab = null;

    // Holds the current clipping region in case the label will
    // be clipped
    Shape clip = null;
    final Rectangle newClip = state.getRectangle();

    // Indirection for image canvas that contains a graphics canvas
    mxICanvas clippedCanvas = this.isLabelClipped(state.getCell()) ? canvas : null;

    if (clippedCanvas instanceof mxImageCanvas) {
      clippedCanvas = ((mxImageCanvas) clippedCanvas).getGraphicsCanvas();
      // TODO: Shift newClip to match the image offset
      // Point pt = ((mxImageCanvas) canvas).getTranslate();
      // newClip.translate(-pt.x, -pt.y);
    }

    if (clippedCanvas instanceof mxGraphics2DCanvas) {
      final Graphics g = ((mxGraphics2DCanvas) clippedCanvas).getGraphics();
      clip = g.getClip();

      // Ensure that our new clip resides within our old clip
      if (clip instanceof Rectangle) {
        g.setClip(newClip.intersection((Rectangle) clip));
      }
      // Otherwise, default to original implementation
      else {
        g.setClip(newClip);
      }
    }

    if (drawLabel) {
      final String label = state.getLabel();

      if (label != null && state.getLabelBounds() != null) {
        lab = canvas.drawLabel(label, state, this.isHtmlLabel(cell));
      }
    }

    // Restores the previous clipping region
    if (clippedCanvas instanceof mxGraphics2DCanvas) {
      ((mxGraphics2DCanvas) clippedCanvas).getGraphics().setClip(clip);
    }

    // Invokes the cellDrawn callback with the object which was created
    // by the canvas to represent the cell graphically
    if (obj != null) {
      this.cellDrawn(canvas, state, obj, lab);
    }
  }
}
 
Example 18
Project: Tarski   File: mxGraphComponent.java   View Source Code Vote up 4 votes
/**
 * Prints the specified page on the specified graphics using <code>pageFormat</code> for the page
 * format.
 * 
 * @param g The graphics to paint the graph on.
 * @param printFormat The page format to use for printing.
 * @param page The page to print
 * @return Returns {@link Printable#PAGE_EXISTS} or {@link Printable#NO_SUCH_PAGE}.
 */
public int print(Graphics g, PageFormat printFormat, int page) {
  int result = NO_SUCH_PAGE;

  // Disables double-buffering before printing
  RepaintManager currentManager = RepaintManager.currentManager(mxGraphComponent.this);
  currentManager.setDoubleBufferingEnabled(false);

  // Gets the current state of the view
  mxGraphView view = graph.getView();

  // Stores the old state of the view
  boolean eventsEnabled = view.isEventsEnabled();
  mxPoint translate = view.getTranslate();

  // Disables firing of scale events so that there is no
  // repaint or update of the original graph while pages
  // are being printed
  view.setEventsEnabled(false);

  // Uses the view to create temporary cell states for each cell
  mxTemporaryCellStates tempStates = new mxTemporaryCellStates(view, 1 / pageScale);

  try {
    view.setTranslate(new mxPoint(0, 0));

    mxGraphics2DCanvas canvas = createCanvas();
    canvas.setGraphics((Graphics2D) g);
    canvas.setScale(1 / pageScale);

    view.revalidate();

    mxRectangle graphBounds = graph.getGraphBounds();
    Dimension pSize =
        new Dimension((int) Math.ceil(graphBounds.getX() + graphBounds.getWidth()) + 1,
            (int) Math.ceil(graphBounds.getY() + graphBounds.getHeight()) + 1);

    int w = (int) (printFormat.getImageableWidth());
    int h = (int) (printFormat.getImageableHeight());
    int cols = (int) Math.max(Math.ceil((double) (pSize.width - 5) / (double) w), 1);
    int rows = (int) Math.max(Math.ceil((double) (pSize.height - 5) / (double) h), 1);

    if (page < cols * rows) {
      int dx = (int) ((page % cols) * printFormat.getImageableWidth());
      int dy = (int) (Math.floor(page / cols) * printFormat.getImageableHeight());

      g.translate(-dx + (int) printFormat.getImageableX(),
          -dy + (int) printFormat.getImageableY());
      g.setClip(dx, dy, (int) (dx + printFormat.getWidth()),
          (int) (dy + printFormat.getHeight()));

      graph.drawGraph(canvas);

      result = PAGE_EXISTS;
    }
  } finally {
    view.setTranslate(translate);

    tempStates.destroy();
    view.setEventsEnabled(eventsEnabled);

    // Enables double-buffering after printing
    currentManager.setDoubleBufferingEnabled(true);
  }

  return result;
}
 
Example 19
Project: jdk8u-jdk   File: RepaintArea.java   View Source Code Vote up 4 votes
/**
 * Invokes paint and update on target Component with optimal
 * rectangular clip region.
 * If PAINT bounding rectangle is less than
 * MAX_BENEFIT_RATIO times the benefit, then the vertical and horizontal unions are
 * painted separately.  Otherwise the entire bounding rectangle is painted.
 *
 * @param   target Component to <code>paint</code> or <code>update</code>
 * @since   1.4
 */
public void paint(Object target, boolean shouldClearRectBeforePaint) {
    Component comp = (Component)target;

    if (isEmpty()) {
        return;
    }

    if (!comp.isVisible()) {
        return;
    }

    RepaintArea ra = this.cloneAndReset();

    if (!subtract(ra.paintRects[VERTICAL], ra.paintRects[HORIZONTAL])) {
        subtract(ra.paintRects[HORIZONTAL], ra.paintRects[VERTICAL]);
    }

    if (ra.paintRects[HORIZONTAL] != null && ra.paintRects[VERTICAL] != null) {
        Rectangle paintRect = ra.paintRects[HORIZONTAL].union(ra.paintRects[VERTICAL]);
        int square = paintRect.width * paintRect.height;
        int benefit = square - ra.paintRects[HORIZONTAL].width
            * ra.paintRects[HORIZONTAL].height - ra.paintRects[VERTICAL].width
            * ra.paintRects[VERTICAL].height;
        // if benefit is comparable with bounding box
        if (MAX_BENEFIT_RATIO * benefit < square) {
            ra.paintRects[HORIZONTAL] = paintRect;
            ra.paintRects[VERTICAL] = null;
        }
    }
    for (int i = 0; i < paintRects.length; i++) {
        if (ra.paintRects[i] != null
            && !ra.paintRects[i].isEmpty())
        {
            // Should use separate Graphics for each paint() call,
            // since paint() can change Graphics state for next call.
            Graphics g = comp.getGraphics();
            if (g != null) {
                try {
                    g.setClip(ra.paintRects[i]);
                    if (i == UPDATE) {
                        updateComponent(comp, g);
                    } else {
                        if (shouldClearRectBeforePaint) {
                            g.clearRect( ra.paintRects[i].x,
                                         ra.paintRects[i].y,
                                         ra.paintRects[i].width,
                                         ra.paintRects[i].height);
                        }
                        paintComponent(comp, g);
                    }
                } finally {
                    g.dispose();
                }
            }
        }
    }
}
 
Example 20
Project: openjdk-jdk10   File: RepaintArea.java   View Source Code Vote up 4 votes
/**
 * Invokes paint and update on target Component with optimal
 * rectangular clip region.
 * If PAINT bounding rectangle is less than
 * MAX_BENEFIT_RATIO times the benefit, then the vertical and horizontal unions are
 * painted separately.  Otherwise the entire bounding rectangle is painted.
 *
 * @param   target Component to {@code paint} or {@code update}
 * @since   1.4
 */
public void paint(Object target, boolean shouldClearRectBeforePaint) {
    Component comp = (Component)target;

    if (isEmpty()) {
        return;
    }

    if (!comp.isVisible()) {
        return;
    }

    RepaintArea ra = this.cloneAndReset();

    if (!subtract(ra.paintRects[VERTICAL], ra.paintRects[HORIZONTAL])) {
        subtract(ra.paintRects[HORIZONTAL], ra.paintRects[VERTICAL]);
    }

    if (ra.paintRects[HORIZONTAL] != null && ra.paintRects[VERTICAL] != null) {
        Rectangle paintRect = ra.paintRects[HORIZONTAL].union(ra.paintRects[VERTICAL]);
        int square = paintRect.width * paintRect.height;
        int benefit = square - ra.paintRects[HORIZONTAL].width
            * ra.paintRects[HORIZONTAL].height - ra.paintRects[VERTICAL].width
            * ra.paintRects[VERTICAL].height;
        // if benefit is comparable with bounding box
        if (MAX_BENEFIT_RATIO * benefit < square) {
            ra.paintRects[HORIZONTAL] = paintRect;
            ra.paintRects[VERTICAL] = null;
        }
    }
    for (int i = 0; i < paintRects.length; i++) {
        if (ra.paintRects[i] != null
            && !ra.paintRects[i].isEmpty())
        {
            // Should use separate Graphics for each paint() call,
            // since paint() can change Graphics state for next call.
            Graphics g = comp.getGraphics();
            if (g != null) {
                try {
                    g.setClip(ra.paintRects[i]);
                    if (i == UPDATE) {
                        updateComponent(comp, g);
                    } else {
                        if (shouldClearRectBeforePaint) {
                            g.clearRect( ra.paintRects[i].x,
                                         ra.paintRects[i].y,
                                         ra.paintRects[i].width,
                                         ra.paintRects[i].height);
                        }
                        paintComponent(comp, g);
                    }
                } finally {
                    g.dispose();
                }
            }
        }
    }
}