簡體   English   中英

這里的 boolean 如何自行變為假

[英]How does boolean here become false on its own

這是打印按鈕的動作監聽器

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");
          } 
   }
});

}

當我將此代碼段與整個代碼一起編譯時,會顯示打印按鈕 以上是打印按鈕的動作監聽器。

當我單擊打印按鈕時,將顯示此對話框:

在此處輸入圖像描述

3-4 秒后自動取消打印顯示在 cmd 上。 這是怎么發生的? 當我點擊取消時,什么都沒有顯示。 怎么能聲明job.printDialog(); 自己返回false?

完整代碼

// 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();
}

}

根據 API,打印對話框由操作系統處理,而不是 JVM,所以我並不完全驚訝於具有不同設置的不同人可能有不同的結果。 我建議您嘗試使用實際的打印機運行它,看看會發生什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM