List of usage examples for java.awt.geom Point2D getY
public abstract double getY();
From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java
private void validatePerimeter(Point2D l1p1, Point2D l1p2, Point2D l2p1, Point2D l2p2, HmPerimeterInvalidPointsVo vo) throws Exception { Point2D ip = llis(l1p1, l1p2, l2p1, l2p2); if (ip != null) { vo.addInvalidPoint(ip.getX(), ip.getY()); }//from w w w. j a v a 2 s. c o m }
From source file:org.apache.fop.render.bitmap.AbstractBitmapDocumentHandler.java
/** {@inheritDoc} */ public IFPainter startPageContent() throws IFException { int bitmapWidth; int bitmapHeight; double scale; Point2D offset = null; if (targetBitmapSize != null) { //Fit the generated page proportionally into the given rectangle (in pixels) double scale2w = 1000 * targetBitmapSize.width / this.currentPageDimensions.getWidth(); double scale2h = 1000 * targetBitmapSize.height / this.currentPageDimensions.getHeight(); bitmapWidth = targetBitmapSize.width; bitmapHeight = targetBitmapSize.height; //Centering the page in the given bitmap offset = new Point2D.Double(); if (scale2w < scale2h) { scale = scale2w;//from w w w .j a v a 2 s .c om double h = this.currentPageDimensions.height * scale / 1000; offset.setLocation(0, (bitmapHeight - h) / 2.0); } else { scale = scale2h; double w = this.currentPageDimensions.width * scale / 1000; offset.setLocation((bitmapWidth - w) / 2.0, 0); } } else { //Normal case: just scale according to the target resolution scale = scaleFactor * getUserAgent().getTargetResolution() / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION; bitmapWidth = (int) ((this.currentPageDimensions.width * scale / 1000f) + 0.5f); bitmapHeight = (int) ((this.currentPageDimensions.height * scale / 1000f) + 0.5f); } //Set up bitmap to paint on this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight); Graphics2D graphics2D = this.currentImage.createGraphics(); // draw page background if (!getSettings().hasTransparentPageBackground()) { graphics2D.setBackground(getSettings().getPageBackgroundColor()); graphics2D.setPaint(getSettings().getPageBackgroundColor()); graphics2D.fillRect(0, 0, bitmapWidth, bitmapHeight); } //Set rendering hints graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); if (getSettings().isAntiAliasingEnabled() && this.currentImage.getColorModel().getPixelSize() > 1) { graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } else { graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } if (getSettings().isQualityRenderingEnabled()) { graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); } else { graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); } graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); //Set up initial coordinate system for the page if (offset != null) { graphics2D.translate(offset.getX(), offset.getY()); } graphics2D.scale(scale / 1000f, scale / 1000f); return new Java2DPainter(graphics2D, getContext(), getFontInfo()); }
From source file:gda.plots.SimplePlot.java
/** * Recalculates the rectangle which should be magnified. * //from w w w . ja v a2 s .c o m * @param e * the MouseEvent which triggered the recalculation */ private void recalculateMagnifyRectangle(MouseEvent e) { if (magnifyWidth == 0 || magnifyHeight == 0) return; Rectangle2D scaledDataArea = getScreenDataArea(); double widthToUse; double heightToUse; double xToUse; double yToUse; // If magnifyWidth is positive then e.getX() is // the end of the rectangle so the start is (e.getX() - magnifyWidth ). // If magnifyWidth is negative then e.getX() is the start of a // rectangle with the opposite sign width. Similarly for y. if (magnifyWidth > 0) { xToUse = e.getX() - magnifyWidth; widthToUse = magnifyWidth; } else { xToUse = e.getX(); widthToUse = -1.0 * magnifyWidth; } if (magnifyHeight > 0) { yToUse = e.getY() - magnifyHeight; heightToUse = magnifyHeight; } else { yToUse = e.getY(); heightToUse = -1.0 * magnifyHeight; } // xToUse and yToUse now specify the top left of the rectangle. In order // to keep the magnified rectangle inside the data area the start point // must be inside a rectangle which is the scaledDataArea reduced in // width // and height by the width and height of the magnifyRectangle. Point2D revisedStartPoint = ShapeUtilities.getPointInRectangle(xToUse, yToUse, new Rectangle2D.Double(scaledDataArea.getMinX(), scaledDataArea.getMinY(), scaledDataArea.getWidth() - magnifyWidth, scaledDataArea.getHeight() - magnifyHeight)); magnifyRectangle = new Rectangle2D.Double(revisedStartPoint.getX(), revisedStartPoint.getY(), widthToUse, heightToUse); }
From source file:com.joliciel.jochre.graphics.SegmenterImpl.java
/** * Detects paragraph splits and assign rows to correct paragraphs. * @param sourceImage// w w w. ja v a2 s . c om */ void groupRowsIntoParagraphs(SourceImage sourceImage) { LOG.debug("########## groupRowsIntoParagraphs #########"); // We'll use various possible indicators, including // indented start, indented end, and spacing between rows. // On pages with a single big paragraph makes it hypersensitive to differences in row-start/row-end // This means we cannot use deviation. Instead, we use the average shape width on the page. // We also adjust maxLeft & minRight to match the vertical line slope // This is now complicated by the possibility of multiple columns // Need to take into account a big horizontal space - Pietrushka page 14 // Find horizontal spaces that go all the way across and are wider than a certain threshold // simply do a boolean column and black out everything in a row, than see if there are any remaining spaces above a certain threshold // Columns are thus arranged into "areas", separated by white-space. boolean[] fullRows = new boolean[sourceImage.getHeight()]; for (RowOfShapes row : sourceImage.getRows()) { for (int y = row.getTop(); y <= row.getBottom(); y++) { fullRows[y] = true; } } DescriptiveStatistics rowHeightStats = new DescriptiveStatistics(); for (RowOfShapes row : sourceImage.getRows()) { int height = row.getXHeight(); rowHeightStats.addValue(height); } double avgRowHeight = rowHeightStats.getPercentile(50); LOG.debug("meanRowHeight: " + avgRowHeight); double minHeightForWhiteSpace = avgRowHeight * 1.3; LOG.debug("minHeightForWhiteSpace: " + minHeightForWhiteSpace); // find the "white rows" - any horizontal white space // in the page which is sufficiently high List<int[]> whiteRows = new ArrayList<int[]>(); boolean inWhite = false; int startWhite = 0; for (int y = 0; y < sourceImage.getHeight(); y++) { if (!inWhite && !fullRows[y]) { inWhite = true; startWhite = y; } else if (inWhite && fullRows[y]) { int length = y - startWhite; if (length > minHeightForWhiteSpace) { LOG.debug("Adding whiteRow " + startWhite + "," + (y - 1)); whiteRows.add(new int[] { startWhite, y - 1 }); } inWhite = false; } } if (inWhite) whiteRows.add(new int[] { startWhite, sourceImage.getHeight() - 1 }); whiteRows.add(new int[] { sourceImage.getHeight(), sourceImage.getHeight() }); // place rows in "areas" defined by the "white rows" found above List<List<RowOfShapes>> areas = new ArrayList<List<RowOfShapes>>(); int startY = -1; for (int[] whiteRow : whiteRows) { List<RowOfShapes> area = new ArrayList<RowOfShapes>(); for (RowOfShapes row : sourceImage.getRows()) { if (row.getTop() >= startY && row.getBottom() <= whiteRow[0]) { area.add(row); } } if (area.size() > 0) { areas.add(area); } startY = whiteRow[1]; } // break up each area into vertical columns LOG.debug("break up each area into vertical columns"); List<Column> columns = new ArrayList<Column>(); List<List<Column>> columnsPerAreaList = new ArrayList<List<Column>>(); for (List<RowOfShapes> area : areas) { LOG.debug("Next area"); List<Column> columnsPerArea = new ArrayList<SegmenterImpl.Column>(); columnsPerAreaList.add(columnsPerArea); TreeSet<RowOfShapes> rows = new TreeSet<RowOfShapes>(new RowOfShapesVerticalLocationComparator()); rows.addAll(area); for (RowOfShapes row : rows) { // try to place this row in one of the columns directly above it. // this means that a row which overlaps more than one column has to "close" this column, so it is no longer considered List<Column> overlappingColumns = new ArrayList<Column>(); for (Column column : columnsPerArea) { if (!column.closed) { RowOfShapes lastRowInColumn = column.get(column.size() - 1); if (row.getRight() - row.getXAdjustment() >= lastRowInColumn.getLeft() - lastRowInColumn.getXAdjustment() && row.getLeft() - row.getXAdjustment() <= lastRowInColumn.getRight() - lastRowInColumn.getXAdjustment()) { overlappingColumns.add(column); } } } if (overlappingColumns.size() == 1) { Column myColumn = overlappingColumns.get(0); RowOfShapes lastRowInMyColumn = myColumn.get(0); // close any columns that are now at a distance of more than one row for (Column column : columnsPerArea) { if (!column.closed && !column.equals(myColumn)) { RowOfShapes lastRowInColumn = column.get(column.size() - 1); if (lastRowInMyColumn.getTop() > lastRowInColumn.getBottom()) { column.closed = true; LOG.debug("Closing distant column " + lastRowInColumn); } } } myColumn.add(row); LOG.debug(row.toString()); LOG.debug(" added to column " + lastRowInMyColumn); } else { for (Column overlappingColumn : overlappingColumns) { overlappingColumn.closed = true; RowOfShapes lastRowInColumn = overlappingColumn.get(overlappingColumn.size() - 1); LOG.debug("Closing overlapping column " + lastRowInColumn); } Column myColumn = new Column(sourceImage); myColumn.add(row); LOG.debug("Found new column"); LOG.debug(row.toString()); columns.add(myColumn); columnsPerArea.add(myColumn); } } } // next area for (Column column : columns) column.recalculate(); // Intermediate step to reform the vertical columns, if they exist // basically the idea is that if the columns are aligned vertically, then the thresholds for paragraph indents // should be shared, to increase the statistical sample size and reduce anomalies. // We'll assume that two columns from two consecutive areas are in the same vertical group if they overlap with each other horizontally // and don't overlap with any other column in the other column's area. List<List<Column>> columnGroups = new ArrayList<List<Column>>(); List<Column> columnsInPrevArea = null; for (List<Column> columnsPerArea : columnsPerAreaList) { if (columnsInPrevArea != null) { for (Column prevColumn : columnsInPrevArea) { LOG.debug("Checking " + prevColumn); // find the column group containing the previous column List<Column> myColumnGroup = null; for (List<Column> columnGroup : columnGroups) { if (columnGroup.contains(prevColumn)) { myColumnGroup = columnGroup; break; } } if (myColumnGroup == null) { myColumnGroup = new ArrayList<SegmenterImpl.Column>(); LOG.debug("Creating column group for column " + prevColumn.toString()); columnGroups.add(myColumnGroup); myColumnGroup.add(prevColumn); } // does only one column overlap with this one? Column overlappingColumn = null; for (Column column : columnsPerArea) { if (column.adjustedRight >= prevColumn.adjustedLeft && column.adjustedLeft <= prevColumn.adjustedRight) { if (overlappingColumn == null) { LOG.debug("I overlap with " + column); overlappingColumn = column; } else { LOG.debug("But I overlap also with " + column); overlappingColumn = null; break; } } } if (overlappingColumn != null) { // does it overlap with only me? for (Column otherPrevColumn : columnsInPrevArea) { if (otherPrevColumn.equals(prevColumn)) continue; if (overlappingColumn.adjustedRight >= otherPrevColumn.adjustedLeft && overlappingColumn.adjustedLeft <= otherPrevColumn.adjustedRight) { LOG.debug("But it overlaps also with " + otherPrevColumn); overlappingColumn = null; break; } } } if (overlappingColumn != null) { myColumnGroup.add(overlappingColumn); LOG.debug("Adding " + overlappingColumn); LOG.debug(" to group with " + prevColumn); } } // next previous column } // have previous columns columnsInPrevArea = columnsPerArea; } // next area if (columnsInPrevArea != null) { for (Column prevColumn : columnsInPrevArea) { // find the column group containing the previous column List<Column> myColumnGroup = null; for (List<Column> columnGroup : columnGroups) { if (columnGroup.contains(prevColumn)) { myColumnGroup = columnGroup; break; } } if (myColumnGroup == null) { myColumnGroup = new ArrayList<SegmenterImpl.Column>(); LOG.debug("Creating column group for column " + prevColumn.toString()); columnGroups.add(myColumnGroup); myColumnGroup.add(prevColumn); } } } // What we really want here is, for each column (in the case of right-to-left), // two clusters on the right // and one relatively big cluster on the left. // anything outside of the cluster on the left is an EOP. boolean hasTab = false; for (List<Column> columnGroup : columnGroups) { LOG.debug("Next column group"); double averageShapeWidth = sourceImage.getAverageShapeWidth(); LOG.debug("averageShapeWidth: " + averageShapeWidth); double epsilon = averageShapeWidth / 2.0; LOG.debug("epsilon: " + epsilon); int columnGroupTop = sourceImage.getHeight(); int columnGroupBottom = 0; int columnGroupLeft = sourceImage.getWidth(); int columnGroupRight = 0; for (Column column : columnGroup) { if (column.top < columnGroupTop) columnGroupTop = (int) Math.round(column.top); if (column.bottom > columnGroupBottom) columnGroupBottom = (int) Math.round(column.bottom); if (column.adjustedLeft < columnGroupLeft) columnGroupLeft = (int) Math.round(column.adjustedLeft); if (column.adjustedRight > columnGroupRight) columnGroupRight = (int) Math.round(column.adjustedRight); } // right thresholds LOG.debug("Calculating right thresholds"); // first, create a DBScan cluster of all rows by their adjusted right coordinate List<RowOfShapes> rightHandRows = new ArrayList<RowOfShapes>(); List<double[]> rightCoordinates = new ArrayList<double[]>(); for (Column column : columnGroup) { for (RowOfShapes row : column) { double right = row.getRight() - row.getXAdjustment(); // double rightOverlap = this.findLargeShapeOverlapOnRight(row, column, sourceImage); // if (rightOverlap==0) { // // leave out any right-overlapping rows here // // since we need accurate statistics for margin detection // // This is questionable - especially since a long vertical bar (see Petriushka) // // tends to give all rows a left overlap. Also, because the overlap is calculated based // // on the mean right & mean left, not based on any sort of margin clusters. // rightHandRows.add(row); // rightCoordinates.add(new double[] {right}); // } rightHandRows.add(row); rightCoordinates.add(new double[] { right }); } } int minCardinalityForRightMargin = 5; DBSCANClusterer<RowOfShapes> rightMarginClusterer = new DBSCANClusterer<RowOfShapes>(rightHandRows, rightCoordinates); Set<Set<RowOfShapes>> rowClusters = rightMarginClusterer.cluster(epsilon, minCardinalityForRightMargin, true); TreeSet<Set<RowOfShapes>> orderedRowClusters = new TreeSet<Set<RowOfShapes>>( new CardinalityComparator<RowOfShapes>()); orderedRowClusters.addAll(rowClusters); int i = 0; // find the two right-most clusters, and assume they are the margin & the tab DescriptiveStatistics rightMarginStats = null; DescriptiveStatistics rightTabStats = null; for (Set<RowOfShapes> cluster : orderedRowClusters) { DescriptiveStatistics rightStats = new DescriptiveStatistics(); MeanAbsoluteDeviation rightDev = new MeanAbsoluteDeviation(); for (RowOfShapes row : cluster) { int rowIndex = rightHandRows.indexOf(row); double right = rightCoordinates.get(rowIndex)[0]; rightStats.addValue(right); rightDev.increment(right); } LOG.debug("Cluster " + i + ". Cardinality=" + cluster.size()); LOG.debug("Right mean : " + rightStats.getMean()); LOG.debug("Right dev: " + rightDev.getResult()); if (cluster.size() >= minCardinalityForRightMargin) { if (rightMarginStats == null || rightMarginStats.getMean() < rightStats.getMean()) { if (rightMarginStats != null) rightTabStats = rightMarginStats; rightMarginStats = rightStats; } else if (rightTabStats == null || rightTabStats.getMean() < rightStats.getMean()) { rightTabStats = rightStats; } } else { break; } i++; } // next right-coordinate cluster double rightMargin = sourceImage.getWidth(); double rightTab = sourceImage.getWidth(); if (rightMarginStats != null) { rightMargin = rightMarginStats.getMean(); } else { List<Rectangle> columnSeparators = sourceImage.findColumnSeparators(); for (Rectangle columnSeparator : columnSeparators) { if (columnSeparator.getTop() <= columnGroupTop && columnSeparator.getBottom() >= columnGroupBottom && columnSeparator.getLeft() >= columnGroupRight) { if (columnSeparator.getLeft() < rightMargin) rightMargin = columnSeparator.getLeft(); } } } if (rightTabStats != null) { rightTab = rightTabStats.getMean(); } LOG.debug("rightMargin: " + rightMargin); LOG.debug("rightTab: " + rightTab); // left thresholds LOG.debug("Calculating left thresholds"); // first, create a DBScan cluster of all rows by their adjusted left coordinate List<RowOfShapes> leftHandRows = new ArrayList<RowOfShapes>(); List<double[]> leftCoordinates = new ArrayList<double[]>(); for (Column column : columnGroup) { for (RowOfShapes row : column) { double left = row.getLeft() - row.getXAdjustment(); // double leftOverlap = this.findLargeShapeOverlapOnLeft(row, column, sourceImage); // if (leftOverlap == 0) { // // leave out any overlapping rows from margin calcs, // // since we need accurate statistics here // leftHandRows.add(row); // leftCoordinates.add(new double[] {left}); // } leftHandRows.add(row); leftCoordinates.add(new double[] { left }); } } int minCardinalityForLeftMargin = 5; DBSCANClusterer<RowOfShapes> leftMarginClusterer = new DBSCANClusterer<RowOfShapes>(leftHandRows, leftCoordinates); Set<Set<RowOfShapes>> leftRowClusters = leftMarginClusterer.cluster(epsilon, minCardinalityForLeftMargin, true); TreeSet<Set<RowOfShapes>> orderedLeftRowClusters = new TreeSet<Set<RowOfShapes>>( new CardinalityComparator<RowOfShapes>()); orderedLeftRowClusters.addAll(leftRowClusters); i = 0; // find the two left-most clusters, and assume they are the margin & the tab DescriptiveStatistics leftMarginStats = null; DescriptiveStatistics leftTabStats = null; for (Set<RowOfShapes> cluster : orderedLeftRowClusters) { DescriptiveStatistics leftStats = new DescriptiveStatistics(); MeanAbsoluteDeviation leftDev = new MeanAbsoluteDeviation(); for (RowOfShapes row : cluster) { int rowIndex = leftHandRows.indexOf(row); double left = leftCoordinates.get(rowIndex)[0]; leftStats.addValue(left); leftDev.increment(left); } LOG.debug("Cluster " + i + ". Cardinality=" + cluster.size()); LOG.debug("Left mean : " + leftStats.getMean()); LOG.debug("Left dev: " + leftDev.getResult()); if (cluster.size() >= minCardinalityForLeftMargin) { if (leftMarginStats == null || leftMarginStats.getMean() > leftStats.getMean()) { if (leftMarginStats != null) leftTabStats = leftMarginStats; leftMarginStats = leftStats; } else if (leftTabStats == null || leftTabStats.getMean() > leftStats.getMean()) { leftTabStats = leftStats; } } else { break; } i++; } // next left-coordinate cluster double leftMargin = 0; double leftTab = 0; if (leftMarginStats != null) { leftMargin = leftMarginStats.getMean(); } else { List<Rectangle> columnSeparators = sourceImage.findColumnSeparators(); for (Rectangle columnSeparator : columnSeparators) { if (columnSeparator.getTop() <= columnGroupTop && columnSeparator.getBottom() >= columnGroupBottom && columnSeparator.getRight() <= columnGroupLeft) { if (columnSeparator.getRight() > leftMargin) leftMargin = columnSeparator.getRight(); } } } if (leftTabStats != null) { leftTab = leftTabStats.getMean(); } LOG.debug("leftMargin: " + leftMargin); LOG.debug("leftTab: " + leftTab); for (Column column : columnGroup) { if (sourceImage.isLeftToRight()) { column.startMargin = leftMargin; if (leftTabStats != null) { column.startTab = leftTab; column.hasTab = true; } else { LOG.debug("No left tab - setting based on left margin"); column.startTab = leftMargin + (5.0 * sourceImage.getAverageShapeWidth()); column.hasTab = false; } column.endMargin = rightMargin; } else { column.startMargin = rightMargin; if (rightTabStats != null) { column.startTab = rightTab; column.hasTab = true; } else { LOG.debug("No right tab - setting based on right margin"); column.startTab = rightMargin - (5.0 * sourceImage.getAverageShapeWidth()); column.hasTab = false; } column.endMargin = leftMargin; } LOG.debug("Margins for " + column); LOG.debug("startMargin: " + column.startMargin); LOG.debug("startTab: " + column.startTab); LOG.debug("endMargin: " + column.endMargin); } // next column } // next column group LOG.debug("hasTab: " + hasTab); double safetyMargin = 1.5 * sourceImage.getAverageShapeWidth(); // Now, paragraphs are either "indented", "outdented" or not "dented" at all (no tabs). // This applies to the entire page. // To recognise indenting vs. outdenting, we have to see if the row preceding each // indent/outdent is full or partial. In the case of indentation, partial rows will // typically be followed by an indent. In the case of outdentation, partial rows will // typically be followed by an outdent. boolean isIndented = true; int indentCount = 0; int outdentCount = 0; for (List<Column> columnGroup : columnGroups) { LOG.debug("Next column group"); boolean prevRowPartial = false; for (Column column : columnGroup) { if (column.hasTab) { for (RowOfShapes row : column) { if (sourceImage.isLeftToRight()) { if (prevRowPartial) { if (row.getLeft() - row.getXAdjustment() > column.startTab - safetyMargin) { indentCount++; } else if (row.getLeft() - row.getXAdjustment() < column.startMargin + safetyMargin) { outdentCount++; } } if (row.getRight() - row.getXAdjustment() < column.endMargin - safetyMargin) { prevRowPartial = true; } else { prevRowPartial = false; } } else { if (prevRowPartial) { if (row.getRight() - row.getXAdjustment() < column.startTab + safetyMargin) { indentCount++; } else if (row.getRight() - row.getXAdjustment() > column.startMargin - safetyMargin) { outdentCount++; } } if (row.getLeft() - row.getXAdjustment() > column.endMargin + safetyMargin) { prevRowPartial = true; } else { prevRowPartial = false; } } // left-to-right? } // next row } // column has tab } // next column } // next column group isIndented = (indentCount + 2 >= outdentCount); LOG.debug("indentCount: " + indentCount); LOG.debug("outdentCount: " + outdentCount); LOG.debug("isIndented: " + isIndented); // order the columns TreeSet<Column> orderedColumns = new TreeSet<SegmenterImpl.Column>(columns); columns.clear(); columns.addAll(orderedColumns); // find the paragraphs found in each column for (Column column : columns) { LOG.debug("--- Next column ---"); // break up the column into paragraphs Paragraph paragraph = null; RowOfShapes previousRow = null; int maxShapesForStandaloneParagraph = 2; List<RowOfShapes> rowsForStandaloneParagraphs = new ArrayList<RowOfShapes>(); Point2D previousPointStartMargin = null; Point2D previousPointStartTab = null; Point2D previousPointEndMargin = null; for (RowOfShapes row : column) { boolean rowForStandaloneParagraph = false; boolean newParagraph = false; if (row.getShapes().size() <= maxShapesForStandaloneParagraph) { rowsForStandaloneParagraphs.add(row); rowForStandaloneParagraph = true; } else { double rightOverlap = this.findLargeShapeOverlapOnRight(row, column, sourceImage); double leftOverlap = this.findLargeShapeOverlapOnLeft(row, column, sourceImage); if (drawSegmentation) { double rowVerticalMidPoint = row.getBaseLineMiddlePoint(); double startMarginX = column.startMargin + row.getXAdjustment(); double startTabX = column.startTab + row.getXAdjustment(); double endMarginX = column.endMargin + row.getXAdjustment(); if (sourceImage.isLeftToRight()) { startMarginX += safetyMargin; startTabX -= safetyMargin; endMarginX -= safetyMargin; startMarginX += leftOverlap; startTabX += leftOverlap; endMarginX -= rightOverlap; } else { startMarginX -= safetyMargin; startTabX += safetyMargin; endMarginX += safetyMargin; startMarginX -= rightOverlap; startTabX -= rightOverlap; endMarginX += leftOverlap; } Point2D.Double currentPointStartMargin = new Point2D.Double(startMarginX, rowVerticalMidPoint); Point2D.Double currentPointStartTab = new Point2D.Double(startTabX, rowVerticalMidPoint); Point2D.Double currentPointEndMargin = new Point2D.Double(endMarginX, rowVerticalMidPoint); if (previousPointStartMargin != null) { graphics2D.setStroke(new BasicStroke(1)); graphics2D.setPaint(Color.BLUE); graphics2D.drawLine((int) Math.round(previousPointStartMargin.getX()), (int) Math.round(previousPointStartMargin.getY()), (int) Math.round(currentPointStartMargin.getX()), (int) Math.round(currentPointStartMargin.getY())); graphics2D.drawLine((int) Math.round(previousPointEndMargin.getX()), (int) Math.round(previousPointEndMargin.getY()), (int) Math.round(currentPointEndMargin.getX()), (int) Math.round(currentPointEndMargin.getY())); graphics2D.setPaint(Color.RED); graphics2D.drawLine((int) Math.round(previousPointStartTab.getX()), (int) Math.round(previousPointStartTab.getY()), (int) Math.round(currentPointStartTab.getX()), (int) Math.round(currentPointStartTab.getY())); graphics2D.setPaint(Color.RED); graphics2D.drawLine((int) Math.round(previousPointEndMargin.getX()), (int) Math.round(previousPointEndMargin.getY()), (int) Math.round(currentPointEndMargin.getX()), (int) Math.round(currentPointEndMargin.getY())); } previousPointStartMargin = currentPointStartMargin; previousPointStartTab = currentPointStartTab; previousPointEndMargin = currentPointEndMargin; } if (previousRow == null) { LOG.debug("New paragraph (first)"); newParagraph = true; } else { if (sourceImage.isLeftToRight()) { if (previousRow.getRight() - previousRow.getXAdjustment() - rightOverlap < column.endMargin - safetyMargin) { LOG.debug("New paragraph (previous EOP)"); newParagraph = true; } else if (column.hasTab && isIndented && row.getLeft() - row.getXAdjustment() + leftOverlap > column.startTab - safetyMargin) { LOG.debug("New paragraph (indent)"); newParagraph = true; } else if (column.hasTab && !isIndented && row.getLeft() - row.getXAdjustment() + leftOverlap < column.startMargin + safetyMargin) { LOG.debug("New paragraph (outdent)"); newParagraph = true; } } else { if (previousRow.getLeft() - previousRow.getXAdjustment() + leftOverlap > column.endMargin + safetyMargin) { LOG.debug("New paragraph (previous EOP)"); newParagraph = true; } else if (column.hasTab && isIndented && row.getRight() - row.getXAdjustment() - rightOverlap < column.startTab + safetyMargin) { LOG.debug("New paragraph (indent)"); newParagraph = true; } else if (column.hasTab && !isIndented && row.getRight() - row.getXAdjustment() - rightOverlap > column.startMargin - safetyMargin) { LOG.debug("New paragraph (outdent)"); newParagraph = true; } } // left-to-right? } // have previous row } // standalone paragraph? if (!rowForStandaloneParagraph) LOG.debug(row.toString()); if (newParagraph) { if (rowsForStandaloneParagraphs.size() > 0) { for (RowOfShapes oneRow : rowsForStandaloneParagraphs) { LOG.debug("Standalone paragraph"); LOG.debug("Standalone row: left(" + oneRow.getLeft() + "), top(" + oneRow.getTop() + "), right(" + oneRow.getRight() + "), bottom(" + oneRow.getBottom() + ")"); Paragraph standaloneParagraph = sourceImage.newParagraph(); standaloneParagraph.getRows().add(oneRow); } rowsForStandaloneParagraphs.clear(); } paragraph = sourceImage.newParagraph(); } //LOG.debug("Row: left(" + row.getLeft() + "), right(" + row.getRight() + "), width(" + (row.getRight() - row.getLeft() + 1) + ")"); if (!rowForStandaloneParagraph) { paragraph.getRows().add(row); previousRow = row; } } // next row in column if (rowsForStandaloneParagraphs.size() > 0) { for (RowOfShapes oneRow : rowsForStandaloneParagraphs) { LOG.debug("Standalone paragraph"); LOG.debug("Standalone row: left(" + oneRow.getLeft() + "), top(" + oneRow.getTop() + "), right(" + oneRow.getRight() + "), bottom(" + oneRow.getBottom() + ")"); Paragraph standaloneParagraph = sourceImage.newParagraph(); standaloneParagraph.getRows().add(oneRow); } rowsForStandaloneParagraphs.clear(); } } // next column }
From source file:lu.fisch.unimozer.Diagram.java
public Point2D getIntersection(Point2D p1, Point2D p2, Point2D p3, Point2D p4) { double x1 = p1.getX(); double y1 = p1.getY(); double x2 = p2.getX(); double y2 = p2.getY(); double x3 = p3.getX(); double y3 = p3.getY(); double x4 = p4.getX(); double y4 = p4.getY(); double xD1, yD1, xD2, yD2, xD3, yD3; double dot, deg, len1, len2; double segmentLen1, segmentLen2; double ua, ub, div; double xi, yi; // calculate differences xD1 = p2.getX() - p1.getX();// w ww. j a v a2 s .c om xD2 = p4.getX() - p3.getX(); yD1 = p2.getY() - p1.getY(); yD2 = p4.getY() - p3.getY(); xD3 = p1.getX() - p3.getX(); yD3 = p1.getY() - p3.getY(); // calculate the lengths of the two lines len1 = Math.sqrt(xD1 * xD1 + yD1 * yD1); len2 = Math.sqrt(xD2 * xD2 + yD2 * yD2); // calculate angle between the two lines. dot = (xD1 * xD2 + yD1 * yD2); // dot product deg = dot / (len1 * len2); // if abs(angle)==1 then the lines are parallell, // so no intersection is possible if (Math.abs(deg) == 1) return null; div = yD2 * xD1 - xD2 * yD1; ua = (xD2 * yD3 - yD2 * xD3) / div; ub = (xD1 * yD3 - yD1 * xD3) / div; xi = (p1.getX() + ua * xD1); yi = (p1.getY() + ua * yD1); Point2D pt = new Point2D.Double(xi, yi); // calculate the combined length of the two segments // between Pt-p1 and Pt-p2 xD1 = pt.getX() - p1.getX(); xD2 = pt.getX() - p2.getX(); yD1 = pt.getY() - p1.getY(); yD2 = pt.getY() - p2.getY(); segmentLen1 = Math.sqrt(xD1 * xD1 + yD1 * yD1) + Math.sqrt(xD2 * xD2 + yD2 * yD2); // calculate the combined length of the two segments // between Pt-p3 and Pt-p4 xD1 = pt.getX() - p3.getX(); xD2 = pt.getX() - p4.getX(); yD1 = pt.getY() - p3.getY(); yD2 = pt.getY() - p4.getY(); segmentLen2 = Math.sqrt(xD1 * xD1 + yD1 * yD1) + Math.sqrt(xD2 * xD2 + yD2 * yD2); // if the lengths of both sets of segments are the same as // the lenghts of the two lines the point is actually // on the line segment. // if the point isn't on the line, return null if (Math.abs(len1 - segmentLen1) > 0.01 || Math.abs(len2 - segmentLen2) > 0.01) return null; return pt; }
From source file:v800_trainer.JCicloTronic.java
private void Draw_Map() { Update_Map_paint = false;/*from w ww .j ava 2 s. com*/ Map_internal_Panel.removeAll(); if (mapKit != null) { mapKit.removeAll(); mapKit = null; } mapKit = new org.jxmapviewer.JXMapKit(); mapKit.setName("mapKit"); mapKit.setPreferredSize(Map_internal_Panel.getSize()); Map_internal_Panel.add(mapKit, java.awt.BorderLayout.CENTER); // mapKit.setDefaultProvider(DefaultProviders.OpenStreetMaps); if (Map_Type.getSelectedIndex() == 0) mapKit.getMainMap().setTileFactory(new DefaultTileFactory(new OSMTileFactoryInfo())); if (Map_Type.getSelectedIndex() == 1) mapKit.getMainMap().setTileFactory( new DefaultTileFactory(new VirtualEarthTileFactoryInfo(VirtualEarthTileFactoryInfo.MAP))); if (Map_Type.getSelectedIndex() == 2) mapKit.getMainMap().setTileFactory( new DefaultTileFactory(new VirtualEarthTileFactoryInfo(VirtualEarthTileFactoryInfo.SATELLITE))); if (Map_Type.getSelectedIndex() == 3) mapKit.getMainMap().setTileFactory( new DefaultTileFactory(new VirtualEarthTileFactoryInfo(VirtualEarthTileFactoryInfo.HYBRID))); int j = Auswahl_Map.getSelectedIndex(); if (j == 0) { this.LoadGoogleEarth.setEnabled(false); this.Kein_kmz_text.setText("bersicht"); this.jLabel_map_streckenlnge.setText(""); } else { if (new java.io.File(Statistikhandle.TourData[Auswahl_Map.getSelectedIndex()].DataProperty .getProperty("GoogleEarth", "")).exists() == false || Statistikhandle.TourData[Auswahl_Map.getSelectedIndex()].GeoDataArray.isEmpty()) { this.LoadGoogleEarth.setEnabled(false); this.Kein_kmz_text.setText("kein Log File"); this.jLabel_map_streckenlnge.setText(""); mapKit.removeAll(); return; } this.LoadGoogleEarth.setEnabled(true); this.Kein_kmz_text.setText("<html>" + Statistikhandle.TourData[Auswahl_Map.getSelectedIndex()].DataProperty.getProperty("Titel", "") + "</html>"); } int Datenp = Statistikhandle.TourData[j].Datenpunkte; from_x = 0; to_x = 999999999; mark_x = 0; if (j == 0) { int Anzahl_Kurven = Integer.parseInt(Properties.getProperty("AnzahlKurven", "5")) + 1; if (Anzahl_Kurven > Auswahl_Map.getItemCount()) { Anzahl_Kurven = Auswahl_Map.getItemCount(); } map_x_max = Statistikhandle.TourData[1].map_x_max; map_x_min = map_x_max; map_y_max = Statistikhandle.TourData[1].map_y_max; map_y_min = map_y_max; for (int i = 1; i < Anzahl_Kurven; i++) { if (Statistikhandle.TourData[i].map_x_max > map_x_max) { map_x_max = Statistikhandle.TourData[i].map_x_max; } if (Statistikhandle.TourData[i].map_x_min < map_x_min) { map_x_min = Statistikhandle.TourData[i].map_x_min; } if (Statistikhandle.TourData[i].map_y_max > map_y_max) { map_y_max = Statistikhandle.TourData[i].map_y_max; } if (Statistikhandle.TourData[i].map_y_min < map_y_min) { map_y_min = Statistikhandle.TourData[i].map_y_min; } } } if (j != 0 && Auswahl_Map.getSelectedIndex() <= Integer .parseInt(Properties.getProperty("AnzahlKurven", "5"))) { // Markierung aus Zoombereich auslesen int i = 0; if (Graphik_Radio_Strecke.isSelected() == true) { while (Statistikhandle.TourData[j].Strecke_gesZeit[i] < graph_min && i + 1 < Datenp) { i++; } from_x = Statistikhandle.TourData[j].Strecke_gesZeit[i]; while (Statistikhandle.TourData[j].Strecke_gesZeit[i] < graph_max && i + 1 < Datenp) { i++; } to_x = Statistikhandle.TourData[j].Strecke_gesZeit[i]; } else { while (Statistikhandle.TourData[j].gesZeit[i] < graph_min && i + 1 < Datenp) { i++; } from_x = Statistikhandle.TourData[j].Strecke_gesZeit[i]; while (Statistikhandle.TourData[j].gesZeit[i] < graph_max && i + 1 < Datenp) { i++; } to_x = Statistikhandle.TourData[j].Strecke_gesZeit[i]; } // Streckenmarkierung (crosshair) auslesen i = 0; if (Graphik_Radio_Strecke.isSelected() == true) { while (Statistikhandle.TourData[j].Strecke_gesZeit[i] < graph_crosshair && i + 1 < Datenp) { i++; } mark_x = Statistikhandle.TourData[j].Strecke_gesZeit[i]; } else { while (Statistikhandle.TourData[j].gesZeit[i] < graph_crosshair && i + 1 < Datenp) { i++; } mark_x = Statistikhandle.TourData[j].Strecke_gesZeit[i]; } double distance = 0; int selection = 0; //int selection = Auswahl_Map.getSelectedIndex() - 1; if (Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(0)) != 0) { map_y_max = Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(0)); map_y_min = map_y_max; } if (Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(1)) != 0) { map_x_max = Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(1)); map_x_min = map_x_max; } do { distance = distance + distFrom(Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 1)), Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection)), Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 3)), Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 2))); selection = selection + 2; } while (from_x > distance && selection < Statistikhandle.TourData[j].GeoDataArray.size() - 4); map_y_max = Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection)); map_y_min = map_y_max; map_x_max = Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 1)); map_x_min = map_x_max; do { distance = distance + distFrom(Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 1)), Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection)), Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 3)), Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 2))); if (map_y_max < Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection))) { map_y_max = Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection)); } if (map_y_min > Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection))) { map_y_min = Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection)); } if (map_x_max < Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 1))) { map_x_max = Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 1)); } if (map_x_min > Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 1))) { map_x_min = Double.parseDouble(Statistikhandle.TourData[j].GeoDataArray.get(selection + 1)); } selection = selection + 2; } while (to_x > distance && selection < Statistikhandle.TourData[j].GeoDataArray.size() - 4); } mapKit.setCenterPosition(new GeoPosition(((map_x_max + map_x_min) / 2), ((map_y_max + map_y_min) / 2))); Point2D pointa = mapKit.getMainMap().convertGeoPositionToPoint(new GeoPosition(map_x_max, map_y_max)); Point2D pointb = mapKit.getMainMap().convertGeoPositionToPoint(new GeoPosition(map_x_min, map_y_min)); double rectX = Map_internal_Panel.getWidth(); double rectY = Map_internal_Panel.getHeight(); int maxzoom = mapKit.getMainMap().getTileFactory().getInfo().getMaximumZoomLevel(); double deltaX = 0; double deltaY = 0; for (int i = 0; i < maxzoom; i++) { mapKit.getMainMap().setZoom(maxzoom - i); pointa = mapKit.getMainMap().convertGeoPositionToPoint(new GeoPosition(map_x_max, map_y_max)); pointb = mapKit.getMainMap().convertGeoPositionToPoint(new GeoPosition(map_x_min, map_y_min)); deltaX = pointa.getX() - pointb.getX(); deltaY = pointb.getY() - pointa.getY(); if (rectX < deltaX || rectY < deltaY) { mapKit.getMainMap().setZoom(maxzoom - i + 1); break; } } if (Auswahl_Map.getSelectedIndex() != 0) { this.jLabel27.setEnabled(true); this.jLabel_map_streckenlnge .setText(Statistikhandle.TourData[Auswahl_Map.getSelectedIndex()].map_Streckenlnge + " km"); } else { this.jLabel27.setEnabled(false); } read_Waypoint(); DefaultWaypoint Mark = new DefaultWaypoint(Markierung); Set<Waypoint> waypoints = new HashSet<Waypoint>(Arrays.asList(new DefaultWaypoint(Markierung))); WaypointPainter waypointPainter = new WaypointPainter(); waypointPainter.setWaypoints(waypoints); ArrayList painters = new ArrayList(); painters.add(lineOverlay); painters.add(waypointPainter); CompoundPainter<JXMapViewer> painter = new CompoundPainter<JXMapViewer>(painters); mapKit.getMainMap().setOverlayPainter(painter); repaint(); Update_Map_paint = true; }
From source file:com.net2plan.interfaces.networkDesign.NetPlan.java
/** * <p>Saves the current network plan to a given output stream.</p> * * @param outputStream Output stream//w w w . j av a 2 s . c o m */ public void saveToOutputStream(OutputStream outputStream) { try { XMLOutputFactory2 output = (XMLOutputFactory2) XMLOutputFactory2.newFactory(); XMLStreamWriter2 writer = (XMLStreamWriter2) output.createXMLStreamWriter(outputStream); writer.writeStartDocument("UTF-8", "1.0"); XMLUtils.indent(writer, 0); writer.writeStartElement("network"); writer.writeAttribute("description", getNetworkDescription()); writer.writeAttribute("name", getNetworkName()); writer.writeAttribute("version", Version.getFileFormatVersion()); writer.writeAttribute("nextElementId", nextElementId.toString()); //Set<Long> nodeIds_thisNetPlan = new HashSet<Long> (getNodeIds()); for (Node node : nodes) { boolean emptyNode = node.attributes.isEmpty(); XMLUtils.indent(writer, 1); if (emptyNode) writer.writeEmptyElement("node"); else writer.writeStartElement("node"); Point2D position = node.nodeXYPositionMap; writer.writeAttribute("id", Long.toString(node.id)); writer.writeAttribute("xCoord", Double.toString(position.getX())); writer.writeAttribute("yCoord", Double.toString(position.getY())); writer.writeAttribute("name", node.name); writer.writeAttribute("isUp", Boolean.toString(node.isUp)); final Set<NetworkLayer> layersWithIcons = layers.stream() .filter(l -> node.getUrlNodeIcon(l) != null).collect(Collectors.toSet()); final List<Long> idsLayersWithIcons = layersWithIcons.stream().map(l -> l.getId()) .collect(Collectors.toList()); writer.writeAttribute("layersWithIconsDefined", CollectionUtils.join(idsLayersWithIcons, " ")); for (NetworkLayer layer : layersWithIcons) if (node.getUrlNodeIcon(layer) != null) writer.writeAttribute("nodeIconURLLayer_" + layer.getId(), node.getUrlNodeIcon(layer).toString()); for (Entry<String, String> entry : node.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyNode) { XMLUtils.indent(writer, 1); writer.writeEndElement(); } } for (Resource res : resources) { final boolean emptyResource = res.attributes.isEmpty(); XMLUtils.indent(writer, 1); if (emptyResource) writer.writeEmptyElement("resource"); else writer.writeStartElement("resource"); writer.writeAttribute("id", Long.toString(res.id)); writer.writeAttribute("hostNodeId", Long.toString(res.hostNode.id)); writer.writeAttribute("type", res.type); writer.writeAttribute("name", res.name); writer.writeAttribute("capacityMeasurementUnits", res.capacityMeasurementUnits); writer.writeAttribute("processingTimeToTraversingTrafficInMs", Double.toString(res.processingTimeToTraversingTrafficInMs)); writer.writeAttribute("capacity", Double.toString(res.capacity)); if (res.urlIcon != null) writer.writeAttribute("urlIcon", res.urlIcon.toString()); List<Double> baseResourceAndOccupiedCapacitiesMap = new LinkedList<Double>(); for (Entry<Resource, Double> br : res.capacityIOccupyInBaseResource.entrySet()) { baseResourceAndOccupiedCapacitiesMap.add((double) br.getKey().id); baseResourceAndOccupiedCapacitiesMap.add(br.getValue()); } writer.writeAttribute("baseResourceAndOccupiedCapacitiesMap", CollectionUtils.join(baseResourceAndOccupiedCapacitiesMap, " ")); for (Entry<String, String> entry : res.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyResource) { XMLUtils.indent(writer, 1); writer.writeEndElement(); } } for (NetworkLayer layer : layers) { XMLUtils.indent(writer, 1); writer.writeStartElement("layer"); writer.writeAttribute("id", Long.toString(layer.id)); writer.writeAttribute("name", layer.name); writer.writeAttribute("description", layer.description); writer.writeAttribute("isDefaultLayer", Boolean.toString(defaultLayer == layer)); writer.writeAttribute("linkCapacityUnitsName", layer.linkCapacityUnitsName); writer.writeAttribute("demandTrafficUnitsName", layer.demandTrafficUnitsName); if (layer.defaultNodeIconURL != null) writer.writeAttribute("defaultNodeIconURL", layer.defaultNodeIconURL.toString()); for (Link link : layer.links) { boolean emptyLink = link.attributes.isEmpty(); XMLUtils.indent(writer, 2); if (emptyLink) writer.writeEmptyElement("link"); else writer.writeStartElement("link"); writer.writeAttribute("id", Long.toString(link.id)); writer.writeAttribute("originNodeId", Long.toString(link.originNode.id)); writer.writeAttribute("destinationNodeId", Long.toString(link.destinationNode.id)); writer.writeAttribute("capacity", Double.toString(link.capacity)); writer.writeAttribute("lengthInKm", Double.toString(link.lengthInKm)); writer.writeAttribute("propagationSpeedInKmPerSecond", Double.toString(link.propagationSpeedInKmPerSecond)); writer.writeAttribute("isUp", Boolean.toString(link.isUp)); for (Entry<String, String> entry : link.attributes.entrySet()) { XMLUtils.indent(writer, 3); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyLink) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for (Demand demand : layer.demands) { boolean emptyDemand = demand.attributes.isEmpty() && demand.mandatorySequenceOfTraversedResourceTypes.isEmpty(); XMLUtils.indent(writer, 2); if (emptyDemand) writer.writeEmptyElement("demand"); else writer.writeStartElement("demand"); writer.writeAttribute("id", Long.toString(demand.id)); writer.writeAttribute("ingressNodeId", Long.toString(demand.ingressNode.id)); writer.writeAttribute("egressNodeId", Long.toString(demand.egressNode.id)); writer.writeAttribute("offeredTraffic", Double.toString(demand.offeredTraffic)); for (String type : demand.mandatorySequenceOfTraversedResourceTypes) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("serviceChainResourceTypeOfSequence"); writer.writeAttribute("type", type); } for (Entry<String, String> entry : demand.attributes.entrySet()) { XMLUtils.indent(writer, 3); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyDemand) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for (MulticastDemand demand : layer.multicastDemands) { boolean emptyDemand = demand.attributes.isEmpty(); XMLUtils.indent(writer, 2); if (emptyDemand) writer.writeEmptyElement("multicastDemand"); else writer.writeStartElement("multicastDemand"); writer.writeAttribute("id", Long.toString(demand.id)); writer.writeAttribute("ingressNodeId", Long.toString(demand.ingressNode.id)); List<Long> egressNodeIds = new LinkedList<Long>(); for (Node n : demand.egressNodes) egressNodeIds.add(n.id); writer.writeAttribute("egressNodeIds", CollectionUtils.join(egressNodeIds, " ")); writer.writeAttribute("offeredTraffic", Double.toString(demand.offeredTraffic)); for (Entry<String, String> entry : demand.attributes.entrySet()) { XMLUtils.indent(writer, 3); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyDemand) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for (MulticastTree tree : layer.multicastTrees) { boolean emptyTree = tree.attributes.isEmpty(); XMLUtils.indent(writer, 3); if (emptyTree) writer.writeEmptyElement("multicastTree"); else writer.writeStartElement("multicastTree"); writer.writeAttribute("id", Long.toString(tree.id)); writer.writeAttribute("demandId", Long.toString(tree.demand.id)); writer.writeAttribute("carriedTrafficIfNotFailing", Double.toString(tree.carriedTrafficIfNotFailing)); writer.writeAttribute("occupiedLinkCapacityIfNotFailing", Double.toString(tree.occupiedLinkCapacityIfNotFailing)); List<Long> linkIds = new LinkedList<Long>(); for (Link e : tree.linkSet) linkIds.add(e.id); writer.writeAttribute("currentSetLinks", CollectionUtils.join(linkIds, " ")); /* If the original link set was removed, it is replaced by the current link set */ boolean initialLinkSetNotRemoved = true; for (Link e : tree.initialSetLinksWhenWasCreated) if (e.netPlan == null) { initialLinkSetNotRemoved = false; break; } linkIds = new LinkedList<Long>(); for (Link e : initialLinkSetNotRemoved ? tree.initialSetLinksWhenWasCreated : tree.linkSet) linkIds.add(e.id); writer.writeAttribute("initialSetLinks", CollectionUtils.join(linkIds, " ")); for (Entry<String, String> entry : tree.attributes.entrySet()) { XMLUtils.indent(writer, 4); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyTree) { XMLUtils.indent(writer, 3); writer.writeEndElement(); } } if (layer.routingType == RoutingType.SOURCE_ROUTING) { boolean emptySourceRouting = !hasRoutes(layer); XMLUtils.indent(writer, 2); if (emptySourceRouting) writer.writeEmptyElement("sourceRouting"); else writer.writeStartElement("sourceRouting"); for (Route route : layer.routes) { boolean emptyRoute = route.attributes.isEmpty(); XMLUtils.indent(writer, 3); if (emptyRoute) writer.writeEmptyElement("route"); else writer.writeStartElement("route"); writer.writeAttribute("id", Long.toString(route.id)); writer.writeAttribute("demandId", Long.toString(route.demand.id)); writer.writeAttribute("currentCarriedTrafficIfNotFailing", Double.toString(route.currentCarriedTrafficIfNotFailing)); writer.writeAttribute("currentLinksAndResourcesOccupationIfNotFailing", CollectionUtils.join(route.currentLinksAndResourcesOccupationIfNotFailing, " ")); writer.writeAttribute("currentPath", CollectionUtils.join(NetPlan.getIds(route.currentPath), " ")); writer.writeAttribute("initialStateCarriedTrafficIfNotFailing", Double.toString(route.initialStateCarriedTrafficIfNotFailing)); writer.writeAttribute("initialStateOccupationIfNotFailing", CollectionUtils.join(route.initialStateOccupationIfNotFailing, " ")); writer.writeAttribute("initialStatePath", CollectionUtils.join(NetPlan.getIds(route.initialStatePath), " ")); writer.writeAttribute("backupRoutes", CollectionUtils.join(NetPlan.getIds(route.backupRoutes), " ")); for (Entry<String, String> entry : route.attributes.entrySet()) { XMLUtils.indent(writer, 4); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyRoute) { XMLUtils.indent(writer, 3); writer.writeEndElement(); } } if (!emptySourceRouting) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } else { boolean emptyHopByHopRouting = !hasForwardingRules(layer); XMLUtils.indent(writer, 2); if (emptyHopByHopRouting) writer.writeEmptyElement("hopByHopRouting"); else writer.writeStartElement("hopByHopRouting"); IntArrayList rows = new IntArrayList(); IntArrayList cols = new IntArrayList(); DoubleArrayList vals = new DoubleArrayList(); layer.forwardingRulesNoFailureState_f_de.getNonZeros(rows, cols, vals); for (int cont = 0; cont < rows.size(); cont++) { final int indexDemand = rows.get(cont); final int indexLink = cols.get(cont); final double splittingRatio = vals.get(cont); XMLUtils.indent(writer, 3); writer.writeEmptyElement("forwardingRule"); writer.writeAttribute("demandId", Long.toString(layer.demands.get(indexDemand).id)); writer.writeAttribute("linkId", Long.toString(layer.links.get(indexLink).id)); writer.writeAttribute("splittingRatio", Double.toString(splittingRatio)); } if (!emptyHopByHopRouting) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for (Entry<String, String> entry : layer.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } XMLUtils.indent(writer, 1); writer.writeEndElement(); } for (SharedRiskGroup srg : srgs) { boolean emptySRG = srg.attributes.isEmpty(); XMLUtils.indent(writer, 1); if (emptySRG) writer.writeEmptyElement("srg"); else writer.writeStartElement("srg"); writer.writeAttribute("id", Long.toString(srg.id)); writer.writeAttribute("meanTimeToFailInHours", Double.toString(srg.meanTimeToFailInHours)); writer.writeAttribute("meanTimeToRepairInHours", Double.toString(srg.meanTimeToRepairInHours)); writer.writeAttribute("nodes", CollectionUtils.join(NetPlan.getIds(srg.nodes), " ")); writer.writeAttribute("links", CollectionUtils.join(NetPlan.getIds(srg.links), " ")); for (Entry<String, String> entry : srg.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptySRG) { XMLUtils.indent(writer, 1); writer.writeEndElement(); } } for (DemandLinkMapping d_e : interLayerCoupling.edgeSet()) { for (Entry<Demand, Link> coupling : d_e.demandLinkMapping.entrySet()) { XMLUtils.indent(writer, 1); writer.writeEmptyElement("layerCouplingDemand"); writer.writeAttribute("lowerLayerDemandId", "" + coupling.getKey().id); writer.writeAttribute("upperLayerLinkId", "" + coupling.getValue().id); } for (Entry<MulticastDemand, Set<Link>> coupling : d_e.multicastDemandLinkMapping.entrySet()) { XMLUtils.indent(writer, 1); writer.writeEmptyElement("layerCouplingMulticastDemand"); List<Long> linkIds = new LinkedList<Long>(); for (Link e : coupling.getValue()) linkIds.add(e.id); writer.writeAttribute("lowerLayerDemandId", "" + coupling.getKey().id); writer.writeAttribute("upperLayerLinkIds", CollectionUtils.join(linkIds, " ")); } } for (Entry<String, String> entry : this.attributes.entrySet()) { XMLUtils.indent(writer, 1); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } XMLUtils.indent(writer, 0); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new RuntimeException(e); } }
From source file:lu.fisch.unimozer.Diagram.java
@Override public void paint(Graphics graphics) { super.paint(graphics); Graphics2D g = (Graphics2D) graphics; // set anti-aliasing rendering ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setFont(new Font(g.getFont().getFontName(), Font.PLAIN, Unimozer.DRAW_FONT_SIZE)); // clear background g.setColor(Color.WHITE);// w w w. j av a 2s. c o m g.fillRect(0, 0, getWidth() + 1, getHeight() + 1); g.setColor(Color.BLACK); /*Set<String> set; Iterator<String> itr; // draw classes a first time for(MyClass clas : classes.values()) { clas.setEnabled(this.isEnabled()); clas.draw(graphics,showFields,showMethods); }*/ /* let's try this one ... */ for (Entry<String, MyClass> entry : classes.entrySet()) { // get the actual class ... MyClass clas = entry.getValue(); clas.setEnabled(this.isEnabled()); clas.draw(graphics, showFields, showMethods); } // draw packages packages.clear(); for (MyClass myClass : classes.values()) { if (myClass.isDisplayUML()) { Package myPackage = null; if (!packages.containsKey(myClass.getPackagename())) { myPackage = new Package(myClass.getPackagename(), myClass.getPosition().y, myClass.getPosition().x, myClass.getWidth(), myClass.getHeight()); packages.put(myPackage.getName(), myPackage); } else myPackage = packages.get(myClass.getPackagename()); if (myClass.getPosition().x + myClass.getWidth() > myPackage.getRight()) myPackage.setRight(myClass.getPosition().x + myClass.getWidth()); if (myClass.getPosition().y + myClass.getHeight() > myPackage.getBottom()) myPackage.setBottom(myClass.getPosition().y + myClass.getHeight()); if (myClass.getPosition().x < myPackage.getLeft()) myPackage.setLeft(myClass.getPosition().x); if (myClass.getPosition().y < myPackage.getTop()) myPackage.setTop(myClass.getPosition().y); } } // draw classes /* set = classes.keySet(); itr = set.iterator(); while (itr.hasNext()) { String str = itr.next(); classes.get(str).draw(graphics); }/**/ mostRight = 0; mostBottom = 0; // ?? /* set = classes.keySet(); itr = set.iterator(); while (itr.hasNext()) { String str = itr.next(); MyClass thisClass = classes.get(str); } */ // init topLeft & bottomRight topLeft = new Point(this.getWidth(), this.getHeight()); bottomRight = new Point(0, 0); // draw packages if (packages.size() > 0) if ((packages.size() == 1 && packages.get(Package.DEFAULT) == null) || packages.size() > 1) for (Package pack : packages.values()) { pack.draw(graphics); // push outer box if (pack.getTopAbs() < topLeft.y) topLeft.y = pack.getTopAbs(); if (pack.getLeftAbs() < topLeft.x) topLeft.x = pack.getLeftAbs(); if (pack.getBottomAbs() > bottomRight.y) bottomRight.y = pack.getBottomAbs(); if (pack.getRightAbs() > bottomRight.x) bottomRight.x = pack.getRightAbs(); } // draw implmementations if (isShowHeritage()) { Stroke oldStroke = g.getStroke(); g.setStroke(dashed); /*itr = set.iterator(); while (itr.hasNext()) { String str = itr.next(); */ /* let's try this one ... */ for (Entry<String, MyClass> entry : classes.entrySet()) { // get the actual class ... String str = entry.getKey(); MyClass thisClass = classes.get(str); if (thisClass.getPosition().x + thisClass.getWidth() > mostRight) mostRight = thisClass.getPosition().x + thisClass.getWidth(); if (thisClass.getPosition().y + thisClass.getHeight() > mostBottom) mostBottom = thisClass.getPosition().y + thisClass.getHeight(); if (thisClass.getImplements().size() > 0) for (String extendsClass : thisClass.getImplements()) { MyClass otherClass = classes.get(extendsClass); if (otherClass == null) otherClass = findByShortName(extendsClass); //if(otherClass==null) System.err.println(extendsClass+" not found (1)"); //if (otherClass==null) otherClass=findByShortName(extendsClass); //if(otherClass==null) System.err.println(extendsClass+" not found (2)"); if (otherClass != null && thisClass.isDisplayUML() && otherClass.isDisplayUML()) { thisClass.setExtendsMyClass(otherClass); // draw arrow from thisClass to otherClass // get the center point of each class Point fromP = new Point(thisClass.getPosition().x + thisClass.getWidth() / 2, thisClass.getPosition().y + thisClass.getHeight() / 2); Point toP = new Point(otherClass.getPosition().x + otherClass.getWidth() / 2, otherClass.getPosition().y + otherClass.getHeight() / 2); // get the corner 4 points of the desstination class // (outer margin = 4) Point toP1 = new Point(otherClass.getPosition().x - 4, otherClass.getPosition().y - 4); Point toP2 = new Point(otherClass.getPosition().x + otherClass.getWidth() + 4, otherClass.getPosition().y - 4); Point toP3 = new Point(otherClass.getPosition().x + otherClass.getWidth() + 4, otherClass.getPosition().y + otherClass.getHeight() + 4); Point toP4 = new Point(otherClass.getPosition().x - 4, otherClass.getPosition().y + otherClass.getHeight() + 4); // get the intersection with the center line an one of the // sedis of the destination class Point2D toDraw = getIntersection(fromP, toP, toP1, toP2); if (toDraw == null) toDraw = getIntersection(fromP, toP, toP2, toP3); if (toDraw == null) toDraw = getIntersection(fromP, toP, toP3, toP4); if (toDraw == null) toDraw = getIntersection(fromP, toP, toP4, toP1); // draw the arrowed line if (toDraw != null) drawExtends(g, fromP, new Point((int) toDraw.getX(), (int) toDraw.getY())); } } } g.setStroke(oldStroke); } // draw inheritance if (isShowHeritage()) { /*itr = set.iterator(); while (itr.hasNext()) { String str = itr.next(); */ /* let's try this one ... */ for (Entry<String, MyClass> entry : classes.entrySet()) { // get the actual class ... String str = entry.getKey(); MyClass thisClass = classes.get(str); if (thisClass.getPosition().x + thisClass.getWidth() > mostRight) mostRight = thisClass.getPosition().x + thisClass.getWidth(); if (thisClass.getPosition().y + thisClass.getHeight() > mostBottom) mostBottom = thisClass.getPosition().y + thisClass.getHeight(); String extendsClass = thisClass.getExtendsClass(); //System.out.println(thisClass.getFullName()+" extends "+extendsClass); if (!extendsClass.equals("") && thisClass.isDisplayUML()) { MyClass otherClass = classes.get(extendsClass); if (otherClass == null) otherClass = findByShortName(extendsClass); //if(otherClass==null) System.err.println(extendsClass+" not found (1)"); //if (otherClass==null) otherClass=findByShortName(extendsClass); //if(otherClass==null) System.err.println(extendsClass+" not found (2)"); if (otherClass != null) { if (otherClass != thisClass) { thisClass.setExtendsMyClass(otherClass); // draw arrow from thisClass to otherClass // get the center point of each class Point fromP = new Point(thisClass.getPosition().x + thisClass.getWidth() / 2, thisClass.getPosition().y + thisClass.getHeight() / 2); Point toP = new Point(otherClass.getPosition().x + otherClass.getWidth() / 2, otherClass.getPosition().y + otherClass.getHeight() / 2); // get the corner 4 points of the desstination class // (outer margin = 4) Point toP1 = new Point(otherClass.getPosition().x - 4, otherClass.getPosition().y - 4); Point toP2 = new Point(otherClass.getPosition().x + otherClass.getWidth() + 4, otherClass.getPosition().y - 4); Point toP3 = new Point(otherClass.getPosition().x + otherClass.getWidth() + 4, otherClass.getPosition().y + otherClass.getHeight() + 4); Point toP4 = new Point(otherClass.getPosition().x - 4, otherClass.getPosition().y + otherClass.getHeight() + 4); // get the intersection with the center line an one of the // sedis of the destination class Point2D toDraw = getIntersection(fromP, toP, toP1, toP2); if (toDraw == null) toDraw = getIntersection(fromP, toP, toP2, toP3); if (toDraw == null) toDraw = getIntersection(fromP, toP, toP3, toP4); if (toDraw == null) toDraw = getIntersection(fromP, toP, toP4, toP1); // draw in red if there is a cclic inheritance problem if (thisClass.hasCyclicInheritance()) { ((Graphics2D) graphics).setStroke(new BasicStroke(2)); graphics.setColor(Color.RED); } // draw the arrowed line if (toDraw != null) drawExtends((Graphics2D) graphics, fromP, new Point((int) toDraw.getX(), (int) toDraw.getY())); } else { ((Graphics2D) graphics).setStroke(new BasicStroke(2)); graphics.setColor(Color.RED); // line graphics.drawLine(thisClass.getPosition().x + thisClass.getWidth() / 2, thisClass.getPosition().y, thisClass.getPosition().x + thisClass.getWidth() / 2, thisClass.getPosition().y - 32); graphics.drawLine(thisClass.getPosition().x + thisClass.getWidth() / 2, thisClass.getPosition().y - 32, thisClass.getPosition().x + thisClass.getWidth() + 32, thisClass.getPosition().y - 32); graphics.drawLine(thisClass.getPosition().x + thisClass.getWidth() + 32, thisClass.getPosition().y - 32, thisClass.getPosition().x + thisClass.getWidth() + 32, thisClass.getPosition().y + thisClass.getHeight() + 32); graphics.drawLine(thisClass.getPosition().x + thisClass.getWidth() + 32, thisClass.getPosition().y + thisClass.getHeight() + 32, thisClass.getPosition().x + thisClass.getWidth() / 2, thisClass.getPosition().y + thisClass.getHeight() + 32); drawExtends((Graphics2D) graphics, new Point(thisClass.getPosition().x + thisClass.getWidth() / 2, thisClass.getPosition().y + thisClass.getHeight() + 32), new Point(thisClass.getPosition().x + thisClass.getWidth() / 2, thisClass.getPosition().y + thisClass.getHeight())); } // reset the stroke and the color ((Graphics2D) graphics).setStroke(new BasicStroke(1)); graphics.setColor(Color.BLACK); } } } } // setup a hastable to store the relations //Hashtable<String,StringList> classUsage = new Hashtable<String,StringList>(); // store compositions Hashtable<MyClass, Vector<MyClass>> classCompositions = new Hashtable<MyClass, Vector<MyClass>>(); // store aggregations Hashtable<MyClass, Vector<MyClass>> classAggregations = new Hashtable<MyClass, Vector<MyClass>>(); // store all relations Hashtable<MyClass, Vector<MyClass>> classUsings = new Hashtable<MyClass, Vector<MyClass>>(); /* // iterate through all classes to find compositions itr = set.iterator(); while (itr.hasNext()) { // get the actual classname String str = itr.next(); */ /* let's try this one ... */ for (Entry<String, MyClass> entry : classes.entrySet()) { // get the actual class ... String str = entry.getKey(); // get the corresponding "MyClass" object MyClass thisClass = classes.get(str); // setup a list to store the relations with this class Vector<MyClass> theseCompositions = new Vector<MyClass>(); // get all fields of this class StringList uses = thisClass.getFieldTypes(); for (int u = 0; u < uses.count(); u++) { // try to find the other (used) class MyClass otherClass = classes.get(uses.get(u)); if (otherClass == null) otherClass = findByShortName(uses.get(u)); if (otherClass != null) // means this class uses the other ones { // add the other class to the list theseCompositions.add(otherClass); } } // add the list of used classes to the MyClass object thisClass.setUsesMyClass(theseCompositions); // store the composition in the general list classCompositions.put(thisClass, theseCompositions); // store the compositions int eh global relation list classUsings.put(thisClass, new Vector<MyClass>(theseCompositions)); // ^^^^^^^^^^^^^^^^^^^^ // important !! => create a new vector, otherwise the list // are the same ... } /* // iterate through all classes to find aggregations itr = set.iterator(); while (itr.hasNext()) { // get the actual class String str = itr.next(); */ /* let's try this one ... */ for (Entry<String, MyClass> entry : classes.entrySet()) { // get the actual class ... String str = entry.getKey(); // get the corresponding "MyClass" object MyClass thisClass = classes.get(str); // we need a list to store the aggragations with this class Vector<MyClass> theseAggregations = new Vector<MyClass>(); // try to get the list of compositions for this class // init if not present Vector<MyClass> theseCompositions = classCompositions.get(thisClass); if (theseCompositions == null) theseCompositions = new Vector<MyClass>(); // try to get the list of all relations for this class // init if not present Vector<MyClass> theseClasses = classUsings.get(thisClass); if (theseClasses == null) theseClasses = new Vector<MyClass>(); // get the names of the classes that thisclass uses StringList foundUsage = thisClass.getUsesWho(); // go through the list an check to find a corresponding MyClass for (int f = 0; f < foundUsage.count(); f++) { // get the name of the used class String usedClass = foundUsage.get(f); MyClass otherClass = classes.get(usedClass); if (otherClass == null) otherClass = findByShortName(usedClass); if (otherClass != null && thisClass != otherClass) // meanint "otherClass" is a class used by thisClass { if (!theseCompositions.contains(otherClass)) theseAggregations.add(otherClass); if (!theseClasses.contains(otherClass)) theseClasses.add(otherClass); } } // get all method types of this class StringList uses = thisClass.getMethodTypes(); for (int u = 0; u < uses.count(); u++) { // try to find the other (used) class MyClass otherClass = classes.get(uses.get(u)); if (otherClass == null) otherClass = findByShortName(uses.get(u)); if (otherClass != null) // means this class uses the other ones { // add the other class to the list theseAggregations.add(otherClass); } } // store the relations to the class thisClass.setUsesMyClass(theseClasses); // store the aggregation to the global list classAggregations.put(thisClass, theseAggregations); // store all relations to the global list classUsings.put(thisClass, theseClasses); } if (isShowComposition()) { /*Set<MyClass> set2 = classCompositions.keySet(); Iterator<MyClass> itr2 = set2.iterator(); while (itr2.hasNext()) { MyClass thisClass = itr2.next(); */ /* let's try this one ... */ for (Entry<MyClass, Vector<MyClass>> entry : classCompositions.entrySet()) { // get the actual class ... MyClass thisClass = entry.getKey(); if (thisClass.isDisplayUML()) { Vector<MyClass> otherClasses = classCompositions.get(thisClass); for (MyClass otherClass : otherClasses) drawComposition(g, thisClass, otherClass, classUsings); } } } if (isShowAggregation()) { /*Set<MyClass> set2 = classAggregations.keySet(); Iterator<MyClass> itr2 = set2.iterator(); while (itr2.hasNext()) { MyClass thisClass = itr2.next(); */ /* let's try this one ... */ for (Entry<MyClass, Vector<MyClass>> entry : classAggregations.entrySet()) { // get the actual class ... MyClass thisClass = entry.getKey(); if (thisClass.isDisplayUML()) { Vector<MyClass> otherClasses = classAggregations.get(thisClass); for (MyClass otherClass : otherClasses) drawAggregation(g, thisClass, otherClass, classUsings); } } } // draw classes again to put them on top // of the arrows /*set = classes.keySet(); itr = set.iterator(); while (itr.hasNext()) { String str = itr.next(); */ /* let's try this one ... */ for (Entry<String, MyClass> entry : classes.entrySet()) { // get the actual class ... String str = entry.getKey(); classes.get(str).setEnabled(this.isEnabled()); classes.get(str).draw(graphics, showFields, showMethods); // push outer box MyClass thisClass = classes.get(str); if (thisClass.getPosition().y < topLeft.y) topLeft.y = thisClass.getPosition().y; if (thisClass.getPosition().x < topLeft.x) topLeft.x = thisClass.getPosition().x; if (thisClass.getPosition().y + thisClass.getHeight() > bottomRight.y) bottomRight.y = thisClass.getPosition().y + thisClass.getHeight(); if (thisClass.getPosition().x + thisClass.getWidth() > bottomRight.x) bottomRight.x = thisClass.getPosition().x + thisClass.getWidth(); } // comments if (commentString != null) { String fontName = g.getFont().getName(); g.setFont(new Font("Courier", g.getFont().getStyle(), Unimozer.DRAW_FONT_SIZE)); if (!commentString.trim().equals("")) { String myCommentString = new String(commentString); Point myCommentPoint = new Point(commentPoint); //System.out.println(myCommentString); // adjust comment myCommentString = myCommentString.trim(); // adjust position myCommentPoint.y = myCommentPoint.y + 16; // explode comment StringList sl = StringList.explode(myCommentString, "\n"); // calculate totals int totalHeight = 0; int totalWidth = 0; for (int i = 0; i < sl.count(); i++) { String line = sl.get(i).trim(); int h = (int) g.getFont().getStringBounds(line, g.getFontRenderContext()).getHeight(); int w = (int) g.getFont().getStringBounds(line, g.getFontRenderContext()).getWidth(); totalHeight += h; totalWidth = Math.max(totalWidth, w); } // get comment size // draw background g.setColor(new Color(255, 255, 128, 255)); g.fillRoundRect(myCommentPoint.x, myCommentPoint.y, totalWidth + 8, totalHeight + 8, 4, 4); // draw border g.setColor(Color.BLACK); g.drawRoundRect(myCommentPoint.x, myCommentPoint.y, totalWidth + 8, totalHeight + 8, 4, 4); // draw text totalHeight = 0; for (int i = 0; i < sl.count(); i++) { String line = sl.get(i).trim(); int h = (int) g.getFont().getStringBounds(myCommentString, g.getFontRenderContext()) .getHeight(); g.drawString(line, myCommentPoint.x + 4, myCommentPoint.y + h + 2 + totalHeight); totalHeight += h; } } g.setFont(new Font(fontName, Font.PLAIN, Unimozer.DRAW_FONT_SIZE)); } /* if(!isEnabled()) { g.setColor(new Color(128,128,128,128)); g.fillRect(0,0,getWidth(),getHeight()); } */ this.setPreferredSize(new Dimension(mostRight + 32, mostBottom + 32)); // THE NEXT LINE MAKES ALL DIALOGUES DISAPEAR!! //this.setSize(mostRight+32, mostBottom+32); this.validate(); ((JScrollPane) this.getParent().getParent()).revalidate(); if (mode == MODE_EXTENDS && extendsFrom != null && extendsDragPoint != null) { graphics.setColor(Color.BLUE); ((Graphics2D) graphics).setStroke(new BasicStroke(2)); drawExtends(g, new Point(extendsFrom.getPosition().x + extendsFrom.getWidth() / 2, extendsFrom.getPosition().y + extendsFrom.getHeight() / 2), extendsDragPoint); graphics.setColor(Color.BLACK); ((Graphics2D) graphics).setStroke(new BasicStroke(1)); } }
From source file:tufts.vue.LWComponent.java
public void setCenterAt(Point2D p) { setCenterAt(p.getX(), p.getY()); }
From source file:tufts.vue.LWComponent.java
public final void setLocation(Point2D p) { setLocation((float) p.getX(), (float) p.getY()); }