Re: getImage and print...

Hi all,

as I was just the day before yesterday on the same topic, I thought I'd
contribute to the general knowledge of the list.

To implement a "save screenshot" JButton I do:

    snapBut= new JButton("Snapshot");
    snapBut.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent e)

  private void saveDisplay(){
    Runnable captureImage = new Runnable() {
      public void run() {

        JFileChooser fc= new JFileChooser();
        fc.setDialogTitle("Save screenshot as Jpeg");
        String dir = fc.getCurrentDirectory().getAbsolutePath();

        if(fc.showDialog(cframe, "Save") == JFileChooser.APPROVE_OPTION)
          System.out.println("Saving image..." );
          String cfn = fc.getSelectedFile().getName();

          BufferedImage image = display.getImage();

          FileOutputStream ffout = new
          JPEGEncodeParam jepar
          jepar.setQuality( 1.0f, true);

          JPEGImageEncoder jpege = JPEGCodec.createJPEGEncoder(ffout) ;
          jpege.encode(image, jepar);
          System.out.println("Saved "+cfn);

        else {
           System.out.println("No file was chosen or an error

      } catch(FileNotFoundException e){e.printStackTrace();
      } catch(IOException e){e.printStackTrace();



    Thread t = new Thread(captureImage);

with credits to Curtis (see the SpreadSheet, where such save display
method is implemented).

To print a display using a JButton I do:

    printBut= new JButton("Print");
    printBut.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent e)

  private void printDisplay(){
    Runnable printImage = new Runnable() {
      public void run() {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        if (printJob.printDialog()) {
           try {
           catch (Exception pe) {
    Thread t = new Thread(printImage);


Please note that in my app I've only got one display.

The catch in the "print display", is that it brings up a dialog where
you have to specify the absolute path, when printing to a file,
otherwise you get a nasty "no write permission" message, or something
like that.
I'd be happy if someone could tell me how to call the print dialog with
the full path name...

Oh, yes, this is done under Unix; I don't have a clue how it behaves in
Windows (I mena the stuff with the absolute path). Of course, you can
print direct to a printer, too :-)



  • 2000 messages navigation, sorted by:
    1. Thread
    2. Subject
    3. Author
    4. Date
    5. ↑ Table Of Contents
  • Search the visad archives: