以编程方式触发Jasper Report Viewer打印按钮

时间:2015-03-17 14:11:45

标签: java jasper-reports

我有以下IReport类,我已经在" Escape"上实现了退出JRViewer。 Keypress如下,现在我需要在" Space"的按键上触发JRViewer的Print按钮。如果有人有想法,请指导我。 (代码应该出现在" CODE应该去这里"部分)

public class IReport extends javax.swing.JFrame {

    public IReport(String filename, HashMap parameter) {

        super("Report Viewer");

        //addWindowListener(this);
        setIcon();

        try {
            DefaultJasperReportsContext context = DefaultJasperReportsContext.getInstance();
            JRPropertiesUtil.getInstance(context).setProperty("net.sf.jasperreports.xpath.executer.factory",
                    "net.sf.jasperreports.engine.util.xml.JaxenXPathExecuterFactory");
            JasperPrint print = JasperFillManager.fillReport(filename, parameter, DatabaseService.getConnection());

            JRViewer viewer = new JRViewer(print);

            Container c = getContentPane();

            c.add(viewer);

            //When user press Escape report viewer get closed---------------------
            viewer.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "quit");
            viewer.getActionMap().put("quit", new AbstractAction() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    dispose();

                }

            });
            //---------------------------------------------------------------------

            //When user press space print button should be triggered---------------------
            viewer.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "print");
            viewer.getActionMap().put("print", new AbstractAction() {

                @Override
                public void actionPerformed(ActionEvent e) {

                    //CODE SHOULD GO HERE

                }

            });
            //---------------------------------------------------------------------

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        this.setExtendedState(MAXIMIZED_BOTH);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    }


}

1 个答案:

答案 0 :(得分:0)

据我所知,你可以做到的唯一方法就是扩展课程JRViewer

单击Print按钮btnPrintActionPerformed时调用的方法具有package-private可见性。这意味着只有同一个包中的类才能访问该方法。

然而,打印按钮本身具有protected可见性。因此,同一个包中的类以及子类都可以访问它。

因此,您可以创建一个扩展JRViewer的类,并添加一个getter来检索print按钮。

public class MyCustomJRViewer extends JRViewer {

    public JButton getPrintButton() {
        return btnPrint;
    }

}

使您的当前代码使用自定义JRViewer,并在您的操作中执行以下操作:

myCustomViewer.getActionMap().put("print", new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent e) {
        myCustomViewer.getPrintButton().actionPerformed(e);
    }

});