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

The following are Jave code examples for showing how to use setBackground() 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: png_to_jpg_in_svg   File: PNG_to_JPG_in_SVG.java   View Source Code Vote up 7 votes
private String convertPngToJpeg(String pngBase64) throws IOException {
	byte[] pngBinary = DatatypeConverter.parseBase64Binary(pngBase64);
	InputStream in = new ByteArrayInputStream(pngBinary);
	BufferedImage pngImage = ImageIO.read(in);

	int width = pngImage.getWidth(), height = pngImage.getHeight();
	BufferedImage jpgImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

	Graphics2D g = jpgImage.createGraphics();
	g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
	g.setBackground(Color.WHITE);
	g.clearRect(0, 0, width, height);
	g.drawImage(pngImage, 0, 0, width, height, null);
	g.dispose();

	final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	writer.setOutput(ImageIO.createImageOutputStream(baos));
	writer.write(null, new IIOImage(jpgImage, null, null), JPEG_PARAMS);

	String jpgBase64 = DatatypeConverter.printBase64Binary(baos.toByteArray());
	return jpgBase64;
}
 
Example 2
Project: jdk8u-jdk   File: Test7019861.java   View Source Code Vote up 6 votes
public static void main(String[] argv) throws Exception {
    BufferedImage im = getWhiteImage(30, 30);
    Graphics2D g2 = (Graphics2D)im.getGraphics();
    g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(KEY_STROKE_CONTROL, VALUE_STROKE_PURE);
    g2.setStroke(new BasicStroke(10, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
    g2.setBackground(Color.white);
    g2.setColor(Color.black);

    Path2D p = getPath(0, 0, 20);
    g2.draw(p);

    if (!(new Color(im.getRGB(20, 19))).equals(Color.black)) {
        throw new Exception("This pixel should be black");
    }
}
 
Example 3
Project: openjdk-jdk10   File: CGLGraphicsConfig.java   View Source Code Vote up 6 votes
@Override
public void flip(final LWComponentPeer<?, ?> peer, final Image backBuffer,
                 final int x1, final int y1, final int x2, final int y2,
                 final BufferCapabilities.FlipContents flipAction) {
    final Graphics g = peer.getGraphics();
    try {
        g.drawImage(backBuffer, x1, y1, x2, y2, x1, y1, x2, y2, null);
    } finally {
        g.dispose();
    }
    if (flipAction == BufferCapabilities.FlipContents.BACKGROUND) {
        final Graphics2D bg = (Graphics2D) backBuffer.getGraphics();
        try {
            bg.setBackground(peer.getBackground());
            bg.clearRect(0, 0, backBuffer.getWidth(null),
                         backBuffer.getHeight(null));
        } finally {
            bg.dispose();
        }
    }
}
 
Example 4
Project: VASSAL-src   File: MapBoard.java   View Source Code Vote up 6 votes
@Override
boolean draw(Graphics2D g) {
  // set background color
  g.setBackground(tableColor);
  Dimension d = getLayout().getBoardSize();
  g.clearRect(0, 0, d.width, d.height);

  // See if map image file exists
  File sml = action.getCaseInsensitiveFile(new File(forceExtension(path, "sml")), null, false, null);
  if (sml != null) {
    try {
      readScannedMapLayoutFile(sml, g);
    }
    // FIXME: review error message
    catch (IOException e) {}
  }
  else if (getSet().underlay != null) {
    // If sml file doesn't exist, see if there is a single-sheet underlay image
  g.drawImage(getSet().underlay, null, 0, 0);
  }
  return true;
}
 
Example 5
Project: Bachelor-Thesis   File: MapGraphic.java   View Source Code Vote up 6 votes
@Override
public void draw(Graphics2D g2) {
	Coord c,c2;
	
	if (simMap == null) {
		return;
	}
	
	g2.setColor(PATH_COLOR);
	g2.setBackground(BG_COLOR);
	
	// draws all edges between map nodes (bidirectional edges twice)
	for (MapNode n : simMap.getNodes()) {
		c = n.getLocation();
		
		// draw a line to adjacent nodes
		for (MapNode n2 : n.getNeighbors()) {
			c2 = n2.getLocation();
			g2.drawLine(scale(c2.getX()), scale(c2.getY()),
					scale(c.getX()), scale(c.getY()));
		}
	}
}
 
Example 6
Project: jaer   File: ToradexOakG3AxisAccelerationSensorGUI.java   View Source Code Vote up 6 votes
@Override
public void paint(Graphics g) {
    super.paint(g);
    if (sensor == null) {
        return;
    }
    Graphics2D g2 = (Graphics2D) g;
    g2.setBackground(Color.WHITE);
    g2.clearRect(0, 0, getWidth(), getHeight());
    g2.setColor(Color.RED);
    g2.setStroke(new BasicStroke(2f));
    ToradexOakG3AxisAccelerationSensor.Acceleration v=sensor.getAcceleration();
    int w=getWidth(), h=getHeight();
    final float m = ToradexOakG3AxisAccelerationSensor.MAX_ACCEL;
    float x = w*v.x/m+w/2;
    float y = h*v.y/m+h/2;
    float z = (v.z+m/2)/m*h/10;
    final int r = (int)z;
    int xx=(int)(x-r), yy=(int)(y-r);
    g2.drawOval(xx, yy, r * 2, r * 2);
}
 
Example 7
Project: OpenJSharp   File: CGLGraphicsConfig.java   View Source Code Vote up 6 votes
@Override
public void flip(final LWComponentPeer<?, ?> peer, final Image backBuffer,
                 final int x1, final int y1, final int x2, final int y2,
                 final BufferCapabilities.FlipContents flipAction) {
    final Graphics g = peer.getGraphics();
    try {
        g.drawImage(backBuffer, x1, y1, x2, y2, x1, y1, x2, y2, null);
    } finally {
        g.dispose();
    }
    if (flipAction == BufferCapabilities.FlipContents.BACKGROUND) {
        final Graphics2D bg = (Graphics2D) backBuffer.getGraphics();
        try {
            bg.setBackground(peer.getBackground());
            bg.clearRect(0, 0, backBuffer.getWidth(null),
                         backBuffer.getHeight(null));
        } finally {
            bg.dispose();
        }
    }
}
 
Example 8
Project: JuggleMasterPro   File: AnimationJFrame.java   View Source Code Vote up 6 votes
/**
 * Method description
 * 
 * @see
 */
final public void doCreateBackgroundImages() {
	// Tools.verbose("On rentre dans doCreateBackgroundImages()");
	this.imgGbackgroundBufferA = new BufferedImage[2];
	for (int intLbackgroundIndex = Constants.bytS_ENGINE_NIGHT; intLbackgroundIndex <= Constants.bytS_ENGINE_DAY; ++intLbackgroundIndex) {
		this.imgGbackgroundBufferA[intLbackgroundIndex] =
															Constants.objS_GRAPHICS_CONFIGURATION.createCompatibleImage(Constants.intS_GRAPHICS_SCREEN_WIDTH,
																														Constants.intS_GRAPHICS_SCREEN_HEIGHT,
																														Transparency.OPAQUE);

		final Graphics2D objLbackgroundGraphics2D = (Graphics2D) this.imgGbackgroundBufferA[intLbackgroundIndex].getGraphics();

		objLbackgroundGraphics2D.setBackground(this.objGjuggleMasterPro.objGbackgroundColorA[intLbackgroundIndex]);
		objLbackgroundGraphics2D.setColor(this.objGjuggleMasterPro.objGbackgroundColorA[intLbackgroundIndex]);
		objLbackgroundGraphics2D.fillRect(0, 0, Constants.intS_GRAPHICS_SCREEN_WIDTH, Constants.intS_GRAPHICS_SCREEN_HEIGHT);
		objLbackgroundGraphics2D.dispose();
	}
}
 
Example 9
Project: the-one-mdonnyk   File: MapGraphic.java   View Source Code Vote up 6 votes
@Override
public void draw(Graphics2D g2) {
	Coord c,c2;
	
	if (simMap == null) {
		return;
	}
	
	g2.setColor(PATH_COLOR);
	g2.setBackground(BG_COLOR);
	
	// draws all edges between map nodes (bidirectional edges twice)
	for (MapNode n : simMap.getNodes()) {
		c = n.getLocation();
		
		// draw a line to adjacent nodes
		for (MapNode n2 : n.getNeighbors()) {
			c2 = n2.getLocation();
			g2.drawLine(scale(c2.getX()), scale(c2.getY()),
					scale(c.getX()), scale(c.getY()));
		}
	}
}
 
Example 10
Project: MMDownloader   File: ImageMerge.java   View Source Code Vote up 5 votes
@SuppressWarnings("unused")
public void mergeAll(String mergedName) {
	try {
		System.out.print("이미지 병합중 ... ");
		
		int i, len, preHeight, width, maxWidth = -1, totalHeight = -1;
		
		/* 폴더 내부의 모든 이미지(jpg, bmp등)를 얻음 */
		File images[] = root.listFiles(f-> f.getName().matches(imgExt));

		BufferedImage bi[] = new BufferedImage[len = images.length];
		for(i=0;i<len;i++) {
			bi[i] = ImageIO.read(images[i]);
			maxWidth = Math.max(maxWidth, width = bi[i].getWidth()); //생성될 통합파일의 너비 계산
			totalHeight += bi[i].getHeight(); //생성될 통합파일의 총 높이 계산
		}
		
		/* 통합 이미지. 최대 너비 x 총 높이 */
		BufferedImage mergedImage = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics = (Graphics2D) mergedImage.getGraphics();
		graphics.setBackground(Color.BLACK); //여백은 검정으로 채움
		
		graphics.drawImage(bi[0], 0, 0, null); //처음엔 (0, 0)에 그리기
		preHeight = bi[0].getHeight();
		
		for(i=1;i<len;i++) {
			graphics.drawImage(bi[i], 0, preHeight, null);
			preHeight += bi[i].getHeight(); //높이를 누산해야됨
		}
		
		/* 병합된 이미지를 최종적으로 write */
		ImageIO.write(mergedImage, "jpg", new File(root+"/" + mergedName + ".jpg"));
		
	} catch (Exception e) {
		ErrorHandling.saveErrLog("이미지 병합 실패: "+mergedName, "", e);
		return;
	}
	System.out.println("성공");
}
 
Example 11
Project: VASSAL-src   File: ADC2Module.java   View Source Code Vote up 5 votes
public void drawFlagImage(Graphics2D g) {
  final int tabHeight = 15;
  final int tabWidth = 10;
  g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
  g.setColor(background);
  g.fillRoundRect(-tabWidth, 0, 2*tabWidth, tabHeight, 6, 6);
  g.setColor(foreground);
  g.drawRoundRect(-tabWidth, 0, 2*tabWidth-1, tabHeight-1, 6, 6);
  g.setFont(new Font("Dialog", Font.PLAIN, 9));
  Rectangle2D r = g.getFontMetrics().getStringBounds(name, g);
  g.drawString(name, tabWidth/2 - (int) (r.getWidth()/2.0) - 1, 11);
  g.setBackground(new Color(0,0,0,0));
  g.clearRect(-tabWidth, 0, tabWidth, tabHeight);
}
 
Example 12
Project: VASSAL-src   File: Symbol.java   View Source Code Vote up 5 votes
public static BufferedImage buildSizeImage(String size, int sym_w, int sym_h, int gap) {

      SizeOption option = findSize(size);
      String type = option.getType();
      int count = option.getCount();

      BufferedImage bi = createImage(count, sym_w, sym_h, gap);
      Graphics2D g = bi.createGraphics();
      g.setBackground(null);
      g.setColor(Color.BLACK);
      return buildSizeImage(g, count, type, sym_w, sym_h, gap);
    }
 
Example 13
Project: oscm   File: ImageProducer.java   View Source Code Vote up 5 votes
protected BufferedImage createImage(Color bgColor) {
    BufferedImage bufferedImage = new BufferedImage(END_X, END_Y,
            BufferedImage.TYPE_INT_RGB);
    // create graphics and graphics2d
    final Graphics graphics = bufferedImage.getGraphics();
    final Graphics2D g2d = (Graphics2D) graphics;

    // set the background color
    g2d.setBackground(bgColor == null ? Color.gray : bgColor);
    g2d.clearRect(START_X, START_Y, END_X, END_Y);
    // create a pattern for the background
    createPattern(g2d);
    // set the fonts and font rendering hints
    Font font = new Font("Helvetica", Font.ITALIC, 30);
    g2d.setFont(font);
    FontRenderContext frc = g2d.getFontRenderContext();
    g2d.translate(10, 24);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setStroke(new BasicStroke(3));

    // sets the foreground color
    g2d.setPaint(Color.DARK_GRAY);
    GlyphVector gv = font.createGlyphVector(frc, message);
    int numGlyphs = gv.getNumGlyphs();
    for (int ii = 0; ii < numGlyphs; ii++) {
        AffineTransform at;
        Point2D p = gv.getGlyphPosition(ii);
        at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
        at.rotate(Math.PI / 8);
        Shape shape = gv.getGlyphOutline(ii);
        Shape sss = at.createTransformedShape(shape);
        g2d.fill(sss);
    }
    return blurImage(bufferedImage);
}
 
Example 14
Project: Bachelor-Thesis   File: PlayField.java   View Source Code Vote up 5 votes
/**
 * Draws the play field. To be called by Swing framework or directly if
 * different context than screen is desired
 * @param g The graphics context to draw the field to
 */
public void paint(Graphics g) {
	Graphics2D g2 = (Graphics2D)g;
	g2.setBackground(bgColor);
	
	// clear old playfield graphics
	g2.clearRect(0, 0, this.getWidth(), this.getHeight());
	if (underlayImage != null) {
		g2.drawImage(underlayImage,curTransform, null);
	}

	// draw map (is exists and drawing requested)
	if (mapGraphic != null && showMapGraphic) {
		mapGraphic.draw(g2);
	}
	
	// draw hosts
	for (DTNHost h : w.getHosts()) {
		new NodeGraphic(h).draw(g2); // TODO: Optimization..?
	}
	
	// draw overlay graphics
	for (int i=0, n=overlayGraphics.size(); i<n; i++) {
		overlayGraphics.get(i).draw(g2);
	}
	
	// draw reference scale
	this.refGraphic.draw(g2);
}
 
Example 15
Project: What-Happened-to-Station-7   File: TStack.java   View Source Code Vote up 5 votes
public void apply(Graphics2D g)
{
	g.setTransform(transform);
	g.setPaint(paint);
	g.setStroke(stroke);
	g.setFont(font);
	g.setComposite(composite);
	g.setBackground(bgrnd);
	g.setClip(shape);
	g.setRenderingHints(hints);
}
 
Example 16
Project: hearthstone   File: Images.java   View Source Code Vote up 5 votes
private static ImageIcon getBlank(Dimension d) {
    BufferedImage bi = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D) bi.getGraphics();
    g2.setBackground(new Color(0, 0, 0, 0));
    g2.dispose();
    return new ImageIcon(bi);
}
 
Example 17
Project: the-one-mdonnyk   File: PlayField.java   View Source Code Vote up 5 votes
/**
 * Draws the play field. To be called by Swing framework or directly if
 * different context than screen is desired
 * @param g The graphics context to draw the field to
 */
public void paint(Graphics g) {
	Graphics2D g2 = (Graphics2D)g;
	g2.setBackground(bgColor);
	
	// clear old playfield graphics
	g2.clearRect(0, 0, this.getWidth(), this.getHeight());
	if (underlayImage != null) {
		g2.drawImage(underlayImage,curTransform, null);
	}

	// draw map (is exists and drawing requested)
	if (mapGraphic != null && showMapGraphic) {
		mapGraphic.draw(g2);
	}
	
	// draw hosts
	for (DTNHost h : w.getHosts()) {
		new NodeGraphic(h).draw(g2); // TODO: Optimization..?
	}
	
	// draw overlay graphics
	for (int i=0, n=overlayGraphics.size(); i<n; i++) {
		overlayGraphics.get(i).draw(g2);
	}
	
	// draw reference scale
	this.refGraphic.draw(g2);
}
 
Example 18
Project: jdk8u-jdk   File: JLightweightFrame.java   View Source Code Vote up 5 votes
@Override
public Graphics getGraphics() {
    if (bbImage == null) return null;

    Graphics2D g = bbImage.createGraphics();
    g.setBackground(getBackground());
    g.setColor(getForeground());
    g.setFont(getFont());
    g.scale(scaleFactor, scaleFactor);
    return g;
}
 
Example 19
Project: incubator-netbeans   File: NimbusViewTabDisplayerUI.java   View Source Code Vote up 4 votes
@Override
protected void paintTabBackground(Graphics g, int index, int x, int y,
                                  int width, int height) {
    boolean isLast = index == getDataModel().size()-1;
    if (!isLast) {
        width++;
    }

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

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

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

    if (isPreviousTabSelected) {
        g.setClip(clip);
    }
}
 
Example 20
Project: openjdk-jdk10   File: CrashTest.java   View Source Code Vote up 4 votes
private static void testHugeImage(final int width, final int height)
    throws ArrayIndexOutOfBoundsException
{
    System.out.println("---\n" + "testHugeImage: "
        + "width=" + width + ", height=" + height);

    final BasicStroke stroke = createStroke(2.5f, false, 0);

    // size > 24bits (exceed both tile and buckets arrays)
    System.out.println("image size = " + width + " x "+height);

    final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

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

        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, width, height);

        g2d.setStroke(stroke);
        g2d.setColor(Color.BLACK);

        final Path2D.Float path = new Path2D.Float(WIND_NON_ZERO, 32);
        path.moveTo(0, 0);
        path.lineTo(width, 0);
        path.lineTo(width, height);
        path.lineTo(0, height);
        path.lineTo(0, 0);

        final long start = System.nanoTime();

        g2d.draw(path);

        final long time = System.nanoTime() - start;

        System.out.println("paint: duration= " + (1e-6 * time) + " ms.");

        if (SAVE_IMAGE) {
            try {
                final File file = new File("CrashTest-huge-"
                    + width + "x" +height + ".bmp");

                System.out.println("Writing file: " + file.getAbsolutePath());
                ImageIO.write(image, "BMP", file);
            } catch (IOException ex) {
                System.out.println("Writing file failure:");
                ex.printStackTrace();
            }
        }
    } finally {
        g2d.dispose();
    }
}