Is anybody run the example below successfully?
Print All works fine but Print a portion does not
work on my NT. I am using jdk1.2.
Another question: How to save Swing components to an
image file (say *.jpg, *.gif ... ) ?
Any help would be greatly appreciated!
Daniel
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PrintSampler extends JFrame {
JButton btnPrnAll; //Print All...
JButton btnPrnImage; //Print Image...
Component scrollableObject; //object in the scroll pane
String FrameTitle; //frame and print page description
public PrintSampler(String title, Component bitmapImage) {
super(title);
FrameTitle = title;
scrollableObject = bitmapImage;
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(scrollableObject);
this.getContentPane().add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
btnPrnAll = new JButton("Print All...");
btnPrnAll.setMnemonic('A');
panel.add(btnPrnAll);
btnPrnImage = new JButton("Print Image...");
btnPrnImage.setMnemonic('I');
panel.add(btnPrnImage);
this.getContentPane().add(panel, BorderLayout.SOUTH);
ActionListener printSomething = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
btnPrnAll.setEnabled(false);
btnPrnImage.setEnabled(false);
Properties prnProp = new Properties();
PrintJob prnJob = Toolkit.getDefaultToolkit().getPrintJob(
PrintSampler.this, FrameTitle, prnProp);
if (prnJob != null) {
//System.out.println("Returned properties: " + props);
JButton b = (JButton)evt.getSource();
Component c;
Graphics prnGr = prnJob.getGraphics();
if (b==btnPrnAll) {
c = PrintSampler.this;
} else {
c = scrollableObject;
}
//Print in the center of the page
Dimension od = c.getSize(); //Object size
Dimension pd = prnJob.getPageDimension(); //Page size
prnGr.translate((pd.width-od.width)/2,
(pd.height-od.height)/2);
if (b==btnPrnAll) {
c.printAll(prnGr);
} else {
c.print(prnGr);
}
prnGr.dispose(); //Prints here
prnJob.end(); //Release printer
}
btnPrnAll.setEnabled(true);
btnPrnImage.setEnabled(true);
}
};
btnPrnAll.addActionListener(printSomething);
btnPrnImage.addActionListener(printSomething);
}
public static void main(String[] args) {
ImageIcon icon = new ImageIcon("jpgIcon.jpg");
JFrame f = new PrintSampler("Java/Swing print test", new
JLabel(icon));
f.setSize(300,200);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
f.setVisible(true);
}
} // end of class PrintSampler
=====================================================================
To subscribe/unsubscribe, send mail to [EMAIL PROTECTED]
Java 2D Home Page: http://java.sun.com/products/java-media/2D/