// Project: Recursion // Module: hanoi2 // Source code file: DiskDispay.java // Solve Towers of Hanoi puzzle graphically. // Display three pegs and maximum of // eight disks for Towers of Hanoi puzzle. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class MyPanel extends JPanel { private JButton run, reset; private JComboBox cb; private DiskDisplay dd; private int nDisks; private Timer timer; private BufferedReader br; private PrintWriter pw; public MyPanel() { String[] numbers = {"1", "2", "3", "4", "5", "6", "7", "8"}; cb = new JComboBox(numbers); dd = new DiskDisplay(3, timer); cb.setSelectedIndex(2); nDisks = 3; setBackground(Color.white); run = new JButton("Run"); reset = new JButton("Reset"); setLayout(new FlowLayout()); add(cb); add(reset); add(run); ResetD rd = new ResetD(); cb.addActionListener(rd); reset.addActionListener(rd); run.addActionListener(new RunD()); timer = new Timer(1000, new TimerD()); timer.stop(); try { pw = new PrintWriter("hanoi.txt"); } catch(IOException ex) { System.out.println(ex); } } public void paintComponent(Graphics g) { super.paintComponent(g); dd.display(g); } public void hanoi(int n, int from, int to, int aux) { if (n >= 1) { hanoi(n - 1, from, aux, to); pw.println(from + " " + to); hanoi(n - 1, aux, to, from); } } private class RunD implements ActionListener { public void actionPerformed(ActionEvent e) { hanoi(nDisks, 0, 1, 2); pw.close(); try { br = new BufferedReader( new FileReader("hanoi.txt")); } catch(IOException ex) { System.out.println(ex); } timer.start(); } } private class ResetD implements ActionListener { public void actionPerformed(ActionEvent e) { String item; item = (String) cb.getSelectedItem(); nDisks = Integer.parseInt(item); dd = new DiskDisplay(nDisks, timer); repaint(); try { br.close(); pw = new PrintWriter("hanoi.txt"); } catch(IOException ex) { System.out.println(ex); } timer.stop(); } } private class TimerD implements ActionListener { public void actionPerformed(ActionEvent e) { int from, to; String line; try { if ((line = br.readLine()) != null) { from = Integer.parseInt( line.substring(0, 1)); to = Integer.parseInt( line.substring(2)); dd.move(from, to); repaint(); } } catch(IOException ex) { System.out.println(ex); } } } }