문제

I'm having a NullPointerException when I'm trying to print a JLabel's icon. All I want is to print it on a paper using a button. What seems to be my error? Here's my code:

package at;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;

public class M extends javax.swing.JFrame {

/**
 * Creates new form M
 */
public M() {
    initComponents();
}

public static void printComponent(JComponent comp, boolean fill) throws PrinterException {
    PrinterJob pjob = PrinterJob.getPrinterJob();
    PageFormat pf = pjob.defaultPage();
    pf.setOrientation(PageFormat.LANDSCAPE);

    PageFormat postformat = pjob.pageDialog(pf);
    if (pf != postformat) {
        //Set print component
        pjob.setPrintable(new ComponentPrinter(comp, fill), postformat);
        if (pjob.printDialog()) {
            pjob.print();
        }
    }
}

public static void printComponentToFile(Component comp, boolean fill) throws PrinterException {
    Paper paper = new Paper();
    paper.setSize(8.3 * 72, 11.7 * 72);
    paper.setImageableArea(18, 18, 559, 783);

    PageFormat pf = new PageFormat();
    pf.setPaper(paper);
    pf.setOrientation(PageFormat.LANDSCAPE);

    BufferedImage img = new BufferedImage(
            (int) Math.round(pf.getWidth()),
            (int) Math.round(pf.getHeight()),
            BufferedImage.TYPE_INT_RGB);

    Graphics2D g2d = img.createGraphics();
    g2d.setColor(Color.WHITE);
    g2d.fill(new Rectangle(0, 0, img.getWidth(), img.getHeight()));
    ComponentPrinter cp = new ComponentPrinter(comp, fill);
    try {
        cp.print(g2d, pf, 0);
    } finally {
        g2d.dispose();
    }

    try {
        ImageIO.write(img, "jpg", new File("Page-" + (fill ? "Filled" : "") + ".jpg"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

public static class ComponentPrinter implements Printable {

    private Component comp;
    private boolean fill;

    public ComponentPrinter(Component comp, boolean fill) {
        this.comp = comp;
        this.fill = fill;
    }

    @Override
    public int print(Graphics g, PageFormat format, int page_index) throws PrinterException {

        if (page_index > 0) {
            return Printable.NO_SUCH_PAGE;
        }

        Graphics2D g2 = (Graphics2D) g;
        g2.translate(format.getImageableX(), format.getImageableY());

        double width = (int) Math.floor(format.getImageableWidth());
        double height = (int) Math.floor(format.getImageableHeight());

        if (!fill) {

            width = Math.min(width, comp.getPreferredSize().width);
            height = Math.min(height, comp.getPreferredSize().height);

        }

        comp.setBounds(0, 0, (int) Math.floor(width), (int) Math.floor(height));
        if (comp.getParent() == null) {
            comp.addNotify();
        }
        comp.validate();
        comp.doLayout();
        comp.printAll(g2);
        if (comp.getParent() != null) {
            comp.removeNotify();
        }

        return Printable.PAGE_EXISTS;
    }

}


/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jButton1 = new javax.swing.JButton();
    BtnBack = new javax.swing.JButton();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("A");
    setBackground(new java.awt.Color(255, 255, 255));
         setIconImage(Toolkit.getDefaultToolkit().getImage(MappingScreen.class.getResource("/at/icon.jpg")));
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    jButton1.setText("PRINT");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(1150, 650, 90, 30));

    BtnBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adventureresort/back.png"))); // NOI18N
    BtnBack.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            BtnBackActionPerformed(evt);
        }
    });
    getContentPane().add(BtnBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 620, 80, -1));

    jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/at/mapp.jpg"))); // NOI18N
    getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));

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

private void BtnBackActionPerformed(java.awt.event.ActionEvent evt) {                                        
Home home =new Home();
home.show();
dispose();
}                                       

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {       
        printComponent(jLabel2, false);
    } catch (PrinterException ex) {
        Logger.getLogger(MappingScreen.class.getName()).log(Level.SEVERE, null, ex);
    }

}                                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    try {
        JLabel label = new JLabel(
                "This is a test",
                new ImageIcon("/at/mapp.jpg"),
                JLabel.CENTER);
        printComponentToFile(label, true);
        printComponentToFile(label, false);
    } catch (PrinterException exp) {
        exp.printStackTrace();
    }
    /* 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(M.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(M.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(M.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(M.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 M().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton BtnBack;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel2;
// End of variables declaration    

}

Please help. I'm using netbeans. I really to print this jLabel's icon to complete a project.

Here's the error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
at at.M.initComponents(M.java:162)
at at.M.<init>(M.java:39)
at at.M$3.run(M.java:231)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

올바른 솔루션이 없습니다

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top