title: How to print a JPanel with swing components?
body: <p>I am trying to  print a JPanel using java.awt.print.I want to print out a JPanel.I have tried the following code which consists of only one button.When printed it appears on the left corner of the page,but I need to print it in the original position as it appears on the screen.Is there way to set bounds to give an exact position?</p>
  
  <p>enter code here</p>
  
  <pre><code>import java.awt.*;
  import java.awt.print.*;
  import javax.swing.*;
  import java.awt.event.*;
  
  public class PrintButton extends JPanel implements
          Printable, ActionListener {
  
      JButton ok = new JButton("OK");
  
      public PrintButton() {
          ok.addActionListener(this);
          this.setPreferredSize(new Dimension(400, 400));
          this.add(ok);
          JFrame frame = new JFrame("Print");
          frame.getContentPane().add(this);
          frame.pack();
          frame.setVisible(true);
      }
  
      public static void main(String[] args) {
          new PrintButton();
      }
  
      public void actionPerformed(ActionEvent e) {
  
  
          PrinterJob printJob = PrinterJob.getPrinterJob();
          printJob.setPrintable(this);
          if (printJob.printDialog()) {
              try {
                  printJob.print();
              } catch (Exception ex) {
                  throw new RuntimeException(ex);
              }
          }
      }
  
      public int print(Graphics g, PageFormat pf, int index) throws
              PrinterException {
  
          Graphics2D g2 = (Graphics2D) g;
          if (index &gt;= 1) {
              return Printable.NO_SUCH_PAGE;
          } else {
  
              ok.printAll(g2);
              return Printable.PAGE_EXISTS;
          }
  
      }
  }
  </code></pre>