List of usage examples for java.awt Graphics2D setFont
public abstract void setFont(Font font);
From source file:me.solhub.simple.engine.DebugLocationsStructure.java
@Override protected void draw() { Graphics2D g = (Graphics2D) getGraphics(); Graphics2D bbg = (Graphics2D) _backBuffer.getGraphics(); //anti-aliasing code // bbg.setRenderingHint( // RenderingHints.KEY_TEXT_ANTIALIASING, // RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // bbg.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); bbg.setColor(Color.WHITE);/* w w w .j ava2 s . c om*/ bbg.fillRect(0, 0, _windowWidth, _windowHeight); bbg.translate(_xOffset, _yOffset); // draw destinations bbg.setColor(_simState.startingDestination.getColor()); bbg.drawOval(-(int) _simState.startingDestination.getRadius(), -(int) _simState.startingDestination.getRadius(), (int) _simState.startingDestination.getRadius() * 2, (int) _simState.startingDestination.getRadius() * 2); Iterator<Entry<Vector2D, Color>> blah = _destinationColors.entrySet().iterator(); double destinationRadius = _simState.getDestinationRadius(); while (blah.hasNext()) { Entry<Vector2D, Color> temp = blah.next(); bbg.setColor(temp.getValue()); //calculate center coordinate int x = (int) (temp.getKey().getX() - (destinationRadius)); int y = (int) (temp.getKey().getY() - (destinationRadius)); //drawOval draws a circle inside a rectangle bbg.drawOval(x, y, _simState.getDestinationRadius() * 2, _simState.getDestinationRadius() * 2); } // draw each of the agents Iterator<Agent> agentIter = _simState.getAgentIterator(); while (agentIter.hasNext()) { Agent temp = agentIter.next(); if (temp.isAlive()) { // decide whether to color for destination or group // if( isDestinationColors ) // { // // if stopped then blink white and destination color // if( temp.hasReachedDestination() ) // { // if( pulseWhite % 20 == 0 ) // { // bbg.setColor( Color.WHITE ); // } // else // { // bbg.setColor( temp.getDestinationColor() ); // } // } // else // { // bbg.setColor( temp.getDestinationColor() ); // } // } // else // { // // if stopped then blink black and white // if( temp.hasReachedDestination() ) // { // if( pulseWhite % 20 == 0 ) // { // bbg.setColor( Color.WHITE ); // } // else // { // bbg.setColor( temp.getGroup().getGroupColor() ); // } // } // //set color to red if cancelled and global and not multiple initiators // else if(temp.getCurrentDecision().getDecision().getDecisionType().equals( // DecisionType.CANCELLATION ) // && _simState.getCommunicationType().equals( "global" ) // && !Agent.canMultipleInitiate() // ) // { // bbg.setColor( Color.RED ); // } // else // { // bbg.setColor( temp.getGroup().getGroupColor() ); // } // } double dx = temp.getCurrentDestination().getX() - temp.getCurrentLocation().getX(); double dy = temp.getCurrentDestination().getY() - temp.getCurrentLocation().getY(); double heading = Math.atan2(dy, dx); Utils.drawDirectionalTriangle(bbg, heading - Math.PI / 2, temp.getCurrentLocation().getX(), temp.getCurrentLocation().getY(), 7, temp.getPreferredDestination().getColor(), temp.getGroup().getGroupColor()); // bbg.fillOval( (int) temp.getCurrentLocation().getX() - _agentSize, // (int) temp.getCurrentLocation().getY() - _agentSize , _agentSize * 2, _agentSize * 2 ); } } pulseWhite++; bbg.setColor(Color.BLACK); // the total number of groups bbg.setFont(_infoFont); bbg.drawString("Run: " + (_simState.getCurrentSimulationRun() + 1), _fontXOffset, _fontYOffset); bbg.drawString("Time: " + _simState.getSimulationTime(), _fontXOffset, _fontYOffset + _fontSize); bbg.drawString("Delay: " + LIVE_DELAY, _fontXOffset, _fontYOffset + _fontSize * 2); if (_simState.getCommunicationType().equals("global") && !Agent.canMultipleInitiate()) { String initiatorName = "None"; if (_initiatingAgent != null) { initiatorName = _initiatingAgent.getId().toString(); } bbg.drawString("Init: " + initiatorName, _fontXOffset, _fontYOffset + _fontSize * 3); bbg.drawString("Followers: " + _numberFollowing, _fontXOffset, _fontYOffset + _fontSize * 4); } else { bbg.drawString("Groups: " + _simState.getNumberGroups(), _fontXOffset, _fontYOffset + _fontSize * 3); bbg.drawString("Reached: " + _simState.numReachedDestination, _fontXOffset, _fontYOffset + _fontSize * 4); bbg.drawString("Inits: " + _simState.numInitiating, _fontXOffset, _fontYOffset + _fontSize * 5); bbg.drawString("Eaten: " + _simState.getPredator().getTotalAgentsEaten(), _fontXOffset, _fontYOffset + _fontSize * 6); } g.scale(_zoom, _zoom); g.drawImage(_backBuffer, 0, 0, this); if (SHOULD_VIDEO) { // setup to save to a png BufferedImage buff = new BufferedImage(_windowWidth, _windowHeight, BufferedImage.TYPE_INT_RGB); Graphics2D temp = (Graphics2D) buff.getGraphics(); temp.scale(8, 4); temp.drawImage(_backBuffer, 0, 0, this); // sub-directory File dir = new File("video"); dir.mkdir(); // format string for filename String filename = String.format("video/run-%03d-time-%05d.png", _simState.getCurrentSimulationRun(), _simState.getSimulationTime()); File outputfile = new File(filename); // save it try { ImageIO.write(buff, "png", outputfile); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java
public BufferedImage generateImage() throws IOException { final int DEFAULT_CELL_WIDTH = 48; final int DEFAULT_CELL_HEIGHT = 48; final int imgWidth = this.docOptions.getImage() == null ? DEFAULT_CELL_WIDTH * this.docOptions.getColumns() : Math.round(this.docOptions.getImage().getSVGWidth()); final int imgHeight = this.docOptions.getImage() == null ? DEFAULT_CELL_HEIGHT * this.docOptions.getRows() : Math.round(this.docOptions.getImage().getSVGHeight()); final BufferedImage result; if (exportData.isBackgroundImageExport() && this.docOptions.getImage() != null) { result = this.docOptions.getImage().rasterize(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); } else {//w w w . ja v a2 s . co m result = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); } final Graphics2D gfx = result.createGraphics(); gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gfx.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); final HexEngine<Graphics2D> engine = new HexEngine<Graphics2D>(DEFAULT_CELL_WIDTH, DEFAULT_CELL_HEIGHT, this.docOptions.getHexOrientation()); final List<HexFieldLayer> reversedNormalizedStack = new ArrayList<HexFieldLayer>(); for (int i = this.exportData.getLayers().size() - 1; i >= 0; i--) { final LayerExportRecord rec = this.exportData.getLayers().get(i); if (rec.isAllowed()) { reversedNormalizedStack.add(rec.getLayer()); } } if (Thread.currentThread().isInterrupted()) return null; final HexFieldValue[] stackOfValues = new HexFieldValue[reversedNormalizedStack.size()]; engine.setModel(new HexEngineModel<HexFieldValue[]>() { @Override public int getColumnNumber() { return docOptions.getColumns(); } @Override public int getRowNumber() { return docOptions.getRows(); } @Override public HexFieldValue[] getValueAt(final int col, final int row) { Arrays.fill(stackOfValues, null); for (int index = 0; index < reversedNormalizedStack.size(); index++) { stackOfValues[index] = reversedNormalizedStack.get(index).getHexValueAtPos(col, row); } return stackOfValues; } @Override public HexFieldValue[] getValueAt(final HexPosition pos) { return this.getValueAt(pos.getColumn(), pos.getRow()); } @Override public void setValueAt(int col, int row, HexFieldValue[] value) { } @Override public void setValueAt(HexPosition pos, HexFieldValue[] value) { } @Override public boolean isPositionValid(final int col, final int row) { return col >= 0 && col < docOptions.getColumns() && row >= 0 && row < docOptions.getRows(); } @Override public boolean isPositionValid(final HexPosition pos) { return this.isPositionValid(pos.getColumn(), pos.getRow()); } @Override public void attachedToEngine(final HexEngine<?> engine) { } @Override public void detachedFromEngine(final HexEngine<?> engine) { } }); final HexRect2D visibleSize = engine.getVisibleSize(); final float xcoeff = (float) result.getWidth() / visibleSize.getWidth(); final float ycoeff = (float) result.getHeight() / visibleSize.getHeight(); engine.setScale(xcoeff, ycoeff); final Image[][] cachedIcons = new Image[this.exportData.getLayers().size()][]; engine.setRenderer(new ColorHexRender() { private final Stroke stroke = new BasicStroke(docOptions.getLineWidth()); @Override public Stroke getStroke() { return this.stroke; } @Override public Color getFillColor(HexEngineModel<?> model, int col, int row) { return null; } @Override public Color getBorderColor(HexEngineModel<?> model, int col, int row) { return exportData.isExportHexBorders() ? docOptions.getColor() : null; } @Override public void drawExtra(HexEngine<Graphics2D> engine, Graphics2D g, int col, int row, Color borderColor, Color fillColor) { } @Override public void drawUnderBorder(final HexEngine<Graphics2D> engine, final Graphics2D g, final int col, final int row, final Color borderColor, final Color fillColor) { final HexFieldValue[] stackValues = (HexFieldValue[]) engine.getModel().getValueAt(col, row); for (int i = 0; i < stackValues.length; i++) { final HexFieldValue valueToDraw = stackValues[i]; if (valueToDraw == null) { continue; } g.drawImage(cachedIcons[i][valueToDraw.getIndex()], 0, 0, null); } } }); final Path2D hexShape = ((ColorHexRender) engine.getRenderer()).getHexPath(); final int cellWidth = hexShape.getBounds().width; final int cellHeight = hexShape.getBounds().height; for (int layerIndex = 0; layerIndex < reversedNormalizedStack.size() && !Thread.currentThread().isInterrupted(); layerIndex++) { final HexFieldLayer theLayer = reversedNormalizedStack.get(layerIndex); final Image[] cacheLineForLayer = new Image[theLayer.getHexValuesNumber()]; for (int valueIndex = 1; valueIndex < theLayer.getHexValuesNumber(); valueIndex++) { cacheLineForLayer[valueIndex] = theLayer.getHexValueForIndex(valueIndex).makeIcon(cellWidth, cellHeight, hexShape, true); } cachedIcons[layerIndex] = cacheLineForLayer; } engine.drawWithThreadInterruptionCheck(gfx); if (Thread.currentThread().isInterrupted()) return null; if (this.exportData.isCellCommentariesExport()) { final Iterator<Entry<HexPosition, String>> iterator = this.cellComments.iterator(); gfx.setFont(new Font("Arial", Font.BOLD, 12)); while (iterator.hasNext() && !Thread.currentThread().isInterrupted()) { final Entry<HexPosition, String> item = iterator.next(); final HexPosition pos = item.getKey(); final String text = item.getValue(); final float x = engine.calculateX(pos.getColumn(), pos.getRow()); final float y = engine.calculateY(pos.getColumn(), pos.getRow()); final Rectangle2D textBounds = gfx.getFontMetrics().getStringBounds(text, gfx); final float dx = x - ((float) textBounds.getWidth() - engine.getCellWidth()) / 2; gfx.setColor(Color.BLACK); gfx.drawString(text, dx, y); gfx.setColor(Color.WHITE); gfx.drawString(text, dx - 2, y - 2); } } gfx.dispose(); return result; }
From source file:de.tor.tribes.ui.panels.MinimapPanel.java
private boolean redraw() { Village[][] mVisibleVillages = DataHolder.getSingleton().getVillages(); if (mVisibleVillages == null || mBuffer == null) { return false; }//from w ww.java2 s. c o m Graphics2D g2d = (Graphics2D) mBuffer.getGraphics(); Composite tempC = g2d.getComposite(); //clear g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR)); g2d.fillRect(0, 0, mBuffer.getWidth(), mBuffer.getHeight()); //reset composite g2d.setComposite(tempC); boolean markPlayer = GlobalOptions.getProperties().getBoolean("mark.villages.on.minimap"); if (ServerSettings.getSingleton().getMapDimension() == null) { //could not draw minimap if dimensions are not loaded yet return false; } boolean showBarbarian = GlobalOptions.getProperties().getBoolean("show.barbarian"); Color DEFAULT = Constants.DS_DEFAULT_MARKER; try { int mark = Integer.parseInt(GlobalOptions.getProperty("default.mark")); if (mark == 0) { DEFAULT = Constants.DS_DEFAULT_MARKER; } else if (mark == 1) { DEFAULT = Color.RED; } else if (mark == 2) { DEFAULT = Color.WHITE; } } catch (Exception e) { DEFAULT = Constants.DS_DEFAULT_MARKER; } Rectangle mapDim = ServerSettings.getSingleton().getMapDimension(); double wField = mapDim.getWidth() / (double) visiblePart.width; double hField = mapDim.getHeight() / (double) visiblePart.height; UserProfile profile = GlobalOptions.getSelectedProfile(); Tribe currentTribe = InvalidTribe.getSingleton(); if (profile != null) { currentTribe = profile.getTribe(); } for (int i = visiblePart.x; i < (visiblePart.width + visiblePart.x); i++) { for (int j = visiblePart.y; j < (visiblePart.height + visiblePart.y); j++) { Village v = mVisibleVillages[i][j]; if (v != null) { Color markerColor = null; boolean isLeft = false; if (v.getTribe() == Barbarians.getSingleton()) { isLeft = true; } else { if ((currentTribe != null) && (v.getTribe().getId() == currentTribe.getId())) { //village is owned by current player. mark it dependent on settings if (markPlayer) { markerColor = Color.YELLOW; } } else { try { Marker marker = MarkerManager.getSingleton().getMarker(v.getTribe()); if (marker != null && !marker.isShownOnMap()) { marker = null; markerColor = DEFAULT; } if (marker == null) { marker = MarkerManager.getSingleton().getMarker(v.getTribe().getAlly()); if (marker != null && marker.isShownOnMap()) { markerColor = marker.getMarkerColor(); } } else { if (marker.isShownOnMap()) { markerColor = marker.getMarkerColor(); } } } catch (Exception e) { markerColor = null; } } } if (!isLeft) { if (markerColor != null) { g2d.setColor(markerColor); } else { g2d.setColor(DEFAULT); } g2d.fillRect((int) Math.round((i - visiblePart.x) * wField), (int) Math.round((j - visiblePart.y) * hField), (int) Math.floor(wField), (int) Math.floor(hField)); } else { if (showBarbarian) { g2d.setColor(Color.LIGHT_GRAY); g2d.fillRect((int) Math.round((i - visiblePart.x) * wField), (int) Math.round((j - visiblePart.y) * hField), (int) Math.floor(wField), (int) Math.floor(hField)); } } } } } try { if (GlobalOptions.getProperties().getBoolean("map.showcontinents")) { g2d.setColor(Color.BLACK); Composite c = g2d.getComposite(); Composite a = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f); Font f = g2d.getFont(); Font t = new Font("Serif", Font.BOLD, (int) Math.round(30 * hField)); g2d.setFont(t); int fact = 10; int mid = (int) Math.round(50 * wField); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { g2d.setComposite(a); String conti = "K" + (j * 10 + i); Rectangle2D bounds = g2d.getFontMetrics(t).getStringBounds(conti, g2d); int cx = i * fact * 10 - visiblePart.x; int cy = j * fact * 10 - visiblePart.y; cx = (int) Math.round(cx * wField); cy = (int) Math.round(cy * hField); g2d.drawString(conti, (int) Math.rint(cx + mid - bounds.getWidth() / 2), (int) Math.rint(cy + mid + bounds.getHeight() / 2)); g2d.setComposite(c); int wk = 100; int hk = 100; if (i == 9) { wk -= 1; } if (j == 9) { hk -= 1; } g2d.drawRect(cx, cy, (int) Math.round(wk * wField), (int) Math.round(hk * hField)); } } g2d.setFont(f); } } catch (Exception e) { logger.error("Creation of Minimap failed", e); } g2d.dispose(); return true; }
From source file:org.forester.archaeopteryx.TreePanel.java
final private void paintConfidenceValues(final Graphics2D g, final PhylogenyNode node, final boolean to_pdf, final boolean to_graphics_file) { String conf_str = ""; final List<Confidence> confidences = node.getBranchData().getConfidences(); if (confidences.size() == 1) { final double value = node.getBranchData().getConfidence(0).getValue(); if ((value == Confidence.CONFIDENCE_DEFAULT_VALUE) || (value < getOptions().getMinConfidenceValue())) { return; }//from w w w.j a va 2 s.c om conf_str = FORMATTER_CONFIDENCE.format(value); } else if (confidences.size() > 1) { boolean one_ok = false; boolean not_first = false; Collections.sort(confidences); final StringBuilder sb = new StringBuilder(); for (final Confidence confidence : confidences) { final double value = confidence.getValue(); if (value != Confidence.CONFIDENCE_DEFAULT_VALUE) { if (value >= getOptions().getMinConfidenceValue()) { one_ok = true; } if (not_first) { sb.append("/"); } else { not_first = true; } sb.append(FORMATTER_CONFIDENCE.format(ForesterUtil.round(value, getOptions().getNumberOfDigitsAfterCommaForConfidenceValues()))); } } if (one_ok) { conf_str = sb.toString(); } } if (conf_str.length() > 0) { final double parent_x = node.getParent().getXcoord(); double x = node.getXcoord(); g.setFont(getTreeFontSet().getSmallFont()); if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE) { x += EURO_D; } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED) { x += ROUNDED_D; } if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) { g.setColor(Color.BLACK); } else { g.setColor(getTreeColorSet().getConfidenceColor()); } TreePanel.drawString(conf_str, parent_x + ((x - parent_x - getTreeFontSet()._fm_small.stringWidth(conf_str)) / 2), (node.getYcoord() + getTreeFontSet()._small_max_ascent) - 1, g); } }
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);/*from w w w . jav a 2 s. 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:de.laures.cewolf.jfree.ThermometerPlot.java
/** * Draws the plot on a Java 2D graphics device (such as the screen or a printer). * * @param g2 the graphics device.//from w w w . j av a2 s . c om * @param area the area within which the plot should be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState the state from the parent plot, if there is one. * @param info collects info about the drawing. */ public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { RoundRectangle2D outerStem = new RoundRectangle2D.Double(); RoundRectangle2D innerStem = new RoundRectangle2D.Double(); RoundRectangle2D mercuryStem = new RoundRectangle2D.Double(); Ellipse2D outerBulb = new Ellipse2D.Double(); Ellipse2D innerBulb = new Ellipse2D.Double(); String temp = null; FontMetrics metrics = null; if (info != null) { info.setPlotArea(area); } // adjust for insets... RectangleInsets insets = getInsets(); insets.trim(area); drawBackground(g2, area); // adjust for padding... Rectangle2D interior = (Rectangle2D) area.clone(); this.padding.trim(interior); int midX = (int) (interior.getX() + (interior.getWidth() / 2)); int midY = (int) (interior.getY() + (interior.getHeight() / 2)); int stemTop = (int) (interior.getMinY() + getBulbRadius()); int stemBottom = (int) (interior.getMaxY() - getBulbDiameter()); Rectangle2D dataArea = new Rectangle2D.Double(midX - getColumnRadius(), stemTop, getColumnRadius(), stemBottom - stemTop); outerBulb.setFrame(midX - getBulbRadius(), stemBottom, getBulbDiameter(), getBulbDiameter()); outerStem.setRoundRect(midX - getColumnRadius(), interior.getMinY(), getColumnDiameter(), stemBottom + getBulbDiameter() - stemTop, getColumnDiameter(), getColumnDiameter()); Area outerThermometer = new Area(outerBulb); Area tempArea = new Area(outerStem); outerThermometer.add(tempArea); innerBulb.setFrame(midX - getBulbRadius() + getGap(), stemBottom + getGap(), getBulbDiameter() - getGap() * 2, getBulbDiameter() - getGap() * 2); innerStem.setRoundRect(midX - getColumnRadius() + getGap(), interior.getMinY() + getGap(), getColumnDiameter() - getGap() * 2, stemBottom + getBulbDiameter() - getGap() * 2 - stemTop, getColumnDiameter() - getGap() * 2, getColumnDiameter() - getGap() * 2); Area innerThermometer = new Area(innerBulb); tempArea = new Area(innerStem); innerThermometer.add(tempArea); if ((this.dataset != null) && (this.dataset.getValue() != null)) { double current = this.dataset.getValue().doubleValue(); double ds = this.rangeAxis.valueToJava2D(current, dataArea, RectangleEdge.LEFT); int i = getColumnDiameter() - getGap() * 2; // already calculated int j = getColumnRadius() - getGap(); // already calculated int l = (i / 2); int k = (int) Math.round(ds); if (k < (getGap() + interior.getMinY())) { k = (int) (getGap() + interior.getMinY()); l = getBulbRadius(); } Area mercury = new Area(innerBulb); if (k < (stemBottom + getBulbRadius())) { mercuryStem.setRoundRect(midX - j, k, i, (stemBottom + getBulbRadius()) - k, l, l); tempArea = new Area(mercuryStem); mercury.add(tempArea); } g2.setPaint(getCurrentPaint()); g2.fill(mercury); // draw range indicators... if (this.subrangeIndicatorsVisible) { g2.setStroke(this.subrangeIndicatorStroke); Range range = this.rangeAxis.getRange(); // draw start of normal range double value = this.subrangeInfo[NORMAL][RANGE_LOW]; if (range.contains(value)) { double x = midX + getColumnRadius() + 2; double y = this.rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(x, y, x + 10, y); g2.setPaint(this.subrangePaint[NORMAL]); g2.draw(line); } // draw start of warning range value = this.subrangeInfo[WARNING][RANGE_LOW]; if (range.contains(value)) { double x = midX + getColumnRadius() + 2; double y = this.rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(x, y, x + 10, y); g2.setPaint(this.subrangePaint[WARNING]); g2.draw(line); } // draw start of critical range value = this.subrangeInfo[CRITICAL][RANGE_LOW]; if (range.contains(value)) { double x = midX + getColumnRadius() + 2; double y = this.rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(x, y, x + 10, y); g2.setPaint(this.subrangePaint[CRITICAL]); g2.draw(line); } } // draw the axis... if ((this.rangeAxis != null) && (this.axisLocation != NONE)) { int drawWidth = AXIS_GAP; Rectangle2D drawArea; double cursor = 0; switch (this.axisLocation) { case RIGHT: cursor = midX + getColumnRadius(); drawArea = new Rectangle2D.Double(cursor, stemTop, drawWidth, (stemBottom - stemTop + 1)); this.rangeAxis.draw(g2, cursor, area, drawArea, RectangleEdge.RIGHT, null); break; case LEFT: default: //cursor = midX - COLUMN_RADIUS - AXIS_GAP; cursor = midX - getColumnRadius(); drawArea = new Rectangle2D.Double(cursor, stemTop, drawWidth, (stemBottom - stemTop + 1)); this.rangeAxis.draw(g2, cursor, area, drawArea, RectangleEdge.LEFT, null); break; } } // draw text value on screen g2.setFont(this.valueFont); g2.setPaint(this.valuePaint); metrics = g2.getFontMetrics(); switch (this.valueLocation) { case RIGHT: g2.drawString(this.valueFormat.format(current), midX + getColumnRadius() + getGap(), midY); break; case LEFT: String valueString = this.valueFormat.format(current); int stringWidth = metrics.stringWidth(valueString); g2.drawString(valueString, midX - getColumnRadius() - getGap() - stringWidth, midY); break; case BULB: temp = this.valueFormat.format(current); i = metrics.stringWidth(temp) / 2; g2.drawString(temp, midX - i, stemBottom + getBulbRadius() + getGap()); break; default: } /***/ } g2.setPaint(this.thermometerPaint); g2.setFont(this.valueFont); // draw units indicator metrics = g2.getFontMetrics(); int tickX1 = midX - getColumnRadius() - getGap() * 2 - metrics.stringWidth(UNITS[this.units]); if (tickX1 > area.getMinX()) { g2.drawString(UNITS[this.units], tickX1, (int) (area.getMinY() + 20)); } // draw thermometer outline g2.setStroke(this.thermometerStroke); g2.draw(outerThermometer); g2.draw(innerThermometer); drawOutline(g2, area); }
From source file:org.pmedv.blackboard.components.BoardEditor.java
@Override protected void paintComponent(Graphics g) { Boolean useLayerColor = (Boolean) Preferences.values .get("org.pmedv.blackboard.BoardDesignerPerspective.useLayerColor"); // clear all // g.clearRect(0, 0, getWidth(), getHeight()); g.setColor(BLANK);//from w w w .j av a2 s. c o m g.fillRect(0, 0, getWidth(), getHeight()); // some nice anti aliasing... Graphics2D g2 = (Graphics2D) g; RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2.setRenderingHints(rh); // TODO : Should this be done here? // Sort layers by z-index g2.setColor(Color.LIGHT_GRAY); g2.setStroke(BoardUtil.stroke_1_0f); Collections.sort(model.getLayers()); for (int i = model.getLayers().size() - 1; i >= 0; i--) { // Sort items by z-index Collections.sort(model.getLayers().get(i).getItems()); drawLayer(model.getLayers().get(i), g2); } // draw selection border if (state.equals(SelectionState.DRAGGING_NEW_SELECTION) && button1Pressed) { g2.setColor(Color.GREEN); g2.setStroke(BoardUtil.stroke_1_0f); if (dragStopX < dragStartX && dragStopY > dragStartY) { selectionBorder.setSize(dragStartX - dragStopX, dragStopY - dragStartY); selectionBorder.setLocation(dragStopX, dragStartY); } else if (dragStopY < dragStartY && dragStopX > dragStartX) { selectionBorder.setSize(dragStopX - dragStartX, dragStartY - dragStopY); selectionBorder.setLocation(dragStartX, dragStopY); } else if (dragStopX < dragStartX && dragStopY < dragStartY) { selectionBorder.setSize(dragStartX - dragStopX, dragStartY - dragStopY); selectionBorder.setLocation(dragStopX, dragStopY); } else { selectionBorder.setSize(dragStopX - dragStartX, dragStopY - dragStartY); selectionBorder.setLocation(dragStartX, dragStartY); } g2.draw(selectionBorder); } // display shape currently being drawed if (lineStartX > 0 && lineStartY > 0 && lineStopX > 0 && lineStopY > 0) { if (useLayerColor) g2.setColor(model.getCurrentLayer().getColor()); else g2.setColor(palette.getCurrentColor()); g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem()); // draw new line if (editorMode.equals(EditorMode.DRAW_LINE)) { if (useLayerColor) currentDrawingLine.setColor(model.getCurrentLayer().getColor()); else currentDrawingLine.setColor(palette.getCurrentColor()); currentDrawingLine.setStartType((LineEdgeType) shapesPanel.getStartLineCombo().getSelectedItem()); currentDrawingLine.setEndType((LineEdgeType) shapesPanel.getEndLineCombo().getSelectedItem()); currentDrawingLine.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem()); currentDrawingLine.getStart().setLocation(lineStartX, lineStartY); currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY); currentDrawingLine.draw(g2); } else if (editorMode.equals(EditorMode.DRAW_MEASURE)) { currentDrawingLine.setStroke(Measure.DEFAULT_STROKE); currentDrawingLine.getStart().setLocation(lineStartX, lineStartY); currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY); currentDrawingLine.draw(g2); } // draw new box or ellipse else if (editorMode.equals(EditorMode.DRAW_RECTANGLE) || editorMode.equals(EditorMode.DRAW_ELLIPSE)) { int xLoc = lineStartX; int yLoc = lineStartY; int width = lineStopX - lineStartX; int height = lineStopY - lineStartY; ShapeStyle style = (ShapeStyle) shapesPanel.getStyleCombo().getSelectedItem(); if (style == null || style.equals(ShapeStyle.FILLED)) { if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) { g2.fillRect(xLoc, yLoc, width, height); } else { g2.fillOval(xLoc, yLoc, width, height); } } else if (style.equals(ShapeStyle.OUTLINED)) { g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem()); if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) { g2.drawRect(xLoc, yLoc, width, height); } else { g2.drawOval(xLoc, yLoc, width, height); } } } } // draw selection handles if (selectedItem != null) { g2.setStroke(BoardUtil.stroke_1_0f); g2.setColor(Color.GREEN); selectedItem.drawHandles(g2, 8); } // draw border if (zoomLayer != null) { TransformUI ui = (TransformUI) (Object) zoomLayer.getUI(); DefaultTransformModel xmodel = (DefaultTransformModel) ui.getModel(); if (xmodel.isMirror()) { g2.setColor(Color.RED); } else { g2.setColor(Color.GREEN); } } else { g2.setColor(Color.GREEN); } g2.setStroke(DEFAULT_STROKE); Rectangle border = new Rectangle(0, 0, model.getWidth() - 1, model.getHeight() - 1); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g2.draw(border); if (model.getType().equals(BoardType.STRIPES) || model.getType().equals(BoardType.HOLES)) { g2.setColor(Color.BLACK); g2.setFont(miniFont); int index = 1; for (int x = 12; x < model.getWidth() - 16; x += 16) { g2.drawString(String.valueOf(index++), x, 8); } index = 1; for (int y = 18; y < model.getHeight(); y += 16) { g2.drawString(String.valueOf(index++), 3, y); } } if (editorMode.equals(EditorMode.CHECK_CONNECTIONS)) { if (connectedLines != null) { for (Line line : connectedLines) { line.drawFat(g2); } } } if (drawing) { g2.setColor(Color.BLUE); g2.setStroke(DEFAULT_STROKE); if (selectedPin != null) { g2.drawRect(lineStopX - 8, lineStopY - 8, 16, 16); } } super.paintComponents(g2); }
From source file:fr.fg.server.core.TerritoryManager.java
private static BufferedImage createTerritoryMap(int idSector) { List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector)); float[][] points = new float[areas.size()][2]; int[] dominatingAllies = new int[areas.size()]; int i = 0;/*from w ww .j a va 2 s .c om*/ for (Area area : areas) { points[i][0] = area.getX() * MAP_SCALE; points[i][1] = area.getY() * MAP_SCALE; dominatingAllies[i] = area.getIdDominatingAlly(); i++; } Hull hull = new Hull(points); MPolygon hullPolygon = hull.getRegion(); float[][] newPoints = new float[points.length + hullPolygon.count()][2]; System.arraycopy(points, 0, newPoints, 0, points.length); float[][] hullCoords = hullPolygon.getCoords(); for (i = 0; i < hullPolygon.count(); i++) { double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]); double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]); newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE)); newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE)); } points = newPoints; Voronoi voronoi = new Voronoi(points); Delaunay delaunay = new Delaunay(points); // Dcoupage en rgions MPolygon[] regions = voronoi.getRegions(); // Calcule le rayon de la galaxie int radius = 0; for (Area area : areas) { radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY()); } radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE; int diameter = 2 * radius + 1; // Construit l'image avec les quadrants BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) territoriesImage.getGraphics(); // Affecte une couleur chaque alliance HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>(); for (Area area : areas) { int idDominatingAlly = area.getIdDominatingAlly(); if (idDominatingAlly != 0) alliesColors.put(idDominatingAlly, Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]); } Polygon[] polygons = new Polygon[regions.length]; for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] != 0) { polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3); } } // Dessine tous les secteurs g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] == 0) continue; Polygon p = polygons[i]; // Dessine le polygone g.setColor(alliesColors.get(dominatingAllies[i])); g.fill(p); // Rempli les espaces entre les polygones adjacents qui // correspondent au territoire d'une mme alliance int[] linkedRegions = delaunay.getLinked(i); for (int j = 0; j < linkedRegions.length; j++) { int linkedRegion = linkedRegions[j]; if (linkedRegion >= areas.size()) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) { if (linkedRegion <= i) continue; float[][] coords1 = regions[i].getCoords(); float[][] coords2 = regions[linkedRegion].getCoords(); int junctionIndex = 0; int[][] junctions = new int[2][2]; search: for (int k = 0; k < coords1.length; k++) { for (int l = 0; l < coords2.length; l++) { if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) { junctions[junctionIndex][0] = k; junctions[junctionIndex][1] = l; junctionIndex++; if (junctionIndex == 2) { int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]], polygons[linkedRegion].xpoints[junctions[0][1]], polygons[linkedRegion].xpoints[junctions[1][1]], polygons[i].xpoints[junctions[1][0]], }; int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]], polygons[linkedRegion].ypoints[junctions[0][1]], polygons[linkedRegion].ypoints[junctions[1][1]], polygons[i].ypoints[junctions[1][0]], }; Polygon border = new Polygon(xpts, ypts, 4); g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND)); g.fill(border); g.draw(border); break search; } break; } } } } } } // Dessine des lignes de contours des territoires g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] == 0) continue; g.setStroke(new BasicStroke(1.5f)); g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter()); float[][] coords1 = regions[i].getCoords(); lines: for (int j = 0; j < coords1.length; j++) { int[] linkedRegions = delaunay.getLinked(i); for (int k = 0; k < linkedRegions.length; k++) { int linkedRegion = linkedRegions[k]; if (linkedRegion >= areas.size()) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) { float[][] coords2 = regions[linkedRegion].getCoords(); for (int m = 0; m < coords2.length; m++) { if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1] && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1) % coords2.length][0] && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1) % coords2.length][1]) || (coords1[(j + 1) % coords1.length][0] == coords2[(m - 1 + coords2.length) % coords2.length][0] && coords1[(j + 1) % coords1.length][1] == coords2[(m - 1 + coords2.length) % coords2.length][1]))) { continue lines; } } } } g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]), Math.round(polygons[i].xpoints[(j + 1) % coords1.length]), Math.round(polygons[i].ypoints[(j + 1) % coords1.length])); } for (int j = 0; j < coords1.length; j++) { int neighbours = 0; int lastNeighbourRegion = -1; int neighbourCoordsIndex = -1; int[] linkedRegions = delaunay.getLinked(i); for (int k = 0; k < linkedRegions.length; k++) { int linkedRegion = linkedRegions[k]; if (linkedRegion >= areas.size()) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) { float[][] coords2 = regions[linkedRegion].getCoords(); for (int m = 0; m < coords2.length; m++) { if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) { neighbours++; lastNeighbourRegion = linkedRegion; neighbourCoordsIndex = m; break; } } } } if (neighbours == 1) { g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]), Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]), Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex])); } } } BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB); g = (Graphics2D) finalImage.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f)); g.drawImage(territoriesImage, 0, 0, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f)); // Charge la police pour afficher le nom des alliances try { Font textFont = Font.createFont(Font.TRUETYPE_FONT, Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf")); textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD); g.setFont(textFont); } catch (Exception e) { LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e); } FontMetrics fm = g.getFontMetrics(); ArrayList<Integer> closedRegions = new ArrayList<Integer>(); for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] == 0 || closedRegions.contains(i)) continue; ArrayList<Integer> allyRegions = new ArrayList<Integer>(); ArrayList<Integer> openRegions = new ArrayList<Integer>(); openRegions.add(i); while (openRegions.size() > 0) { int currentRegion = openRegions.remove(0); allyRegions.add(currentRegion); closedRegions.add(currentRegion); int[] linkedRegions = delaunay.getLinked(currentRegion); for (int k = 0; k < linkedRegions.length; k++) { int linkedRegion = linkedRegions[k]; if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion) || allyRegions.contains(linkedRegion)) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) openRegions.add(linkedRegion); } } Area area = areas.get(i); long xsum = 0; long ysum = 0; for (int k = 0; k < allyRegions.size(); k++) { int allyRegion = allyRegions.get(k); area = areas.get(allyRegion); xsum += area.getX(); ysum += area.getY(); } int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1; int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1; ; Point point = new Point(x, y); boolean validLocation = false; for (int k = 0; k < allyRegions.size(); k++) { int allyRegion = allyRegions.get(k); if (polygons[allyRegion].contains(point)) { validLocation = true; break; } } if (validLocation) { if (allyRegions.size() == 1) y -= 14; } else { int xmid = (int) (xsum / allyRegions.size()); int ymid = (int) (ysum / allyRegions.size()); area = areas.get(i); int dx = area.getX() - xmid; int dy = area.getY() - ymid; int distance = dx * dx + dy * dy; int nearestAreaIndex = i; int nearestDistance = distance; for (int k = 0; k < allyRegions.size(); k++) { int allyRegion = allyRegions.get(k); area = areas.get(allyRegion); dx = area.getX() - xmid; dy = area.getY() - ymid; distance = dx * dx + dy * dy; if (distance < nearestDistance) { nearestAreaIndex = allyRegion; nearestDistance = distance; } } area = areas.get(nearestAreaIndex); x = area.getX() * MAP_SCALE + radius + 1; y = -area.getY() * MAP_SCALE + radius - 13; } // Dessine le tag de l'alliance String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]"; g.setColor(Color.BLACK); g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y); g.setColor(alliesColors.get(dominatingAllies[i])); g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y); } return finalImage; }
From source file:org.forester.archaeopteryx.TreePanel.java
final private void paintNodeDataUnrootedCirc(final Graphics2D g, final PhylogenyNode node, final boolean to_pdf, final boolean to_graphics_file, final boolean radial_labels, final double ur_angle, final boolean is_in_found_nodes) { if (isNodeDataInvisibleUnrootedCirc(node) && !to_graphics_file && !to_pdf) { return;//w w w.j a v a 2 s. c o m } if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) { g.setColor(Color.BLACK); } else if (is_in_found_nodes) { g.setColor(getTreeColorSet().getFoundColor()); } else if (getControlPanel().isColorAccordingToTaxonomy()) { g.setColor(getTaxonomyBasedColor(node)); } else { g.setColor(getTreeColorSet().getSequenceColor()); } _sb.setLength(0); _sb.append(" "); if (node.getNodeData().isHasTaxonomy() && (getControlPanel().isShowTaxonomyCode() || getControlPanel().isShowTaxonomyNames())) { final Taxonomy taxonomy = node.getNodeData().getTaxonomy(); if (_control_panel.isShowTaxonomyCode() && !ForesterUtil.isEmpty(taxonomy.getTaxonomyCode())) { _sb.append(taxonomy.getTaxonomyCode()); _sb.append(" "); } if (_control_panel.isShowTaxonomyNames()) { if (!ForesterUtil.isEmpty(taxonomy.getScientificName()) && !ForesterUtil.isEmpty(taxonomy.getCommonName())) { _sb.append(taxonomy.getScientificName()); _sb.append(" ("); _sb.append(taxonomy.getCommonName()); _sb.append(") "); } else if (!ForesterUtil.isEmpty(taxonomy.getScientificName())) { _sb.append(taxonomy.getScientificName()); _sb.append(" "); } else if (!ForesterUtil.isEmpty(taxonomy.getCommonName())) { _sb.append(taxonomy.getCommonName()); _sb.append(" "); } } } if (node.isCollapse() && ((!node.isRoot() && !node.getParent().isCollapse()) || node.isRoot())) { _sb.append(" ["); _sb.append(node.getAllExternalDescendants().size()); _sb.append("]"); } if (getControlPanel().isShowNodeNames() && (node.getNodeName().length() > 0)) { if (_sb.length() > 0) { _sb.append(" "); } _sb.append(node.getNodeName()); } if (node.getNodeData().isHasSequence()) { if (getControlPanel().isShowSequenceAcc() && (node.getNodeData().getSequence().getAccession() != null)) { if (_sb.length() > 0) { _sb.append(" "); } if (!ForesterUtil.isEmpty(node.getNodeData().getSequence().getAccession().getSource())) { _sb.append(node.getNodeData().getSequence().getAccession().getSource()); _sb.append(":"); } _sb.append(node.getNodeData().getSequence().getAccession().getValue()); } if (getControlPanel().isShowGeneNames() && (node.getNodeData().getSequence().getName().length() > 0)) { // if ( _sb.length() > 0 ) { // _sb.append( " " ); // } // _sb.append( node.getNodeData().getSequence().getName() ); PhylogenyNode parent = node.getParent(); double x1 = parent.getXcoord(); double y1 = parent.getYcoord(); double x2 = node.getXcoord(); double y2 = node.getYcoord(); double above_the_line = 1.0; if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED) { double center_of_branch_x = Math.abs(x1 + x2) / 2.0; double center_of_branch_y = Math.abs(y1 + y2) / 2.0; TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x, center_of_branch_y - above_the_line, g); } } } g.setFont(getTreeFontSet().getLargeFont()); if (is_in_found_nodes) { g.setFont(getTreeFontSet().getLargeFont().deriveFont(Font.BOLD)); } if (_sb.length() > 1) { final String sb_str = _sb.toString(); double m = 0; if (_graphics_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR) { m = _urt_nodeid_angle_map.get(node.getNodeId()) % TWO_PI; } else { m = (float) (ur_angle % TWO_PI); } _at = g.getTransform(); boolean need_to_reset = false; final float x_coord = node.getXcoord(); final float y_coord = node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / 3.0f); if (radial_labels) { need_to_reset = true; boolean left = false; if ((m > HALF_PI) && (m < ONEHALF_PI)) { m -= PI; left = true; } g.rotate(m, x_coord, node.getYcoord()); if (left) { g.translate(-(getTreeFontSet()._fm_large.getStringBounds(sb_str, g).getWidth()), 0); } } else { if ((m > HALF_PI) && (m < ONEHALF_PI)) { need_to_reset = true; g.translate(-getTreeFontSet()._fm_large.getStringBounds(sb_str, g).getWidth(), 0); } } TreePanel.drawString(sb_str, x_coord, y_coord, g); if (need_to_reset) { g.setTransform(_at); } } }
From source file:org.forester.archaeopteryx.TreePanel.java
final private void paintNodeData(final Graphics2D g, final PhylogenyNode node, final boolean to_graphics_file, final boolean to_pdf, final boolean is_in_found_nodes) { if (isNodeDataInvisible(node) && !to_graphics_file && !to_pdf) { return;/*from ww w . j ava 2 s. c o m*/ } if (getOptions().isShowBranchLengthValues() && ((getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR) || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED) || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE)) && (!node.isRoot()) && (node.getDistanceToParent() != PhylogenyNode.DISTANCE_DEFAULT)) { paintBranchLength(g, node, to_pdf, to_graphics_file); } if (!getControlPanel().isShowInternalData() && !node.isExternal() && !node.isCollapse()) { return; } int x = 0; if (node.getNodeData().isHasTaxonomy() && (getControlPanel().isShowTaxonomyCode() || getControlPanel().isShowTaxonomyNames())) { x = paintTaxonomy(g, node, is_in_found_nodes, to_pdf, to_graphics_file); } if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) { g.setColor(Color.BLACK); } else if (is_in_found_nodes) { g.setColor(getTreeColorSet().getFoundColor()); } else if (getControlPanel().isColorAccordingToTaxonomy()) { g.setColor(getTaxonomyBasedColor(node)); } else { g.setColor(getTreeColorSet().getSequenceColor()); } _sb.setLength(0); if (node.isCollapse() && ((!node.isRoot() && !node.getParent().isCollapse()) || node.isRoot())) { _sb.append(" ["); _sb.append(node.getAllExternalDescendants().size()); _sb.append("]"); } if (getControlPanel().isShowNodeNames() && (node.getNodeName().length() > 0)) { if (_sb.length() > 0) { _sb.append(" "); } _sb.append(node.getNodeName()); } if (node.getNodeData().isHasSequence()) { if (getControlPanel().isShowGeneSymbols() && (node.getNodeData().getSequence().getSymbol().length() > 0)) { if (_sb.length() > 0) { _sb.append(" "); } _sb.append(node.getNodeData().getSequence().getSymbol()); } if (getControlPanel().isShowGeneNames() && (node.getNodeData().getSequence().getName().length() > 0)) { // if ( _sb.length() > 0 ) { // _sb.append( " " ); // } // _sb.append( node.getNodeData().getSequence().getName() ); PhylogenyNode parent = node.getParent(); double x1 = parent.getXcoord(); double y1 = parent.getYcoord(); double x2 = node.getXcoord(); double y2 = node.getYcoord(); double above_the_line = 1.0; if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR) { double center_of_branch_x = Math.abs(x1 + x2) / 2.0; double center_of_branch_y = Math.abs(y1 + y2) / 2.0; TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x, center_of_branch_y - above_the_line, g); } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR) { double center_of_branch_x = Math.abs(x1 + x2) / 2.0; double center_of_branch_y = y2; TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x, center_of_branch_y - above_the_line, g); } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED) { double center_of_branch_x = Math.abs(x1 + x2) / 2.0; double center_of_branch_y = y2; TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x, center_of_branch_y - above_the_line, g); } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE) { double center_of_branch_x = Math.abs(x1 + x2) / 2.0 + EURO_D; double center_of_branch_y = y2; TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x, center_of_branch_y - above_the_line, g); } } if (getControlPanel().isShowSequenceAcc() && (node.getNodeData().getSequence().getAccession() != null)) { if (_sb.length() > 0) { _sb.append(" "); } if (!ForesterUtil.isEmpty(node.getNodeData().getSequence().getAccession().getSource())) { _sb.append(node.getNodeData().getSequence().getAccession().getSource()); _sb.append(":"); } _sb.append(node.getNodeData().getSequence().getAccession().getValue()); } } g.setFont(getTreeFontSet().getLargeFont()); if (is_in_found_nodes) { g.setFont(getTreeFontSet().getLargeFont().deriveFont(Font.BOLD)); } double down_shift_factor = 3.0; if (!node.isExternal() && (node.getNumberOfDescendants() == 1)) { down_shift_factor = 1; } // GUILHEM_BEG ______________ final double posX = node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE; final double posY = (node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor)); final int CONFIDENCE_LEFT_MARGIN = 4; final String sNodeText = _sb.toString(); if (_control_panel.isShowSequenceRelations() && node.getNodeData().isHasSequence() && (_query_sequence != null)) { int nodeTextBoundsWidth = 0; if (sNodeText.length() > 0) { final Rectangle2D node_text_bounds = new TextLayout(sNodeText, g.getFont(), _frc).getBounds(); //would like to remove this 'new', but how... nodeTextBoundsWidth = (int) node_text_bounds.getWidth(); } if (node.getNodeData().getSequence().equals(_query_sequence)) { if (nodeTextBoundsWidth > 0) { // invert font color and background color to show that this is the query sequence g.fillRect((int) posX - 1, (int) posY - 8, nodeTextBoundsWidth + 5, 11); g.setColor(getTreeColorSet().getBackgroundColor()); } } else { final List<SequenceRelation> seqRelations = node.getNodeData().getSequence().getSequenceRelations(); for (final SequenceRelation seqRelation : seqRelations) { final boolean fGotRelationWithQuery = (seqRelation.getRef0().isEqual(_query_sequence) || seqRelation.getRef1().isEqual(_query_sequence)) && seqRelation.getType() .equals(getControlPanel().getSequenceRelationTypeBox().getSelectedItem()); if (fGotRelationWithQuery) { // we will underline the text to show that this sequence is ortholog to the query final double linePosX = node.getXcoord() + 2 + TreePanel.HALF_BOX_SIZE; final String sConfidence = (!getControlPanel().isShowSequenceRelationConfidence() || (seqRelation.getConfidence() == null)) ? null : " (" + seqRelation.getConfidence().getValue() + ")"; if (sConfidence != null) { double confidenceX = posX; if (sNodeText.length() > 0) { confidenceX += new TextLayout(sNodeText, g.getFont(), _frc).getBounds().getWidth() + CONFIDENCE_LEFT_MARGIN; } if (confidenceX > linePosX) { // let's only display confidence value if we are already displaying at least one of Prot/Gene Name and Taxonomy Code final int confidenceWidth = (int) new TextLayout(sConfidence, g.getFont(), _frc) .getBounds().getWidth(); TreePanel.drawString(sConfidence, confidenceX, posY, g); x += CONFIDENCE_LEFT_MARGIN + confidenceWidth; } } if (x + nodeTextBoundsWidth > 0) /* we only underline if there is something displayed */ { if (nodeTextBoundsWidth == 0) { nodeTextBoundsWidth -= 3; /* the gap between taxonomy code and node name should not be underlined if nothing comes after it */ } else { nodeTextBoundsWidth += 2; } g.drawLine((int) linePosX + 1, 3 + (int) posY, (int) linePosX + x + nodeTextBoundsWidth, 3 + (int) posY); break; } } } } } if (sNodeText.length() > 0) { TreePanel.drawString(sNodeText, posX, posY, g); } // GUILHEM_END _____________ // COMMENTED_OUT_BY_GUILHEM_BEG _______________ // TODO FIXME need to check this one! //if ( _sb.length() > 0 ) { // TreePanel.drawString( _sb.toString(), node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE, node.getYcoord() // + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ), g ); //} // COMMENTED_OUT_BY_GUILHEM_END ________________ if (getControlPanel().isShowAnnotation() && node.getNodeData().isHasSequence() && (node.getNodeData().getSequence().getAnnotations() != null) && (!node.getNodeData().getSequence().getAnnotations().isEmpty())) { if (_sb.length() > 0) { x += getTreeFontSet()._fm_large.stringWidth(_sb.toString()) + 5; } final Annotation ann = (Annotation) node.getNodeData().getSequence().getAnnotations().get(0); if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) { g.setColor(Color.BLACK); } else { g.setColor(calculateColorForAnnotation(ann)); } final String ann_str = ann.asSimpleText().toString(); TreePanel.drawString(ann_str, node.getXcoord() + x + 3 + TreePanel.HALF_BOX_SIZE, node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g); _sb.setLength(0); _sb.append(ann_str); } if ((getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR) || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE) || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED)) { if ((getControlPanel().isShowBinaryCharacters() || getControlPanel().isShowBinaryCharacterCounts()) && node.getNodeData().isHasBinaryCharacters()) { if (_sb.length() > 0) { x += getTreeFontSet()._fm_large.stringWidth(_sb.toString()) + 5; } if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) { g.setColor(Color.BLACK); } else { g.setColor(getTreeColorSet().getBinaryDomainCombinationsColor()); } if (getControlPanel().isShowBinaryCharacters()) { TreePanel.drawString( node.getNodeData().getBinaryCharacters().getPresentCharactersAsStringBuffer() .toString(), node.getXcoord() + x + 1 + TreePanel.HALF_BOX_SIZE, node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g); paintGainedAndLostCharacters(g, node, node.getNodeData().getBinaryCharacters().getGainedCharactersAsStringBuffer().toString(), node.getNodeData().getBinaryCharacters().getLostCharactersAsStringBuffer().toString()); } else { if (DRAW_MEAN_COUNTS && node.isInternal()) { final List<PhylogenyNode> ec = node.getAllExternalDescendants(); double sum = 0; int count = 0; for (final PhylogenyNode phylogenyNode : ec) { count++; if (phylogenyNode.getNodeData().getBinaryCharacters() != null) { sum += phylogenyNode.getNodeData().getBinaryCharacters().getPresentCount(); } } final double mean = ForesterUtil.round(sum / count, 1); TreePanel.drawString( node.getNodeData().getBinaryCharacters().getPresentCount() + " [" + mean + "]", node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE, node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g); } else { TreePanel.drawString(node.getNodeData().getBinaryCharacters().getPresentCount(), node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE, node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g); } paintGainedAndLostCharacters(g, node, "+" + node.getNodeData().getBinaryCharacters().getGainedCount(), "-" + node.getNodeData().getBinaryCharacters().getLostCount()); } } } }