How does boolean here become false on its own

给你一囗甜甜゛ 提交于 2020-01-25 07:19:46

问题


This is action listener of print button

public void hookUpEvents() {
 print.addActionListener( new ActionListener() {
   public void actionPerformed( ActionEvent ae ) {
      PrinterJob job = PrinterJob.getPrinterJob();
      job.setPrintable( new Printer() );
      boolean doPrint = job.printDialog();  // boolean variable
       if( doPrint ) {
           try {
            job.print();
           }  catch( PrinterException exc) {
                System.out.println( exc );
              }
       }  else {
            System.out.println("You cancelled the print");
          } 
   }
});

}

When i compile this snippet along with whole code , print button gets displayed . The above is the action listener of the print button.

As i click the print button this dialog box is displayed :

Automatically after 3-4 seconds You cancelled the print is displayed on the cmd. How does this happen ? And when i click cancel nothing is displayed. How can the statement job.printDialog(); return false on its own ?

complete code

// Program to print simple text on a Printer

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.awt.print.*;


class Printer extends JPanel implements Printable  {

JButton print;

 Printer() {
  buildGUI();
  hookUpEvents();
}


public void buildGUI() {
  JFrame fr = new JFrame("Program to Print on a Printer");
  JPanel p = new JPanel();
  print = new JButton("Print");
  p.setBackground( Color.black );
  fr.add(p);
  p.add( print , BorderLayout.CENTER );
  this.setPreferredSize( new Dimension ( 300,200 ) );
  fr.pack();
  fr.setVisible( true );

}

public void hookUpEvents() {
 print.addActionListener( new ActionListener() {
   public void actionPerformed( ActionEvent ae ) {
      PrinterJob job = PrinterJob.getPrinterJob();
      job.setPrintable( Printer.this );
      boolean doPrint = job.printDialog();
//  PageFormat pf = job.pageDialog(job.defaultPage());
       if( doPrint ) {
           try {
            job.print();
           }  catch( PrinterException exc) {
                System.out.println( exc );
              }
       }  else {
            System.out.println("You cancelled the print");
          } 
   }
 });
 }

 public int print( Graphics g , PageFormat pf , int pageIndex) throws PrinterException{
   return PAGE_EXISTS;
 }

public static void main( String args[] ) {
   new Printer();
}

}


回答1:


Per the API, the print dialog is handled by the operating system, not the JVM, so I'm not completely surprised that different folks with different set ups could have different results. I suggest you try running it with an actual printer and see what happens.



来源:https://stackoverflow.com/questions/6594921/how-does-boolean-here-become-false-on-its-own

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!