/** * Exports the plot to an image file. * @param file the destination file. * @throws IOException if an error occurs during writing. */ public void save(File file) throws IOException { BufferedImage bi = new BufferedImage(canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = bi.createGraphics(); canvas.print(g2d); ImageIO.write(bi, FileChooser.getExtension(file), file); }
Font font = g2d.getFont(); int x = (int) (getWidth() * (1 - margin) + 20); int y = (int) (getHeight() * margin + 50); int width = font.getSize(); int height = font.getSize(); FontMetrics fm = g.getFontMetrics(); int x = (getWidth() - fm.stringWidth(title)) / 2; int y = (int) (getHeight() * margin) / 2; g2d.drawString(title, x, y);
@Override public int print(java.awt.Graphics g, PageFormat pf, int page) throws PrinterException { if (page > 0) { // We have only one page, and 'page' is zero-based return NO_SUCH_PAGE; } Graphics2D g2d = (Graphics2D) g; // User (0,0) is typically outside the imageable area, so we must // translate by the X and Y values in the PageFormat to avoid clipping g2d.translate(pf.getImageableX(), pf.getImageableY()); // Scale plots to paper size. double scaleX = pf.getImageableWidth() / canvas.getWidth(); double scaleY = pf.getImageableHeight() / canvas.getHeight(); g2d.scale(scaleX, scaleY); // Disable double buffering canvas.setDoubleBuffered(false); // Now we perform our rendering canvas.print(g); // Enable double buffering canvas.setDoubleBuffered(true); // tell the caller that this page is part of the printed document return PAGE_EXISTS; }