extract your Swing code from your recursive image creation code. Actually think about creating a static method that creates and returns a BufferedImage, and it doesn't have Swing code. Then ask your GUI to call the method whenever it wants, and take the image and either write it to disk or display it in the JLabel ImageIcon.
When I did this (actually today), I created a recursive method with this signature
private static void recursiveDraw(BufferedImage img, Graphics imgG, double scale) {
and with this method body (in pseudocode)
start recursiveDraw method // most important: all recursions must have a good ending condition: get img height and width. If either <= a min, return create a BufferedImage, smlImg, for the smaller image using the height, width and scale factor Get the Graphics object, smlG, from the small image Use smlG.drawImage(...) overload to draw the big image in shrunken form onto the little image recursively call recursiveDraw passing in smlImg, smlG, and scale. dispose of smlG draw smlImg (the small image) onto the bigger one using the bigger Graphics object (passed into this method) and a different overload of the drawImage method. end recursiveDraw method
This algorithm led to the following images: 
For instance:
import java.awt.*; import java.awt.Dialog.ModalityType; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import javax.swing.*; public class RecursiveDrawTest { private static final Color BACKGRND_1 = Color.green; private static final Color BACKGRND_2 = Color.MAGENTA; private static final Color FOREGRND_1 = Color.blue; private static final Color FOREGRND_2 = Color.RED; private static void createAndShowGui() { final JPanel mainPanel = new JPanel(new BorderLayout()); final JSlider slider = new JSlider(50, 90, 65); slider.setMajorTickSpacing(10); slider.setMinorTickSpacing(5); slider.setPaintLabels(true); slider.setPaintTicks(true); JPanel southPanel = new JPanel(); southPanel.add(new JLabel("Percent Size Reduction:")); southPanel.add(slider); southPanel.add(new JButton(new AbstractAction("Create Recursive Image") { @Override public void actionPerformed(ActionEvent arg0) { try { double scale = slider.getValue() / 100.0; BufferedImage img = createRecursiveImg(scale); ImageIcon icon = new ImageIcon(img); JLabel label = new JLabel(icon); Window win = SwingUtilities.getWindowAncestor(mainPanel); JDialog dialog = new JDialog(win, "Image", ModalityType.MODELESS); dialog.getContentPane().add(label); dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setVisible(true); } catch (AWTException e) { e.printStackTrace(); } } })); mainPanel.add(new JScrollPane(new JLabel(new ImageIcon(createLabelImg()))), BorderLayout.CENTER); mainPanel.add(southPanel, BorderLayout.PAGE_END); JFrame frame = new JFrame("RecursiveDrawTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); }
source share