Java Code Examples for java.awt.Graphics#drawString()

The following examples show how to use java.awt.Graphics#drawString() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
public void draw(int px, int py, int width, int height, Graphics g){
	// Fill white rect
	g.setColor(Color.white);
	g.fillRect(px,py,width, height);
	// write the description
	g.setColor(Color.black);
	g.drawString(description, (int)(width*0.05), py+12);
	
	// draw Histo
	drawHisto(px+(int)(width*0.05), py+(int)(height*0.1), (int)(width*0.95), (int)(height*0.8), g);

	//drawLines
	g.setColor(Color.black);
	g.drawLine(px+(int)(width*0.05), py+(int)(height*0.1), px+(int)(width*0.05),(int)(height*0.9));
	g.drawLine(px+(int)(width*0.05), (int)(height*0.9), width,(int)(height*0.9));
}
 
Example 2
private static void showFrame(final TransformedPaintTest t) {
    JFrame f = new JFrame("TransformedPaintTest");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final BufferedImage bi =
        new BufferedImage(R_WIDTH, R_HEIGHT, BufferedImage.TYPE_INT_RGB);
    JPanel p = new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            t.render(g2d, R_WIDTH, R_HEIGHT);
            t.render(bi.createGraphics(), R_WIDTH, R_HEIGHT);
            g2d.drawImage(bi, R_WIDTH + 5, 0, null);

            g.setColor(Color.black);
            g.drawString("Rendered to Back Buffer", 10, 20);
            g.drawString("Rendered to BufferedImage", R_WIDTH + 15, 20);
        }
    };
    p.setPreferredSize(new Dimension(2 * R_WIDTH + 5, R_HEIGHT));
    f.add(p);
    f.pack();
    f.setVisible(true);
}
 
Example 3
@Override
public void paint(Graphics g) {

    super.paint(g);
    Rectangle bounds = getBounds();
    if (superIsButton) {
        return;
    }
    Dimension size = getSize();
    Color oldColor = g.getColor();

    // draw border
    g.setColor(getBackground());
    g.fill3DRect(0, 0, size.width, size.height, false);
    g.fill3DRect(3, 3, size.width - 6, size.height - 6, true);

    // draw text
    FontMetrics metrics = g.getFontMetrics();
    int centerX = size.width / 2;
    int centerY = size.height / 2;
    int textX = centerX - (metrics.stringWidth(labelString) / 2);
    int textY = centerY
            + ((metrics.getMaxAscent() + metrics.getMaxDescent()) / 2);
    g.setColor(getForeground());
    g.drawString(labelString, textX, textY);

    g.setColor(oldColor);
}
 
Example 4
NonOpaqueJFrame() {
    super("NonOpaque Swing JFrame");
    JPanel p = new JPanel() {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            render(g, getWidth(), getHeight(), true);
            g.setColor(Color.red);
            g.drawString("Non-Opaque Swing JFrame", 10, 15);
        }
    };
    p.setDoubleBuffered(false);
    p.setOpaque(false);
    add(p);
    setUndecorated(true);
}
 
Example 5
public void render() {
    ImageCapabilities imgBackBufCap = new ImageCapabilities(true);
    ImageCapabilities imgFrontBufCap = new ImageCapabilities(true);
    BufferCapabilities bufCap =
        new BufferCapabilities(imgFrontBufCap,
            imgBackBufCap, BufferCapabilities.FlipContents.COPIED);
    try {

        createBufferStrategy(2, bufCap);
    } catch (AWTException ex) {
        createBufferStrategy(2);
    }

    BufferStrategy bs = getBufferStrategy();
    do {
        Graphics g =  bs.getDrawGraphics();
        g.setColor(Color.green);
        g.fillRect(0, 0, getWidth(), getHeight());

        g.setColor(Color.red);
        g.drawString("Rendering test", 20, 20);

        g.drawImage(bi, 50, 50, null);

        g.dispose();
        bs.show();
    } while (bs.contentsLost()||bs.contentsRestored());
}
 
Example 6
@Override
public void paint(Graphics g) {
    int w = getSize().width;
    int h = getSize().height;
    if (img == null) {
        super.paint(g);
        g.setColor(Color.black);
        FontMetrics fm = g.getFontMetrics();
        int x = (w - fm.stringWidth(calcString)) / 2;
        int y = h / 2;
        g.drawString(calcString, x, y);
    } else {
        g.drawImage(img, 0, 0, w, h, this);
    }
}
 
Example 7
Source Project: ET_Redux   File: TextCellRenderer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param g
 */
@Override
public void paint(Graphics g) {
    if (mePaint){
        g.setColor(Color.WHITE);
    }
    
    super.paint(g);
    
    g.setColor(Color.black);
    g.setFont(new Font("Monospaced", Font.BOLD, 12));
    g.drawString(this.getText(),
            (int)g.getClipBounds().getWidth() - 55, 20); // hard-coded for now
}
 
Example 8
private void drawString(Graphics g, String s, Color background, Color foreground, int x, int y) {
	g.setFont(new Font("default", Font.BOLD, 12));
	g.setColor(background);
	FontMetrics fm = g.getFontMetrics();
	Rectangle2D rect = fm.getStringBounds(s, g);
	g.fillRect(x, y - fm.getAscent(), (int) rect.getWidth(), (int) rect.getHeight());
	g.setColor(foreground);
	g.drawString(s, x, y);
}
 
Example 9
private static BufferedImage drawString(String text) {
    BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.createGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
    g.setColor(Color.black);
    g.setFont(FONT);
    g.drawString(text, TEXT_X, TEXT_Y);
    g.dispose();
    return image;
}
 
Example 10
Source Project: nanoleaf-desktop   File: ModernSliderUI.java    License: MIT License 5 votes vote down vote up
@Override
protected void paintHorizontalLabel(Graphics g, int value, Component label)
{
	int labelCenter = xPositionForValue(value);
       int labelLeft = labelCenter - (label.getPreferredSize().width / 2);
       g.translate(labelLeft, 0);
       g.setColor(Color.GRAY);
       g.drawString(((JLabel)label).getText(), 0, 5);
       g.translate(-labelLeft, 0);
}
 
Example 11
Source Project: netbeans   File: DrawGraphics.java    License: Apache License 2.0 5 votes vote down vote up
private static void drawStringTextLayout(JComponent c, Graphics g, String text, int x, int baselineY) {
    if (!(g instanceof Graphics2D)) {
        g.drawString(text, x, baselineY);
    } else { // Graphics2D available
        Graphics2D g2d = (Graphics2D)g;
        FontRenderContext frc = g2d.getFontRenderContext();
        TextLayout layout = new TextLayout(text, g2d.getFont(), frc);
        layout.draw(g2d, x, baselineY);
    }
}
 
Example 12
public int print(Graphics g, PageFormat pf, int pi)
        throws PrinterException {
    System.out.println("pi = " + pi);
    if (pi >= 5) {
        return NO_SUCH_PAGE;
    }
    g.drawString("Page : " + (pi+1), 200, 200);
    return PAGE_EXISTS;
}
 
Example 13
@Override
protected void paintComponent(Graphics g) {
	setOurWidth();
	int x = getWidth();
	int y = getHeight();

	Graphics2D g2d = (Graphics2D) g;
	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	g2d.setColor(OSVColors.GREY_3);
	int offX = x / 5;
	int offY = y / 3;
	int width = x * 3 / 5;
	int height = y * 2 / 5;
	g2d.fillRect(offX, offY, width, height);

	if (soc > 0f) {
		g2d.setColor(OSVColors.BLUE_1);
		int maxHeight = 5 * height / 8 - width / 10;
		g2d.fillRect(offX + width / 4 + width / 20, (int) (offY + height / 8 + width / 20 + (1 - soc) * maxHeight),
				width / 2 - width / 10, (int) (5 * height / 8 - width / 10 - (1 - soc) * maxHeight));
	}

	g2d.setStroke(new BasicStroke(6));
	g2d.setColor(OSVColors.WHITE);
	g2d.drawRect(offX + width / 4, offY + height / 8, width / 2, 5 * height / 8);
	g2d.drawRect(offX + width / 4 + width / 8, offY + height / 8 - height / 20, width / 4, height / 20);

	if (isCharging) {
		// TODO Draw lightning
		int ySize = height / 2;
		int xSize = mw.chargeLightning.getWidth() * ySize / mw.chargeLightning.getHeight();
		BufferedImage lightningImg;
		switch (lightningCounter++) {
		case 0:
			lightningImg = mw.chargeLightning0;
			break;
		case 1:
			lightningImg = mw.chargeLightning1;
			break;
		case 2:
			lightningImg = mw.chargeLightning2;
			break;
		case 3:
			lightningImg = mw.chargeLightning3;
			break;
		case 4:
			lightningImg = mw.chargeLightning4;
			break;
		case 5:
			lightningImg = mw.chargeLightning5;
			break;
		case 6:
			lightningImg = mw.chargeLightning6;
			break;
		case 7:
			lightningImg = mw.chargeLightning7;
			break;
		case 8:
			lightningImg = mw.chargeLightning8;
			break;
		case 9:
			lightningImg = mw.chargeLightning9;
			break;
		default:
			lightningImg = mw.chargeLightning;
		}
		if(lightningCounter == 48) {
			lightningCounter = -1;
		}

		ImageIcon sizedLightning = new ImageIcon(lightningImg.getScaledInstance(xSize, ySize, Image.SCALE_SMOOTH));
		int x1 = offX + width / 2 - sizedLightning.getIconWidth() / 2;
		int y1 = offY + 7 * height / 16 - sizedLightning.getIconHeight() / 2;
		g.drawImage(sizedLightning.getImage(), x1, y1, sizedLightning.getIconWidth(),
				sizedLightning.getIconHeight(), null);
	}

	setForeground(OSVColors.WHITE);
	float yF = height / 12;
	g.setFont(font.deriveFont(yF));

	FontMetrics fm = getFontMetrics(g.getFont());
	int xF = fm.stringWidth(socS.getText());
	int xFPos = offX + width / 2 - xF / 2;
	// int xFPos = x1 / 2 + this.getWidth() / 10 - xF / 2;
	// int yFPos = (int) (this.getHeight() / 3 + y1 / 2 + yF / 4);
	int yFPos = (int) (offY + height - height / 16 - yF / 2);
	g.drawString(socS.getText(), xFPos, yFPos);
}
 
Example 14
public int print(Graphics g, PageFormat pf, int pg) {
    if (pg > 0) return NO_SUCH_PAGE;
    g.drawString("\u00e4", 100, 100);
    return PAGE_EXISTS;
}
 
Example 15
@Override
protected void paintComponent(final Graphics g) {
  this.setCaretPosition(this.getDocument().getLength());
  g.setColor(Color.black);
  Insets inset = this.getBorder().getBorderInsets(this);
  int sx = inset.left;
  int sy = inset.top;
  int width = getWidth() - inset.left - inset.right;
  int height = getHeight() - inset.top - inset.bottom;
  g.fillRect(sx, sx, width, height);
  g.setFont(this.getFont());
  if (getText() != null) {
    StringBuilder sb = new StringBuilder();
    if (!autoScroll) {
      sb = new StringBuilder(this.getText());
    } else {
      for (int i = 0; i < numberOfLines; i++) {
        if (i + currentLine < scrollText.length) {
          sb.append(scrollText[i + currentLine]).append("\n");
        }
      }
    }
    if (this.getLineWrap()) {
      int lastSpace = -1;
      int rowLen = 0;
      int maxRowLen = width / 6;
      if (customCharWidth > 0) {
        maxRowLen = width / customCharWidth;
      }
      for (int i = 0; i < sb.length(); i++) {
        if (sb.charAt(i) == ' ') {
          lastSpace = i;
        }
        if (sb.charAt(i) == '\n') {
          lastSpace = -1;
          rowLen = 0;
        } else {
          rowLen++;
        }
        if (rowLen > maxRowLen) {
          if (lastSpace != -1) {
            sb.setCharAt(lastSpace, '\n');
            rowLen = i - lastSpace;
            lastSpace = -1;

          } else {
            sb.setCharAt(i, '\n');
            lastSpace = -1;
            rowLen = 0;
          }
        }
      }
    }
    if (this.hasFocus() && this.isEditable()) {
      if (blinking) {
        blinking = false;
      } else {
        blinking = true;
        sb.insert(this.getCaretPosition(), '|');
      }
    }
    String[] texts = sb.toString().split("\n");
    for (int i = 0; i < texts.length; i++) {
      g.setColor(GuiStatics.COLOR_GREEN_TEXT_DARK);
      int yHeight = GuiStatics.getTextHeight(getFont(), texts[i]);
      if (!smoothScroll) {
        g.drawString(texts[i], sx + 3, sy + i * yHeight + yHeight);
        if (getFont() == GuiStatics.getFontCubellanSC()) {
          g.drawString(texts[i], sx + 1, sy + i * yHeight + yHeight);
          g.drawString(texts[i], sx + 2, sy + i * yHeight - 1 + yHeight);
        }
        g.drawString(texts[i], sx + 2, sy + i * yHeight + 1 + yHeight);
        g.setColor(GuiStatics.COLOR_GREEN_TEXT);
        g.drawString(texts[i], sx + 2, sy + i * yHeight + yHeight);
      } else {
        g.drawString(texts[i], sx + 3,
            sy + i * Y_OFFSET + Y_OFFSET - smoothScrollY);
        g.drawString(texts[i], sx + 1,
            sy + i * Y_OFFSET + Y_OFFSET - smoothScrollY);
        g.drawString(texts[i], sx + 2,
            sy + i * Y_OFFSET - 1 + Y_OFFSET - smoothScrollY);
        g.drawString(texts[i], sx + 2,
            sy + i * Y_OFFSET + 1 + Y_OFFSET - smoothScrollY);
        g.setColor(this.getForeground());
        g.drawString(texts[i], sx + 2,
            sy + i * Y_OFFSET + Y_OFFSET - smoothScrollY);
      }

    }
  }
  smoothScrollY++;
  if (smoothScrollY == 18) {
    smoothScrollY = 0;
    smoothScrollNextRow = true;
  }

}
 
Example 16
public int print(Graphics g, PageFormat pf, int pg) {
    if (pg > 0) return NO_SUCH_PAGE;
    g.drawString("\u00e4", 100, 100);
    return PAGE_EXISTS;
}
 
Example 17
Source Project: dubai   File: CaptchaUtil.java    License: MIT License 4 votes vote down vote up
/**
 * 已有验证码,生成验证码图片
 *
 * @param textCode
 *            文本验证码
 * @param width
 *            图片宽度
 * @param height
 *            图片高度
 * @param interLine
 *            图片中干扰线的条数
 * @param randomLocation
 *            每个字符的高低位置是否随机
 * @param backColor
 *            图片颜色,若为null,则采用随机颜色
 * @param foreColor
 *            字体颜色,若为null,则采用随机颜色
 * @param lineColor
 *            干扰线颜色,若为null,则采用随机颜色
 * @return 图片缓存对象
 */
public static BufferedImage generateImage(String textCode, int width, int height, int interLine,
                                          boolean randomLocation, Color backColor, Color foreColor, Color lineColor) {

    BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = bim.getGraphics();

    // 画背景图
    g.setColor(backColor == null ? getRandomColor() : backColor);
    g.fillRect(0, 0, width, height);

    // 画干扰线
    Random r = new Random();
    if (interLine > 0) {

        int x = 0, y = 0, x1 = width, y1 = 0;
        for (int i = 0; i < interLine; i++) {
            g.setColor(lineColor == null ? getRandomColor() : lineColor);
            y = r.nextInt(height);
            y1 = r.nextInt(height);

            g.drawLine(x, y, x1, y1);
        }
    }

    // 写验证码

    // g.setColor(getRandomColor());
    // g.setColor(isSimpleColor?Color.BLACK:Color.WHITE);

    // 字体大小为图片高度的80%
    int fsize = (int) (height * 0.8);
    int fx = height - fsize;
    int fy = fsize;

    g.setFont(new Font("Default", Font.PLAIN, fsize));

    // 写验证码字符
    for (int i = 0; i < textCode.length(); i++) {
        fy = randomLocation ? (int) ((Math.random() * 0.3 + 0.6) * height) : fy;// 每个字符高低是否随机
        g.setColor(foreColor == null ? getRandomColor() : foreColor);
        g.drawString(textCode.charAt(i) + "", fx, fy);
        fx += fsize * 0.9;
    }

    g.dispose();

    return bim;
}
 
Example 18
Source Project: netbeans   File: TableColumnModelEditor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void paintValue(Graphics g, Rectangle rectangle) {
    String msg = NbBundle.getMessage(TableColumnModelEditor.class, "TableColumnModelEditor_TableColumnModel"); // NOI18N
    FontMetrics fm = g.getFontMetrics();
    g.drawString(msg, rectangle.x, rectangle.y + (rectangle.height - fm.getHeight())/2 + fm.getAscent());
}
 
Example 19
public int print(Graphics g, PageFormat pgFmt, int pi) {
    g.drawString("Page : " + (pi + 1), 200, 200);

    return PAGE_EXISTS;
}
 
Example 20
public Animable animatePanel(final double duration, final Corner corner) {
	return new Animable() {
		
		@Override
		public double getDuration() {
			return duration;
		}
		
		@Override
		public void draw(Graphics gr, ScaleAnimation scale, double t) {
			int width = scale.getWidth();
			int height = scale.getHeight();
			gr.setFont(gr.getFont().deriveFont(height/25f));
			gr.setColor(color);
			Map<StatType, Integer> stats = getStatsAt(t);
			boolean allZero = true;
			for (int stat : stats.values()) {
				if (stat != 0) allZero = false;
			}
			if (allZero) return;
			int number = stats.size();
			double[] textBottom = new double[number];
			double[] textLeft = new double[number];
			String[] texts = new String[number];
			int index = 0;
			for (StatType type : stats.keySet()) {
				String text = type + ": " + stats.get(type);
				Rectangle2D stringBounds = gr.getFontMetrics().getStringBounds(text, gr);
				double textWidth = stringBounds.getWidth();
				double textHeight = stringBounds.getHeight()+width/100;
				textBottom[index] = index == 0 ? textHeight : textBottom[index-1]+textHeight;
				textLeft[index] = corner.isLeftAligned() ? width/100 : width*99/100-textWidth;
				texts[index] = text;
				index++;
			}
			double panelHeight = textBottom[number-1];
			for (int i=0; i<number; i++) {
				if (corner.isTopAligned()) {
					textBottom[i] += height/100;
				} else {
					textBottom[i] += height*99/100-panelHeight;
				}
			}
			for (int i=0; i<number; i++) {
				gr.drawString(texts[i], (int)Math.round(textLeft[i]), (int)Math.round(textBottom[i]));
			}
		}
	};
}