Hi,
> I'm developing a small application in java, and I need to do some
> printing. I've been looking at jdk 1.1.6 documentation, but I
haven't
> been able to find anything useful. Does anyone knows where is some
good
> info about this ?
Does this help?
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class PrintTest extends JFrame implements ActionListener {
private static Frame VrFrame;
private SdActionManager actionManager = new SdActionManager();
public PrintTest() {
super(" PrintTest");
// just put on a panel and print button and make it call
printOnPaper,
//pass the frame as an argument
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent we) {System.exit(0);}});
}
public static void main(String[] args) {
PrintTest frame = new PrintTest();
frame.pack();
frame.setVisible(true);
}
public void printOnPaper(Frame f) {
Properties props = new Properties();
PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(f, "Test",
props);
if ( pj == null ) {
JOptionPane.showMessageDialog(this, "printing cancelled");
return;
}
int screenResolution =
Toolkit.getDefaultToolkit().getScreenResolution();
int topMargin = screenResolution;
int bottomMargin = screenResolution;
int leftMargin = screenResolution/2;
int rightMargin = screenResolution/2;
Dimension pageSize = new Dimension( pj.getPageDimension() );
pageSize.height -= topMargin + bottomMargin;
pageSize.width -= leftMargin + rightMargin;
try {
Font fnt = getFont();
FontMetrics fm =
Toolkit.getDefaultToolkit().getFontMetrics(fnt);
Graphics g = null;
String data = "Hello World!";
g = pj.getGraphics();
g.translate(leftMargin, topMargin);
g.clipRect(0, 0, pageSize.width, pageSize.height);
g.setFont( fnt );
g.drawString(data, 0, fm.getHeight());
g.drawString( data, pageSize.width - fm.stringWidth(data),
pageSize.height - fm.getHeight() );
g.dispose();
g = null;
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "printing Error: " + e);
} finally {
pj.end();
JOptionPane.showMessageDialog(this, "printing complete");
}
}
}
I have used this on JDK 1.1.6 on NT and Linux. Win NT counts the
pagedimension as the printable area of the paper and Linux as the
paper size. Other than that OK.
Regards
Dave
David Warnock
Sundayta Ltd