Dessiner mon GUI pour une impression
Bonjour,
J'aimerais imprimer le contenu d'un JPanel (ou d'une JFrame). Actuellement j'ai le code suivant :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main {
/**
* @param args
*/
static JFrame frame;
public static void main(String[] args) {
frame=new JFrame();
JPanel pann=new JPanel();
pann.add(new JLabel("yop"));
frame.setContentPane(pann);
frame.setVisible(true);
frame.pack();
Rapport.print();
}
}
class Rapport {
static void print() {
// Récupère un PrinterJob
PrinterJob job = PrinterJob.getPrinterJob();
// Définit son contenu à imprimer
job.setPrintable(new PrintRapport());
// Affiche une boîte de choix d'imprimante
if (job.printDialog()){
try {
// Effectue l'impression
job.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
}
}
class PrintRapport implements Printable {
/** Constructeur par défaut de PrintRectangle */
public PrintRapport() {
}
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
// Par défaut, retourne NO_SUCH_PAGE => la page n'existe pas
int retValue = Printable.NO_SUCH_PAGE;
switch(pageIndex){
case 0 : {
// Dessin de la première page
// Récupère la dimension de la zone imprimable
double xLeft = pageFormat.getImageableX();
double yTop = pageFormat.getImageableY();
double width = pageFormat.getImageableWidth();
double height = pageFormat.getImageableHeight();
// La page est valide
retValue = Printable.PAGE_EXISTS;
graphics=Main.frame.getGraphics();
graphics.setClip((int)xLeft, (int)yTop, (int)width, (int)height);
break;
}
}
return retValue;
}
} |
Mais la page est vide et j'ai l'impression que Main.frame.getGraphics(); ne retourne pas ce qu'il y a dans la frame mais plutot une "image" vide.
Merci d'avance pour votre aide