Java只打印一个特定的部分

时间:2014-01-09 10:13:15

标签: java swing

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

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

    }
}

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

2 个答案:

答案 0 :(得分:2)

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

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

剪辑的参数是面板边界。

答案 1 :(得分:2)

我能想到的一些解决方案:

  • 将按钮放在不同的面板中(简单,推荐)。
  • 在打印过程中使用setVisible(false)将按钮设置为不可见,然后再次显示(请记住setVisible不仅仅是满足眼睛)。
  • 手动修改打印机制,并使用覆盖打印/ printAll / printChildren(不推荐)。