Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you want to do printing with Java with any kind of formatting instead of plain text, you need to use <code>javax.print</code>. It is quite similar to the 2D graphics.</p> <p>Have a look at the official tutorial at <a href="http://docs.oracle.com/javase/tutorial/2d/printing/" rel="nofollow">http://docs.oracle.com/javase/tutorial/2d/printing/</a> to learn how to do it.</p> <p>From <a href="http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/2d/printing/examples/HelloWorldPrinter.java" rel="nofollow">http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/2d/printing/examples/HelloWorldPrinter.java</a> (untested):</p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.print.*; public class HelloWorldPrinter implements Printable, ActionListener { public int print(Graphics g, PageFormat pf, int page) throws PrinterException { if (page &gt; 0) { /* We have only one page, and 'page' is zero-based */ return NO_SUCH_PAGE; } /* 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 */ Graphics2D g2d = (Graphics2D)g; g2d.translate(pf.getImageableX(), pf.getImageableY()); /* Now we perform our rendering */ g.drawString("Hello world!", 100, 100); /* tell the caller that this page is part of the printed document */ return PAGE_EXISTS; } public void actionPerformed(ActionEvent e) { PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(this); boolean ok = job.printDialog(); if (ok) { try { job.print(); } catch (PrinterException ex) { /* The job did not successfully complete */ } } } public static void main(String args[]) { UIManager.put("swing.boldMetal", Boolean.FALSE); JFrame f = new JFrame("Hello World Printer"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); JButton printButton = new JButton("Print Hello World"); printButton.addActionListener(new HelloWorldPrinter()); f.add("Center", printButton); f.pack(); f.setVisible(true); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload