JumbledImageApp.java
import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; import java.util.Random; class JumbledImage extends JComponent { private int numlocs = 2; private int numcells = numlocs*numlocs; private int[] cells; private BufferedImage bi; int w, h, cw, ch; public JumbledImage(URL imageSrc) { try { bi = ImageIO.read(imageSrc); w = bi.getWidth(null); h = bi.getHeight(null); } catch (IOException e) { System.out.println("Image could not be read"); // System.exit(1); } cw = w/numlocs; ch = h/numlocs; cells = new int[numcells]; for (int i=0;i<numcells;i++) { cells[i] = i; } } void jumble() { Random rand = new Random(); int ri; for (int i=0; i<numcells; i++) { while ((ri = rand.nextInt(numlocs)) == i); int tmp = cells[i]; cells[i] = cells[ri]; cells[ri] = tmp; } } public Dimension getPreferredSize() { return new Dimension(w, h); } public void paintComponent(Graphics g) { super.paintComponent(g); int dx, dy; for (int x=0; x<numlocs; x++) { int sx = x*cw; for (int y=0; y<numlocs; y++) { int sy = y*ch; int cell = cells[x*numlocs+y]; dx = (cell / numlocs) * cw; dy = (cell % numlocs) * ch; g.drawImage(bi, dx, dy, dx+cw, dy+ch, sx, sy, sx+cw, sy+ch, null); } } } } public class JumbledImageApp extends JPanel { static String imageFileName = "duke_skateboard.jpg"; JButton jumbleButton; private URL imageSrc; private JumbledImage ji; public JumbledImageApp() { imageSrc = getClass().getResource(imageFileName); } public JumbledImageApp (URL imageSrc) { this.imageSrc = imageSrc; } public void buildUI() { ji = new JumbledImage(imageSrc); add(ji); jumbleButton = new JButton("Jumble"); jumbleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton b = (JButton)e.getSource(); ji.jumble(); ji.repaint(); }; }); } public static void main(String args[]) { String filename = imageFileName; if (args.length>0) filename = args[0]; JFrame f = new JFrame("Jumbled Image"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); URL imageSrc = null; try { imageSrc = ((new File(filename)).toURI()).toURL(); } catch (IOException e) { System.out.println(e); System.out.println(filename + " not found"); System.exit(1); } JumbledImageApp jumbler = new JumbledImageApp(); jumbler.buildUI(); f.add(jumbler); f.add(jumbler.jumbleButton,BorderLayout.SOUTH); f.pack(); f.setVisible(true); } }
Maintained by John Loomis, updated Sat Feb 16 17:02:46 2019