JDK-4290780 : printing empty pages using Book and hidden JTextPane
  • Type: Bug
  • Component: client-libs
  • Sub-Component: javax.swing
  • Affected Version: 1.2.2
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_nt
  • CPU: x86
  • Submitted: 1999-11-12
  • Updated: 2005-05-23
  • Resolved: 2005-05-23
Related Reports
Duplicate :  
Description

Name: mc57594			Date: 11/11/99


We use jdk1.2.2 on Windows NT4.0

Changing the comments in the method printData() of the following example
shows two different effects.

Leaving the comments as they are, all pages printed are just empty.
There is no error message.

Using the JTextPane which is displayed the pages are not empty.


<<<<<<<<<<<<<<<<<<<<<<< snip >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.sql.*;

import java.awt.print.*;
import javax.swing.plaf.basic.*;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.text.rtf.*;
import javax.swing.undo.*;

public class PrintTextExample extends JFrame
{

  protected JTextPane textPane;
  protected JTextPane[] printPanes = null;
  protected int numberOfTextPane = 10;
  protected StyleContext styleContext;
  protected DefaultStyledDocument doc;
  protected StyledEditorKit kit;
  protected JFileChooser fileChooser;
  protected JToolBar toolBar;

  protected JComboBox cbFonts;
  protected JComboBox cbSizes;
  protected JToggleButton boldButton;
  protected JToggleButton italicButton;

  protected String fontName = "";
  protected int fontSize = 11;
  
  protected String[] fontNames;
  protected String[] fontSizes;

  protected boolean update;

  protected int startPos = -1;
  protected int finishPos = -1;

  public PrintTextExample() {
    super("PrintText Example");
    setSize(600, 400);
    textPane = new JTextPane();
    kit = new StyledEditorKit();
    textPane.setEditorKit(kit);
    styleContext = new StyleContext();
    doc = new DefaultStyledDocument(styleContext);
    textPane.setDocument(doc);

    JScrollPane ps = new JScrollPane(textPane);
    getContentPane().add(ps, BorderLayout.CENTER);

    JMenuBar menuBar = new JMenuBar();
    
    // ************** file menu ***************************
    JMenu mFile = new JMenu("File");
    
    // menu item new
    Action actionNew = new AbstractAction("New") {
      public void actionPerformed(ActionEvent e) {
        doc = new DefaultStyledDocument(styleContext);
        textPane.setDocument(doc);
        showAttributes(0);
      }
    };
    JMenuItem item =  mFile.add(actionNew);
    
    // add menu item print
    Action actionPrint = new AbstractAction("Print") {
      public void actionPerformed(ActionEvent e) {
        Thread runner = new Thread() {
          public void run() {
            printData();
          }
        };
        runner.start();
      }
    };
    item =  mFile.add(actionPrint);

    mFile.addSeparator();

    // add menu item exit
    Action actionExit = new AbstractAction("Exit") {
      public void actionPerformed(ActionEvent e) {
        System.exit(0);
      }
    };

    item =  mFile.add(actionExit);

    menuBar.add(mFile);
    setJMenuBar(menuBar);

    // ************** tool bar for font adjustment ***************************
    toolBar = new JToolBar();
    
    GraphicsEnvironment ge = GraphicsEnvironment.
      getLocalGraphicsEnvironment();
    fontNames = ge.getAvailableFontFamilyNames();

    //toolBar.addSeparator();
    cbFonts = new JComboBox(fontNames);
    cbFonts.setMaximumSize(cbFonts.getPreferredSize());
    cbFonts.setEditable(true);

    ActionListener lst = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fontName = cbFonts.getSelectedItem().toString();
        MutableAttributeSet attr = new SimpleAttributeSet();
        StyleConstants.setFontFamily(attr, fontName);
        setAttributeSet(attr);
        textPane.grabFocus();
      }
    };
    cbFonts.addActionListener(lst);
    toolBar.add(cbFonts);

    toolBar.addSeparator();
    
    fontSizes = new String[] {"8", "9", "10", "11", "12", "14",
      "16", "18", "20", "22", "24", "26", "28", "36", "48", "72"};
    cbSizes = new JComboBox(fontSizes);
    cbSizes.setMaximumSize(cbSizes.getPreferredSize());
    cbSizes.setEditable(true);

    lst = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        int newFontSize = 0;
        try {
          newFontSize = Integer.parseInt(cbSizes.
            getSelectedItem().toString());
        }
        catch (NumberFormatException ex) { return; }

        fontSize = newFontSize;
        MutableAttributeSet attr = new SimpleAttributeSet();
        StyleConstants.setFontSize(attr, fontSize);
        setAttributeSet(attr);
        textPane.grabFocus();
      }
    };
    cbSizes.addActionListener(lst);
    toolBar.add(cbSizes);

    toolBar.addSeparator();

    boldButton = new JToggleButton("bold");
    lst = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        MutableAttributeSet attr = new SimpleAttributeSet();
        StyleConstants.setBold(attr, boldButton.isSelected());
        setAttributeSet(attr);
        textPane.grabFocus();
      }
    };
    boldButton.addActionListener(lst);
    toolBar.add(boldButton);

    toolBar.addSeparator();

    italicButton = new JToggleButton("italic");
    lst = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        MutableAttributeSet attr = new SimpleAttributeSet();
        StyleConstants.setBold(attr, italicButton.isSelected());
        setAttributeSet(attr);
        textPane.grabFocus();
      }
    };
    italicButton.addActionListener(lst);
    toolBar.add(italicButton);
    getContentPane().add(toolBar, BorderLayout.NORTH);
        
    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);

    CaretListener caretLst = new CaretListener() {
      public void caretUpdate(CaretEvent e) {
        showAttributes(e.getDot());
      }
    };
    textPane.addCaretListener(caretLst);

    FocusListener focusLst = new FocusListener() {
      public void focusGained(FocusEvent e) {
        if (startPos>=0 && finishPos>=0)
          if (textPane.getCaretPosition()==startPos) {
            textPane.setCaretPosition(finishPos);
            textPane.moveCaretPosition(startPos);
          }
          else
            textPane.select(startPos, finishPos);
      }

      public void focusLost(FocusEvent e) {
        startPos = textPane.getSelectionStart();
        finishPos = textPane.getSelectionEnd();
      }
    };
    textPane.addFocusListener(focusLst);

    showAttributes(0);
    setVisible(true);
  }

  
  protected void setAttributeSet(AttributeSet attr) {
    setAttributeSet(attr, false);
  }

  protected void setAttributeSet(AttributeSet attr,
   boolean setParagraphAttributes)
  {
    if (update)
      return;
    int xStart = textPane.getSelectionStart();
    int xFinish = textPane.getSelectionEnd();
    if (!textPane.hasFocus()) {
      xStart = startPos;
      xFinish = finishPos;
    }
    if (setParagraphAttributes)
      doc.setParagraphAttributes(xStart,
      xFinish - xStart, attr, false);
    else if (xStart != xFinish)
      doc.setCharacterAttributes(xStart,
        xFinish - xStart, attr, false);
    else {
      MutableAttributeSet inputAttributes =
        kit.getInputAttributes();
      inputAttributes.addAttributes(attr);
    }
  }

  protected void showAttributes(int p) {
    update = true;
    AttributeSet a = doc.getCharacterElement(p).
      getAttributes();
    String name = StyleConstants.getFontFamily(a);
    if (!fontName.equals(name)) {
      fontName = name;
      cbFonts.setSelectedItem(name);
    }
    int size = StyleConstants.getFontSize(a);
    if (fontSize != size) {
      fontSize = size;
      cbSizes.setSelectedItem(Integer.toString(fontSize));
    }
    boolean bold = StyleConstants.isBold(a);
    if (bold != boldButton.isSelected())
      boldButton.setSelected(bold);
    boolean italic = StyleConstants.isItalic(a);
    if (italic != italicButton.isSelected())
      italicButton.setSelected(italic);
   update = false;
  }
  
      
  public void printData() {
    
    getJMenuBar().repaint();
    StyledEditorKit printKit[] = new StyledEditorKit[numberOfTextPane];
    StyleContext printStyleContext[] = new StyleContext[numberOfTextPane];
    DefaultStyledDocument printDoc[] = new DefaultStyledDocument[numberOfTextPane];
    
    // create 10 JTextPane with same content
    printPanes = new JTextPane[numberOfTextPane];
    for(int k = 0; k < printPanes.length; k++)
    {
    	printPanes[k] = new JTextPane();
    	printKit[k] = new StyledEditorKit();
    	printPanes[k].setEditorKit(printKit[k]);
    	printStyleContext[k] = new StyleContext();
    	printDoc[k] = new DefaultStyledDocument(printStyleContext[k]);
    	String s = "---- page  " + k + " ---------";
    	try {
    	   s = s + doc.getText(0,doc.getLength());
    	   printDoc[k].insertString(0,
                         s,
                         new SimpleAttributeSet());
        }catch(BadLocationException ble) { }
    	printPanes[k].setDocument(printDoc[k]);
    	
    }
    
    try {
      PrinterJob prnJob = PrinterJob.getPrinterJob();
      PrintTextPane pPage = null;
      PageFormat pf = prnJob.defaultPage();
      Book pBook = new Book();
      
      // add pages to the book
      for(int i = 0; i < numberOfTextPane;i++)
      {
      	// doesn't work - the printed pages are empty - no Exception occures
      	pPage = new PrintTextPane(printPanes[i]);
      	pBook.append(pPage,pf,1);
      	
      	// add the visible textPane to the book works properly
      	// all pages are printed
      	//pPage = new PrintTextPane(textPane);
      	//pBook.append(pPage,pf,1);
      	
      }
      prnJob.setPageable(pBook);
      //prnJob.setPrintable(this);
      if (!prnJob.printDialog())
        return;
      setCursor( Cursor.getPredefinedCursor(
        Cursor.WAIT_CURSOR));
      prnJob.print();
      setCursor( Cursor.getPredefinedCursor(
        Cursor.DEFAULT_CURSOR));
      JOptionPane.showMessageDialog(this,
        "Printing completed successfully", "Info",
        JOptionPane.INFORMATION_MESSAGE);
    }
    catch (PrinterException e) {
      e.printStackTrace();
      System.err.println("Print error: "+e.toString());
    }
    
        
  }


public static void main(String argv[]) {
    new PrintTextExample();
  }

class PrintTextPane implements Printable {
    
    JTextPane page =null;
    
    public PrintTextPane(JTextPane page){
	   this.page = page;
    }


  public int print(Graphics pg, PageFormat pageFormat,
   int pageIndex) throws PrinterException {
    
    if(page == null) return NO_SUCH_PAGE;
    else {
	    pg.translate((int)pageFormat.getImageableX(),
	      (int)pageFormat.getImageableY());
	    int wPage = (int)pageFormat.getImageableWidth();
	    int hPage = (int)pageFormat.getImageableHeight();
	    pg.setClip(0, 0, wPage, hPage);
	    // paint text on the pinter graphics context
	    page.paintAll(pg);
	
	    return PAGE_EXISTS;
    }
  }
// end of class PrintPage
}



// end of class TextExample
}
<<<<<<<<<<<<<<<<<<<<<<< snip >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
(Review ID: 96551) 
======================================================================

Comments
EVALUATION closing this bug as the diplicate of 4791649 [Text components need printing support] ###@###.### 2005-05-23 22:33:12 GMT
23-05-2005

WORK AROUND Name: mc57594 Date: 11/11/99 Make the page you want to print visible. ======================================================================
25-09-2004