title: Resize JComponent for file export
body: <p>I have a JPanel upon which I draw a number of custom-written JComponents using the usual 'paintComponent(Graphics g)' method.  I use a JLayeredPane to control the display order of the custom components, as follows:</p>
  
  <pre><code>public Class MyPanel extends JPanel {
      private JLayeredPane layeredPane = new JLayeredPane();
      private JComponent component1;
      private JComponent component2;
  
      public MyPanel() {
          super();
          setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
  
          component1 = new CustomComponent1();
          layeredPane.add (component1, new Integer(0));
  
          component2 = new CustomComponent2();
          layeredPane.add (component2, new Integer(1));
  
          add (layeredPane);
      }
  
      public void resizePanel(Graphics g, int newWidth, int newHeight) {
          component1.setBounds (f(x), f(y), f(newWidth), f(newHeight));
          component2.setBounds (f(x), f(y), f(newWidth), f(newHeight));
      }
  
      public void paintComponent(Graphics g) {
          if ((getWidth() != oldWidth) || (getHeight() != oldHeight)) {
              oldWidth = getWidth();
              oldHeight = getHeight();
              resizePanel (g, getWidth(), getHeight());
          }
          super.paintComponent(g);
      }
  </code></pre>
  
  <p>Now, I would like to export this panel to a JPEG file, but with a different size.  When I use the following code, it successfully creates/exports a JPEG file of the desired size, but it also updates my screen image version of the panel to the new size!  Yikes!</p>
  
  <pre><code>public void export(File file, int width, int height)
      throws IOException
  {
      BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = scaledImage.createGraphics();
      resizePanel (g2, width, height);
      super.paintComponent (g2);
  
      try {
          OutputStream out = new FileOutputStream(file);
          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
          encoder.encode(scaledImage);
          out.close();
      } catch (FileNotFoundException e) {
          throw new IOException ("Unable to export chart to ("
                    + file.getAbsolutePath() + "): " + e.getLocalizedMessage());
      } finally {
          g2.dispose();
      }
  }
  </code></pre>
  
  <p>How can I 'draw' an image suitable for exporting, but not actually cause this new image to be displayed?</p>
  
  <p>Thanks!</p>
  
  <hr>
  
  <p>Well, I'm back to this problem again.....</p>
  
  <p>The scene I'm painting includes some text and now the end user wants the graph exported in a 'portrait' aspect ratio. Since I'm not repainting the scene in the new dimensions but just scaling the image, this causes the text to be seriously squashed horizontally.</p>
  
  <p>Anyway around that? </p>