Java Code Examples for java.awt.Graphics2D.drawString()

The following are Jave code examples for showing how to use drawString() of the java.awt.Graphics2D class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: jdk8u-jdk   File: HelvLtOblTest.java   View Source Code Vote up 6 votes
public void paintComponent(Graphics g) {
     super.paintComponent(g);
     Graphics2D g2 = (Graphics2D)g;
     FontRenderContext frc = new FontRenderContext(null, true, true);
     Font f = helvFont.deriveFont(Font.PLAIN, 40);
     System.out.println("font = " +f.getFontName());
     GlyphVector gv = f.createGlyphVector(frc, codes);
     g.setFont(f);
     g.setColor(Color.white);
     g.fillRect(0,0,400,400);
     g.setColor(Color.black);
     g2.drawGlyphVector(gv, 5,200);
     g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                         RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
     g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                         RenderingHints.VALUE_FRACTIONALMETRICS_ON);
     g2.drawString(str, 5, 250);
}
 
Example 2
Project: jmt   File: DispersionkMeanPanel.java   View Source Code Vote up 6 votes
@Override
public void paint(Graphics g1) {
	if (redraw) {
		redraw = false;
		Graphics2D g = (Graphics2D) legenda.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 110, (SQUARE_L + LINE_H) * (clusters + 1));
		for (int i = 1; i <= clusters + 1; i++) {
			g.setColor(JavaWatColor.getColor((i - 1)));
			g.fillRect(START_SQUARE_W, (START_SQUARE_H + (SQUARE_L + LINE_H) * (i - 1)), SQUARE_L, SQUARE_L);
			g.setColor(Color.BLACK);
			g.drawString("Cluster " + i, START_SQUARE_W + SQUARE_L + SQUARE_L, (START_SQUARE_H + (SQUARE_L + LINE_H) * (i - 1) + LINE_H));
		}
	}
	g1.drawImage(legenda, 0, 0, null);
}
 
Example 3
Project: scorekeeperfrontend   File: DriverTable.java   View Source Code Vote up 6 votes
@Override
public void paint(Graphics g1)
{
	Graphics2D g = (Graphics2D)g1;

	Dimension size = getSize();
	g.setColor(getBackground());
	g.fillRect(0, 0, size.width, size.height);
	g.setColor(new Color(40,40,40));

	//FontMetrics tm = g.getFontMetrics(topFont);
	FontMetrics bm = g.getFontMetrics(bottomFont);

	if (topLine != null)
	{
		g.setFont(topFont);
		g.drawString(topLine, 5, size.height/2 - 2);
	}
	if (bottomLine != null)
	{
		g.setFont(bottomFont);
		g.drawString(bottomLine, 5, size.height/2 + bm.getHeight() - 2);
	}
}
 
Example 4
Project: hackrf-spectrum-analyzer   File: WaterfallPlot.java   View Source Code Vote up 6 votes
@Override protected void paintComponent(Graphics arg0)
{
	Graphics2D g = (Graphics2D) arg0;
	g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	int w = chartWidth;
	int h = getHeight();
	g.setColor(Color.black);
	g.fillRect(0, 0, getWidth(), getHeight());

	g.drawImage(bufferedImages[drawIndex], chartXOffset, 0, w, h, null);
	
	if (displayMarker){
		g.setColor(Color.gray);
		g.drawLine(displayMarkerX, 0, displayMarkerX, h);
		g.drawString(String.format("%.1fMHz", displayMarkerFrequency/1000000.0), displayMarkerX+5, h/2);
	}//finish marker 
	
	g.setColor(Color.white);
	int x	= chartXOffset + w - 250;
	int y	= h - 20;
	g.drawString(renderingInfo, x, y-20);
	g.drawString(statusMessage, x, y);
}
 
Example 5
Project: openjdk-jdk10   File: WindowResizingOnSetLocationTest.java   View Source Code Vote up 6 votes
@Override
public Image getResolutionVariant(double destImageWidth, double destImageHeight) {

    int w = (int) destImageWidth;
    int h = (int) destImageHeight;

    BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    g.scale(scaleX, scaleY);
    int red = (int) (255 / scaleX);
    int green = (int) (250 / scaleX);
    int blue = (int) (20 / scaleX);
    g.setColor(new Color(red, green, blue));
    g.fillRect(0, 0, width, height);

    g.setColor(Color.decode("#87CEFA"));
    Font f = g.getFont();
    g.setFont(new Font(f.getName(), Font.BOLD, 24));
    g.drawString(String.format("scales: [%1.2fx, %1.2fx]", scaleX, scaleY),
            width / 6, height / 2);

    g.dispose();
    return img;
}
 
Example 6
Project: spacesettlers   File: BeaconGraphics.java   View Source Code Vote up 6 votes
public void draw(Graphics2D g) {
      float radius = Beacon.BEACON_RADIUS;
      float diameter = Beacon.BEACON_RADIUS * 2;
      
      Ellipse2D.Double shape = new Ellipse2D.Double(drawLocation.getX() - radius,
      		drawLocation.getY() - radius, diameter, diameter);

      g.setColor(BEACON_COLOR);
      g.fill(shape);

      g.setStroke(JSpaceSettlersComponent.THICK_STROKE);
      g.setColor(BEACON_LINE_COLOR);
      g.draw(shape);

      // add an E to make it clear it is an energy beacon
g.setPaint(Color.BLACK);
g.drawString("E", (int) drawLocation.getX()-3, (int) drawLocation.getY() + 4);

  }
 
Example 7
Project: BatBat-Game   File: PauseState.java   View Source Code Vote up 5 votes
public void draw(Graphics2D g) {
	g.setColor(Color.BLACK); 
	g.fillRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT);
	g.setColor(Color.WHITE); 
	g.setFont(font);
	g.drawString("Game Paused", 110, 110);
}
 
Example 8
Project: rapidminer   File: DensityPlotter.java   View Source Code Vote up 5 votes
private void drawToolTip(Graphics2D g) {
	if (currentToolTip != null) {
		g.setFont(LABEL_FONT);
		Rectangle2D stringBounds = LABEL_FONT.getStringBounds(currentToolTip, g.getFontRenderContext());
		g.setColor(TOOLTIP_COLOR);
		Rectangle2D bg = new Rectangle2D.Double((toolTipX) - stringBounds.getWidth() - 15,
				(toolTipY - (stringBounds.getHeight() / 2)), stringBounds.getWidth() + 6, Math.abs(stringBounds
						.getHeight()) + 4);
		g.fill(bg);
		g.setColor(Color.black);
		g.draw(bg);
		g.drawString(currentToolTip, (float) ((toolTipX) - stringBounds.getWidth() - 12),
				(float) ((toolTipY + stringBounds.getHeight() * 0.5) + 1));
	}
}
 
Example 9
Project: openjdk-jdk10   File: IncorrectTextSize.java   View Source Code Vote up 5 votes
public static void main(final String[] args) throws IOException {
    for (int  point = 5; point < 11; ++point) {
        Graphics2D g2d = bi.createGraphics();
        g2d.setFont(new Font(Font.DIALOG, Font.PLAIN, point));
        g2d.scale(scale, scale);
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.green);
        g2d.drawString(TEXT, 0, 20);
        int length = g2d.getFontMetrics().stringWidth(TEXT);
        if (length < 0) {
            throw new RuntimeException("Negative length");
        }
        for (int i = (length + 1) * scale; i < width; ++i) {
            for (int j = 0; j < height; ++j) {
                if (bi.getRGB(i, j) != Color.white.getRGB()) {
                    g2d.drawLine(length, 0, length, height);
                    ImageIO.write(bi, "png", new File("image.png"));
                    System.out.println("length = " + length);
                    System.err.println("Wrong color at x=" + i + ",y=" + j);
                    System.err.println("Color is:" + new Color(bi.getRGB(i,
                                                                         j)));
                    throw new RuntimeException("Test failed.");
                }
            }
        }
        g2d.dispose();
    }
}
 
Example 10
Project: VISNode   File: VectorIcon.java   View Source Code Vote up 5 votes
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2d = (Graphics2D) g.create();        
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setFont(font.deriveFont((float)size));
    g2d.setColor(color);
    g2d.drawString(text, x, y + getIconHeight());
    g2d.dispose();
}
 
Example 11
Project: geomapapp   File: GeneralUtils.java   View Source Code Vote up 5 votes
/**
 * Place a string in the lower left of a bounding rectangle (eg a plot)
 * @param g
 * @param text
 * @param rect
 * @param font
 * @param xScale
 * @param yScale
 */
public static void drawLowerLeftString(Graphics g, String text, Rectangle2D rect, Font font, double xScale, double yScale, boolean whiteBox) {
	// Get the original font
	Font oldFont = g.getFont();
    // Get the FontMetrics
    FontMetrics metrics = g.getFontMetrics(font);
    // Determine the X coordinate for the text
    int x = 10;
    // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
    int y = (int) ((rect.getHeight() * yScale - metrics.getHeight()) ) + metrics.getAscent() - 5;
    // Set the font
    Graphics2D g2 = (Graphics2D) g;
    g2.setFont(font);
    
    if (whiteBox) {
    	//draw a white box behind the text
	    int textWidth = (int) font.getStringBounds(text, g2.getFontRenderContext()).getWidth() + 2;
	    int textHeight = metrics.getHeight() + 2;
	    Color oldColor = g2.getColor();
	    g2.setColor(Color.white);
	    g2.fillRect(x-1, y-textHeight+4, textWidth, textHeight);
	    g2.setColor(oldColor);
    }
    // Draw the String
    g2.drawString(text, x , y);
    // Reset font
    g2.setFont(oldFont);
}
 
Example 12
Project: openjdk-jdk10   File: RobotMultiDPIScreenTest.java   View Source Code Vote up 5 votes
static BufferedImage getScreenImages() {

        final BufferedImage img = new BufferedImage(maxBounds.width, maxBounds.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = img.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, maxBounds.width, maxBounds.height);
        g.translate(-maxBounds.x, -maxBounds.y);

        g.setStroke(new BasicStroke(8f));
        for (int i = 0; i < screenBounds.length; i++) {
            Rectangle r = screenBounds[i];
            g.setColor(Color.BLACK);
            g.drawRect(r.x, r.y, r.width, r.height);

            g.setColor(Color.ORANGE);
            Rectangle cr = getCenterRect(r);
            g.fillRect(cr.x, cr.y, cr.width, cr.height);

            double scaleX = scales[i][0];
            double scaleY = scales[i][1];
            float fontSize = maxBounds.height / 7;
            g.setFont(g.getFont().deriveFont(fontSize));
            g.setColor(Color.BLUE);
            g.drawString(String.format("Scale: [%2.1f, %2.1f]", scaleX, scaleY),
                    r.x + r.width / 8, r.y + r.height / 2);

        }

        g.dispose();

        return img;
    }
 
Example 13
Project: rapidminer   File: BoundDiagram.java   View Source Code Vote up 5 votes
private void drawToolTip(Graphics2D g) {
	if (currentToolTip != null) {
		g.setFont(LABEL_FONT);
		Rectangle2D stringBounds = LABEL_FONT.getStringBounds(currentToolTip, g.getFontRenderContext());
		g.setColor(TOOLTIP_COLOR);
		Rectangle2D bg = new Rectangle2D.Double(toolTipX - stringBounds.getWidth() / 2 - 4, toolTipY
				- stringBounds.getHeight() / 2 - 2, stringBounds.getWidth() + 5, Math.abs(stringBounds.getHeight()) + 3);
		g.fill(bg);
		g.setColor(Color.black);
		g.draw(bg);
		g.drawString(currentToolTip, (float) (toolTipX - stringBounds.getWidth() / 2) - 2, (float) (toolTipY + 3));
	}
}
 
Example 14
Project: brModelo   File: baseDrawer.java   View Source Code Vote up 4 votes
public void bordaLeftRigth(Graphics2D g, boolean isrigth) {
        FontMetrics fm = g.getFontMetrics();
        String vl = FormateUnidadeMedida(H);
        int pre_x = (isrigth ? getLeftWidth() : getLeft());
        int traco = largTraco < margem ? largTraco : margem;
        traco = (isrigth ? -traco : traco);
        int xIni = pre_x + (isrigth ? -2 : 2);
        int xFim = xIni + 2 * traco;
        int yIni = getTop() + margem;
        int yFim = getTopHeight() - margem;
        int xLin = xIni;
//        int pre_x = (isrigth ? getLeftWidth() - margem : getLeft());
//        int traco = largTraco < margem ? largTraco : margem;
//        int xIni = pre_x + (margem - traco) / 2;
//        int xFim = xIni + traco;
//        int yIni = getTop() + margem;
//        int yFim = getTopHeight() - margem;
//        int xLin = pre_x + margem / 2;

        g.setColor(getCorRegua());
        g.drawLine(xIni, yIni, xFim, yIni);
        g.drawLine(xIni, yFim, xFim, yFim);
        g.drawLine(xLin, yIni, xLin, yFim);

        int blc = calculeSubEspaco(W);
        int sr = yIni;
        xFim -= traco;

        int dv = modInteiro(blc);
        int subblc = 0;
        if (dv > 0) {
            subblc = blc / dv;
        }
        while (sr < yFim) {
            if (dv > 0) {
                int a = blc - subblc;
                while (a > 0) {
                    if (sr + a < yFim) {
                        g.drawLine(xIni, sr + a, xFim - traco / 2, sr + a);
                    }
                    a -= subblc;
                }
            }
            g.drawLine(xIni, sr, xFim, sr);
            sr += blc;
        }

        if (isMostrarTextoRegua()) {
            int degrees = isrigth ? 90 : -90;
            int desse = isrigth ? 0 : fm.stringWidth(vl);
            int centra = fm.getHeight() / 2 - fm.getDescent();
            centra = isrigth ? -centra : centra;

            AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(degrees));
            Font f = new Font(getFont().getName(), Font.BOLD, getFont().getSize());
            g.setFont(f.deriveFont(at));
            g.setColor(getForeColor());
            xLin = pre_x - (isrigth ? margem / 2 : -margem / 2);
            yIni = yIni + (H - fm.stringWidth(vl)) / 2 + desse;
            g.drawString(vl, xLin + centra, yIni);
            g.setFont(getFont());
        }
    }
 
Example 15
Project: openjdk-jdk10   File: ImageWriterCompressionTest.java   View Source Code Vote up 4 votes
public static void main(String[] args) {
    Locale.setDefault(Locale.US);

    final BufferedImage image
        = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);

    final Graphics2D g2d = image.createGraphics();
    try {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
                             RenderingHints.VALUE_RENDER_QUALITY);
        g2d.scale(2.0, 2.0);

        g2d.setColor(Color.red);
        g2d.draw(new Rectangle2D.Float(10, 10, 100, 100));
        g2d.setColor(Color.blue);
        g2d.fill(new Rectangle2D.Float(12, 12, 98, 98));
        g2d.setColor(Color.green);
        g2d.setFont(new Font(Font.SERIF, Font.BOLD, 14));

        for (int i = 0; i < 15; i++) {
            g2d.drawString("Testing Compression ...", 20, 20 + i * 16);
        }

        final String[] fileSuffixes = ImageIO.getWriterFileSuffixes();

        final Set<String> testedWriterClasses = new HashSet<String>();

        for (String suffix : fileSuffixes) {

            if (!IGNORE_FILE_SUFFIXES.contains(suffix)) {
                final Iterator<ImageWriter> itWriters
                    = ImageIO.getImageWritersBySuffix(suffix);

                final ImageWriter writer;
                final ImageWriteParam writerParams;

                if (itWriters.hasNext()) {
                    writer = itWriters.next();

                    if (testedWriterClasses.add(writer.getClass().getName())) {
                        writerParams = writer.getDefaultWriteParam();

                        if (writerParams.canWriteCompressed()) {
                            testCompression(image, writer, writerParams, suffix);
                        }
                    }
                } else {
                    throw new RuntimeException("Unable to get writer !");
                }
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException("IO failure", ioe);
    }
    finally {
        g2d.dispose();
    }
}
 
Example 16
Project: NoMoreOversleeps   File: WebcamCapture.java   View Source Code Vote up 4 votes
@Override
public BufferedImage transform(BufferedImage image)
{
	image = GRAY.filter(image, null);
	Graphics2D graphics = image.createGraphics();
	Font font = new Font("ARIAL", Font.PLAIN, 11);
	if (privacyMode)
	{
		graphics.setColor(Color.DARK_GRAY);
		graphics.fillRect(0, 0, 320, 240);
	}
	graphics.setFont(font);
	graphics.setColor(Color.BLACK);
	graphics.fillRect(0, 0, 320, 20);
	graphics.setColor(Color.WHITE);
	long now = System.currentTimeMillis();
	String str = CommonUtils.convertTimestamp(now);
	if (NMOStatistics.INSTANCE.scheduleStartedOn != 0)
	{
		str = str + "   " + FormattingHelper.formatTimeElapsedWithDays(NMOStatistics.INSTANCE.scheduleStartedOn == 0 ? 0 : now, NMOStatistics.INSTANCE.scheduleStartedOn) + "   " + FormattingHelper.formatTimeElapsedWithDays(NMOStatistics.INSTANCE.scheduleStartedOn == 0 ? 0 : now, NMOStatistics.INSTANCE.scheduleLastOversleep);
	}
	graphics.drawString(str, 4, 14);
	if (MainDialog.isCurrentlyPaused.get() && !((MainDialog.scheduleStatusShort.startsWith("CORE ") || MainDialog.scheduleStatusShort.startsWith("NAP ") || MainDialog.scheduleStatusShort.startsWith("SIESTA ")) && MainDialog.pauseReason.startsWith("Sleep block: ")))
	{
		graphics.setColor(Color.BLACK);
		graphics.fillRect(0, 204, 320, 36);
		graphics.setColor(Color.WHITE);
		graphics.drawString("PAUSED for \"" + MainDialog.pauseReason + "\"\n", 4, 218);
		graphics.drawString("until " + CommonUtils.dateFormatter.format(MainDialog.pausedUntil), 4, 234);
	}
	else
	{
		graphics.setColor(Color.BLACK);
		graphics.fillRect(0, 220, 320, 20);
		graphics.setColor(Color.WHITE);
		graphics.drawString(MainDialog.scheduleStatus, 4, 234);
	}
	image.flush();
	graphics.dispose();
	return image;
}
 
Example 17
Project: rapidminer   File: SystemMonitor.java   View Source Code Vote up 4 votes
@Override
public void paintComponent(Graphics g) {
	super.paintComponent(g);

	GeneralPath path = new GeneralPath();

	Dimension d = getSize();
	int monitorWidth = (int) d.getWidth() - 2 * MARGIN;
	int monitorHeight = (int) d.getHeight() - 2 * MARGIN;

	long total = Runtime.getRuntime().totalMemory();

	Graphics2D g2d = (Graphics2D) g;
	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

	if (this.font == null) {
		this.font = g2d.getFont().deriveFont(12f);
	}

	g2d.setColor(Colors.WHITE);
	g2d.fillRect(MARGIN, MARGIN, monitorWidth, monitorHeight);

	path.moveTo(MARGIN, MARGIN + monitorHeight);
	for (int i = 0; i < memory.length; i++) {
		int index = (currentMeasurement + i) % memory.length;
		path.lineTo(MARGIN + i * monitorWidth / (memory.length - 1),
				MARGIN + monitorHeight - monitorHeight * memory[index] / total);
	}
	path.lineTo(MARGIN + monitorWidth, MARGIN + monitorHeight);
	path.closePath();

	g2d.setColor(gridColor);
	for (int x = 0; x < GRID_X + 1; x++) {
		g2d.drawLine(MARGIN + x * monitorWidth / GRID_X, MARGIN, MARGIN + x * monitorWidth / GRID_X,
				MARGIN + monitorHeight);
	}
	for (int y = 0; y < GRID_Y + 1; y++) {
		g2d.drawLine(MARGIN, MARGIN + y * monitorHeight / GRID_Y, MARGIN + monitorWidth,
				MARGIN + y * monitorHeight / GRID_Y);
	}

	Color currentMemoryColor = memoryColor;
	if (currentlyUsed > 0.2d * Runtime.getRuntime().maxMemory()) {
		double more = currentlyUsed - 0.2d * Runtime.getRuntime().maxMemory();
		double factor = more / (0.6d * Runtime.getRuntime().maxMemory());
		currentMemoryColor = getMemoryColor(Math.max(Math.min(1.0d, factor), 0.0d));
	}
	g2d.setColor(currentMemoryColor);
	g2d.fill(path);
	g2d.setColor(lineColor);
	g2d.draw(path);

	// text
	String maxString = Tools.formatSizeInBytes(total) + " used. Will use up to "
			+ Tools.formatSizeInBytes(Runtime.getRuntime().maxMemory());
	int totalHeight = 2 * font.getSize() + 2 * MARGIN;
	// MARGIN;
	if (totalHeight < getHeight()) {
		g2d.setFont(font);
		g2d.setColor(textColor);
		g2d.drawString(maxString, 2 * MARGIN, monitorHeight - font.getSize() + MARGIN);
	}
}
 
Example 18
Project: Pogamut3   File: PoshWidget.java   View Source Code Vote up 4 votes
@Override
protected void paintWidget() {
    Graphics2D g = getGraphics();

    // draw rectanlge
    g.setColor(getType().getColor());
    g.fillRect(0, 0, width, height);


    int collapseWidth = 0;
    // draw collapse block
    if (!getChildNodes().isEmpty()) {
        collapseWidth = arrowWidth;
        g.setColor(getType().getColor().darker());

        if (isCollapsed()) {
            g.fillPolygon(
                    new int[]{width - arrowWidth, width, width - arrowWidth},
                    new int[]{0, height / 2, height},
                    3);
        } else {
            g.fillPolygon(
                    new int[]{width, width - arrowWidth, width},
                    new int[]{0, height / 2, height},
                    3);
        }
    }
    g.setColor(Color.BLACK);
    int xofs = 4;

    int maxTextWidth = width - xofs - collapseWidth;
    // draw headline text
    FontMetrics boldMetrics = g.getFontMetrics(boldFont);
    String renderedHeadlineString = getFittingString(getHeadlineText(), boldMetrics, maxTextWidth);

    g.setFont(boldFont);
    g.drawString(renderedHeadlineString, xofs, boldMetrics.getHeight());

    // draw comment string
    FontMetrics italicMetrics = g.getFontMetrics(italicFont);
    String renderCommentString = getFittingString(getCommentText(), italicMetrics, maxTextWidth);

    g.setFont(italicFont);
    g.drawString(renderCommentString, xofs, boldMetrics.getHeight() + italicMetrics.getHeight());
}
 
Example 19
Project: QN-ACTR-Release   File: QueueDrawer.java   View Source Code Vote up 4 votes
/**
 * drawing the legend
 * 
 * @param ca
 *            color of the legend
 * @param sa
 *            Comments
 * @param f
 *            font
 * @param x
 *            initial abscissa
 * @param y
 *            initial ordinate
 * @param g2d
 * @return panel lenght 
 */
private double drawLegend(Color[] ca, String[] sa, Font f, double x, double y, Graphics2D g2d, boolean draw) {
	Rectangle2D[] ra = new Rectangle2D[ca.length];
	Rectangle2D[] tba = new Rectangle2D[ca.length];
	double maxw = 0.0, gap = 5.0;
	String ts = "Legenda";
	// backup
	Color ctmp = g2d.getColor();
	Font ftmp = g2d.getFont();

	g2d.setFont(f);
	Rectangle2D tr = f.getStringBounds(ts, g2d.getFontRenderContext());
	maxw = tr.getWidth();
	for (int i = 0; i < ca.length; i++) {
		tba[i] = f.getStringBounds(sa[i], g2d.getFontRenderContext());
		ra[i] = new Rectangle2D.Double(x + gap, y + gap + (tr.getHeight() + gap) * (i + 1), tr.getHeight(), tr.getHeight());
		if (draw) {
			g2d.setColor(ca[i]);
			g2d.fill(ra[i]);
			g2d.setColor(Color.BLACK);
			g2d.draw(ra[i]);
			g2d.drawString(sa[i], (float) (x + gap * 2 + tr.getHeight()), (float) (y + gap + (tr.getHeight() + gap) * (i + 1) + tr.getHeight()
					/ 2.0 - tr.getY() / 2.0));
		}
		if (maxw < tba[i].getWidth()) {
			maxw = tba[i].getWidth();
		}
	}
	if (draw) {
		g2d.drawRect((int) x, (int) y, (int) (maxw + 3.0 * gap + tr.getHeight()), (int) (y + (tr.getHeight() + gap) * (ca.length + 1) + gap));
		g2d.drawRect((int) x, (int) y, (int) (maxw + 3.0 * gap + tr.getHeight()), (int) (tr.getHeight() + gap));
		g2d.fillRect((int) x, (int) y, (int) (maxw + 3.0 * gap + tr.getHeight()), (int) (tr.getHeight() + gap));
		g2d.setColor(Color.WHITE);
		g2d.drawString(ts, (float) (x + gap + (maxw - tr.getWidth() + tr.getHeight()) / 2.0), (float) (y + tr.getY() / 2.0 + tr.getHeight()));
	}

	// restore
	g2d.setFont(ftmp);
	g2d.setColor(ctmp);
	return (maxw + 3.0 * gap + tr.getHeight());

}
 
Example 20
Project: rapidminer   File: ImprovedNeuralNetVisualizer.java   View Source Code Vote up 4 votes
private void paintNodes(Graphics2D g, int height) {
	for (Map.Entry<Integer, List<Node>> entry : layers.entrySet()) {
		int layerIndex = entry.getKey();
		List<Node> layer = entry.getValue();
		int nodes = layer.size();
		if (layerIndex < layers.size() - 1) {
			nodes++;
		}

		String layerName = null;
		if (layerIndex == 0) {
			layerName = "Input";
		} else if (layerIndex == layers.size() - 1) {
			layerName = "Output";
		} else {
			layerName = "Hidden " + layerIndex;
		}

		Rectangle2D stringBounds = LABEL_FONT.getStringBounds(layerName, g.getFontRenderContext());
		g.setColor(Color.BLACK);
		g.drawString(layerName, (int) (((-1) * stringBounds.getWidth() / 2) + NODE_RADIUS / 2), 0);
		int yPos = (height / 2) - (nodes * ROW_HEIGHT / 2);
		for (int r = 0; r < nodes; r++) {
			Shape node = new Ellipse2D.Double(0, yPos, NODE_RADIUS, NODE_RADIUS);
			if ((layerIndex == 0) || (layerIndex == layers.size() - 1)) {
				if ((r < nodes - 1) || (layerIndex == layers.size() - 1)) {
					g.setPaint(SwingTools.makeYellowPaint(NODE_RADIUS, NODE_RADIUS));
				} else {
					g.setPaint(new Color(233, 233, 233));
				}
			} else {
				if (r < nodes - 1) {
					g.setPaint(SwingTools.makeBluePaint(NODE_RADIUS, NODE_RADIUS));
				} else {
					g.setPaint(new Color(233, 233, 233));
				}
			}
			g.fill(node);
			if ((layerIndex == this.selectedLayerIndex) && (r == this.selectedRowIndex)) {
				g.setColor(Color.RED);
			} else {
				g.setColor(Color.BLACK);
			}
			g.draw(node);
			yPos += ROW_HEIGHT;
		}
		g.translate(LAYER_WIDTH, 0);
		layerIndex++;
	}
}