Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>All right, so you had three questions:</p> <p><b>First:</b> The reason why your window is small is because you're using jf.pack() along with a border layout, which makes your JFrame the size required to display all the component it contains without extra space around. You could set the layout to null and lose the jf.pack() part, but this is not usually a recommended practice.</p> <p><b>Second:</b> The window pops up a second time because you're creating a second instance of the same object in your listener there:</p> <pre><code>job.setPrintable( new Printer() ); </code></pre> <p>The "new Printer()" part creates another Printer object, which calls the UI creation again, etc. </p> <p>You could create an inner class instead of an anonymous class to be able to use "this" to refer to the current Printer object.</p> <p>Your hookUpEvents() method would be something like this:</p> <blockquote> <pre><code>public void hookUpEvents() { MyActionListener mal = new MyActionListener(); print.addActionListener(mal); { } </code></pre> </blockquote> <p>Then, somewhere else in the same class create the inner class like this:</p> <pre><code>private class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent ae) { PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(Printer.this); boolean doPrint = job.printDialog(); if( doPrint ) { try { job.print(); } catch( PrinterException exc) { System.out.println( exc ); } } else { System.out.println("You cancelled the print"); } } } </code></pre> <p><b>Third:</b> The print() method is called when you type: "job.print()" since you're overriding the method from the interface. The one in the interface is never actually called since yours is called instead, which is what you want since you defined what it had to do.</p> <p>I hope this answers your questions now.</p> <p><b>Edit:</b> I just tested something similar and I think you could just type Printer.this in the anonymous class to make it work instead of creating an inner class, which would have you change way less code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload