我的代码应该打印我的JTextPane控件的内容,但是页面上没有打印任何内容。页面是空白的。这是我的代码:
@Override
public void actionPerformed(ActionEvent arg0) {
// kod za printanje sadrzaja iz JTextPane-a
/*
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new Editor());
boolean ok = job.printDialog();
if(ok){
try{
job.print();
}
catch(PrinterException pex){
JOptionPane.showMessageDialog(new Editor(), "Greška pri printanju dokumenta!", "Poruka", JOptionPane.INFORMATION_MESSAGE);
}
*/
try{
//System.out.println(tekst1.getText());
// PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
// attr_set.add(MediaSizeName.ISO_A4);
tekst1.setContentType("text/html");
tekst1.print();
}
catch(Exception pex){
pex.printStackTrace();
}
}
};
有人可以帮助我吗??
答案 0 :(得分:1)
由于您已将内容类型定义为text/html
,因此请在设置HTML编辑器套件后进行尝试。
jTextPane.setEditorKit(new HTMLEditorKit());
或者您可以通过将内容设置为text/pain
jTextPane.setContentType("text/plain");
或删除内容类型。
//jTextPane.setContentType("text/html");
有关更多信息,请参阅Java文档方法JEditorPane.setContentType()
包含屏幕截图的示例代码:
注意:将打印文件保存为Microsoft XPS Document Writer
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.text.html.HTMLEditorKit;
public class PrintJTextPane {
public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.setSize(500, 200);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextPane jTextPane = new JTextPane();
jTextPane.setEditorKit(new HTMLEditorKit());
JButton btn = new JButton("Print");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
jTextPane.setContentType("text/html");
boolean done = jTextPane.print();
if (done) {
JOptionPane.showMessageDialog(null, "Printing is done");
} else {
JOptionPane.showMessageDialog(null, "Error while printing");
}
} catch (Exception pex) {
JOptionPane.showMessageDialog(null, "Error while printing");
pex.printStackTrace();
}
}
});
jframe.add(btn, BorderLayout.SOUTH);
jframe.add(jTextPane);
jframe.setVisible(true);
}
}