gpt4 book ai didi

Java 仅打印 Swing 中的特定部分

转载 作者:行者123 更新时间:2023-12-01 18:38:00 24 4
gpt4 key购买 nike

我想打印 Java GUI swing 中的某个部分。所以基本上我有一个框架,然后是其他 View ,如文本字段、标签、表格,然后是面板。面板内部有两个按钮。我想在打印时排除包含两个按钮的面板。我怎样才能做到这一点?到目前为止,这是我完成的代码:

  setTitle("VMS Sales Invoice");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 397, 628);
getContentPane().setLayout(null);

JLabel lblVatable = new JLabel("VATable");
lblVatable.setFont(new Font("SansSerif", Font.BOLD, 12));
lblVatable.setBounds(158, 468, 55, 16);
getContentPane().add(lblVatable);

txtTotalDiscount = new JTextField();
txtTotalDiscount.setFont(new Font("SansSerif", Font.BOLD, 12));
txtTotalDiscount.setEditable(false);
txtTotalDiscount.setBounds(256, 485, 122, 28);
getContentPane().add(txtTotalDiscount);
txtTotalDiscount.setColumns(10);

JLabel lblTotalDiscount = new JLabel("Total Discount");
lblTotalDiscount.setFont(new Font("SansSerif", Font.BOLD, 12));
lblTotalDiscount.setBounds(158, 496, 86, 16);
getContentPane().add(lblTotalDiscount);

setResizable(false);
setLocationRelativeTo(null); // THIS WILL CENTRE THE POSITION OF WINDOW
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);


public class btnPrintAction implements ActionListener, Printable{
public int print(Graphics gx, PageFormat pf, int page) throws PrinterException {

if (page > 0){
return NO_SUCH_PAGE;
} // Only one page
Graphics2D g = (Graphics2D)gx; // Cast to Graphics2D object
g.translate(pf.getImageableX(), pf.getImageableY()); // Match origins to imageable area
//g.drawString ("Hello world", 100, 100); // Print Hello World at offset (100, 100)

Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());

// Print the entire visible contents of a
// java.awt.Frame.
getContentPane().printAll(g);


return PAGE_EXISTS; // Page exists (offsets start at zero!)

}
public void actionPerformed(ActionEvent e) {

PrinterJob job = PrinterJob.getPrinterJob(); // Get the printer's job list
job.setPrintable(this); // We print with this class (btnPrintAction, which implements Printable)
if (job.printDialog() == true) { // If we clicked OK in the print dialog
try {
job.print();
} catch (PrinterException ex){
// It did not work (PrinterException thrown), so add any error handling routines.
JOptionPane.showMessageDialog(null, ex.toString(), "Printing Error",
JOptionPane.WARNING_MESSAGE);
}
}

}
}

您对如何实现这一目标有什么想法吗?我需要让这个工作。非常感谢您的帮助。谢谢。

最佳答案

定义用于打印的图形的剪辑区域。

g.setClip(int x, int y, int width, int height)

其中剪辑参数是面板边界。

关于Java 仅打印 Swing 中的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com