使用JMenuItem打印打开的文档

时间:2014-06-23 10:42:44

标签: java swing awt

我想打印一个打开的文件,当我点击打印menuitem.I写了一些代码,但它没有正常工作。它显示打印对话框然后我点击打印按钮它没有被打印。请帮助我,谢谢。 我的代码:

public class PrintAction extends javax.swing.JFrame {

JScrollPane scrollPane;
JTextPane textPane;
int i=0;
public PrintAction() {
    initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    tabbedPane = new javax.swing.JTabbedPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    open = new javax.swing.JMenuItem();
    print = new javax.swing.JMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jMenu1.setText("File");

    open.setText("Open");
    open.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openActionPerformed(evt);
        }
    });
    jMenu1.add(open);

    print.setText("Print");
    print.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            printActionPerformed(evt);
        }
    });
    jMenu1.add(print);

    jMenuBar1.add(jMenu1);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

private void openActionPerformed(java.awt.event.ActionEvent evt) {                                     
     FileDialog fd = new FileDialog(PrintAction.this, "Select File", FileDialog.LOAD);
     fd.show();
     String title;
     String sts;
     if (fd.getFile() != null) {
       sts = fd.getDirectory() + fd.getFile();
       title=fd.getFile();
       BufferedReader br = null;
       StringBuffer str = new StringBuffer("");
       try {
           br = new BufferedReader(new FileReader(sts));
           String line;
           try {
                while ((line = br.readLine()) != null) {
                str.append(line + "\n");
                }
           } catch (IOException ex) {
                Logger.getLogger(PrintAction.class.getName()).log(Level.SEVERE, null, ex);
             }
       } catch (FileNotFoundException ex) {
            Logger.getLogger(PrintAction.class.getName()).log(Level.SEVERE, null, ex);
         }
       String t = str.toString();
       final JInternalFrame internalFrame = new JInternalFrame("",true,true);  
       textPane = new JTextPane();
       textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
       internalFrame.add(textPane);
       i+=1;
       internalFrame.setName("Document"+i);
       scrollPane=new JScrollPane(textPane);
       internalFrame.add(scrollPane); 
       internalFrame.setTitle(title);
       tabbedPane.add(internalFrame);
       internalFrame.setVisible(true);   
       textPane.setText(t);
       try {
            br.close();
            } 
         catch (IOException ex) {
            Logger.getLogger(PrintAction.class.getName()).log(Level.SEVERE, null, ex);
        }

}     }

private void printActionPerformed(java.awt.event.ActionEvent evt) {                                      
      PrinterJob pj = PrinterJob.getPrinterJob();
      HashPrintRequestAttributeSet printAttr = new HashPrintRequestAttributeSet();
      if(pj.printDialog(printAttr))     // Display print dialog
      {            // If true is returned...
      try
      {
      pj.print(printAttr);    // then print
      }
      catch(PrinterException e)
      {
      JOptionPane.showMessageDialog(this,"Failed to print the file: "+e,"Error",JOptionPane.ERROR_MESSAGE);
      }
      }
}                                     
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(PrintAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(PrintAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(PrintAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(PrintAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new PrintAction().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JMenuItem print;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration                   

}

1 个答案:

答案 0 :(得分:0)

如果您想打印文本窗格的内容,您应该能够使用JTextComponent的print()方法:

textPane.print();

这将显示一个打印对话框并打印JTextPane的内容。

另请参阅http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#print()http://docs.oracle.com/javase/tutorial/uiswing/misc/printtext.html,了解有关如何从组件中打印文字的更多信息。